ngram
listlengths 0
82k
|
|---|
[] |
[
"database_name: str :keyword callable cls: A custom type or function",
"# type: ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"def get_gremlin_database( self, resource_group_name, # type: str account_name, # type:",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls:",
":type database_name: str :param create_update_gremlin_database_parameters: The parameters to provide for",
"= \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type:",
"# type: Any ): # type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create",
"} error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept = \"application/json\" #",
"None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if",
"type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content",
":return: An instance of LROPoller that returns either None or",
"requests. :param config: Configuration of service client. :param serializer: An",
"= self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"a saved state. :keyword polling: True for ARMPolling, False for",
"client. :param serializer: An object model serializer. :param deserializer: An",
"Any ): # type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin",
"type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content",
"the direct response :return: ThroughputSettingsGetResults, or the result of cls(response)",
"= \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type:",
"# type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str',",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def get_gremlin_graph( self, resource_group_name, #",
":param config: Configuration of service client. :param serializer: An object",
"error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError }",
"ignore def _delete_gremlin_database_initial( self, resource_group_name, # type: str account_name, #",
"# type: Any ): # type: (...) -> None cls",
"pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'}",
"min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters",
"# type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata =",
"ignore def begin_delete_gremlin_graph( self, resource_group_name, # type: str account_name, #",
"direct response :return: An iterator like instance of either GremlinDatabaseListResult",
"config def list_gremlin_databases( self, resource_group_name, # type: str account_name, #",
"= \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type:",
"def begin_delete_gremlin_database( self, resource_group_name, # type: str account_name, # type:",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'}",
"ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token',",
"_update_gremlin_database_throughput_initial( self, resource_group_name, # type: str account_name, # type: str",
"self._serialize.query(\"api_version\", api_version, 'str') # Construct headers header_parameters = {} #",
"\"2020-04-01\" # Construct URL url = self._delete_gremlin_graph_initial.metadata['url'] # type: ignore",
"# type: str account_name, # type: str database_name, # type:",
"type: ClsType[\"models.GremlinGraphListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from",
"pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return",
"self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code ==",
"\"\"\" models = models def __init__(self, client, config, serializer, deserializer):",
"type: Optional[str] if cont_token is None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name,",
"= kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401:",
"\"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map =",
"begin_update_gremlin_database_throughput( self, resource_group_name, # type: str account_name, # type: str",
"if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response,",
"return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem =",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata =",
"= \"application/json\" # Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type:",
"azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import",
"graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A custom type",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database.metadata",
"not next_link: # Construct URL url = self.list_gremlin_graphs.metadata['url'] # type:",
"databases under an existing Azure Cosmos DB database account. :param",
"Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom",
"Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay",
"polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_database_to_manual_throughput_initial(",
"PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay =",
"object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod",
"Any ): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type:",
"raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs",
"if not next_link: # Construct URL url = self.list_gremlin_databases.metadata['url'] #",
"type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name,",
"type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any ): # type: (...)",
"result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling =",
"HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _create_update_gremlin_database_initial( self, resource_group_name,",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata =",
"# type: Any ): # type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls",
"ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse",
"type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type: str account_name,",
"autoscale to manual throughput. :param resource_group_name: The name of the",
"# Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments",
":param serializer: An object model serializer. :param deserializer: An object",
"DB database name. :type database_name: str :param create_update_gremlin_database_parameters: The parameters",
"if cont_token is None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None]",
"get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def",
"): # type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an",
"DB Gremlin graph from autoscale to manual throughput. :param resource_group_name:",
":type database_name: str :param graph_name: Cosmos DB graph name. :type",
"a Client instance that instantiates it for you and attaches",
"= {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type,",
"throughput under an existing Azure Cosmos DB database account with",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url':",
"# type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an Azure",
"return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'}",
"provide for the current Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword",
"\"\"\"Gets the Gremlin graph throughput under an existing Azure Cosmos",
"get_gremlin_graph( self, resource_group_name, # type: str account_name, # type: str",
"if cont_token is None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), } url =",
"type: ignore def _delete_gremlin_graph_initial( self, resource_group_name, # type: str account_name,",
"that returns either GremlinDatabaseGetResults or the result of cls(response) :rtype:",
"= self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs )",
"type: Any ): # type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or",
"ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type: str account_name, #",
"# type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None) #",
"ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"the direct response :keyword str continuation_token: A continuation token to",
"# type: ignore def begin_delete_gremlin_database( self, resource_group_name, # type: str",
"direct response :keyword str continuation_token: A continuation token to restart",
"instance of LROPoller that returns either ThroughputSettingsGetResults or the result",
"An object model deserializer. \"\"\" models = models def __init__(self,",
"cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} #",
"ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type:",
"{}) return deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore",
"graph name. :type graph_name: str :param update_throughput_parameters: The RUs per",
"deserialized, {}) return deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type:",
"max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'),",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if",
"= self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters,",
"\"\"\"Gets the Gremlin databases under an existing Azure Cosmos DB",
":type graph_name: str :param create_update_gremlin_graph_parameters: The parameters to provide for",
"An iterator like instance of either GremlinGraphListResult or the result",
"import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models",
"Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations.",
"Azure Cosmos DB Gremlin graph from manual throughput to autoscale.",
"or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\"",
"= self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return",
"client, config, serializer, deserializer): self._client = client self._serialize = serializer",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401: ClientAuthenticationError,",
"HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata",
"provide for the current Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword",
"body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url,",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response,",
"URL url = self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = {",
"ignore def _create_update_gremlin_database_initial( self, resource_group_name, # type: str account_name, #",
"an existing Azure Cosmos DB database account. :param resource_group_name: The",
"= kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401:",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url':",
"= self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request",
"**kwargs # type: Any ): # type: (...) -> Optional[\"models.GremlinGraphGetResults\"]",
"ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} #",
"response.status_code == 200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return",
"cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = {",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_create_update_gremlin_graph( self, resource_group_name,",
"database_name, # type: str graph_name, # type: str **kwargs #",
"return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'}",
"is None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda",
"by Microsoft (R) AutoRest Code Generator. # Changes may cause",
"self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized",
"error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata =",
"type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"]",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self.get_gremlin_database_throughput.metadata['url']",
"create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A custom type or function",
"\"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore",
"Any ): # type: (...) -> LROPoller[None] \"\"\"Deletes an existing",
"manual throughput to autoscale. :param resource_group_name: The name of the",
"int polling_interval: Default waiting time between two polls for LRO",
"= Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations",
"= self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters =",
"(...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph under an existing",
"pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments)",
"self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized",
"the Gremlin graph throughput under an existing Azure Cosmos DB",
"**kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code,",
"is None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters,",
"cont_token is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name,",
"provide for the current Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword",
"that will be passed the direct response :return: ThroughputSettingsGetResults, or",
":rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) #",
"self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"type: (...) -> None cls = kwargs.pop('cls', None) # type:",
"Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay",
":return: An instance of LROPoller that returns either ThroughputSettingsGetResults or",
"**kwargs # type: Any ): # type: (...) -> \"models.GremlinDatabaseGetResults\"",
"get_gremlin_database( self, resource_group_name, # type: str account_name, # type: str",
"update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)",
"type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an Azure Cosmos",
"\"application/json\" def prepare_request(next_link=None): # Construct headers header_parameters = {} #",
"raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore",
"should not instantiate this class directly. Instead, you should create",
"header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response",
"polling, or a polling object for personal polling strategy :paramtype",
"ignore def list_gremlin_graphs( self, resource_group_name, # type: str account_name, #",
"ThroughputSettingsGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError:",
"for the current Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable",
"# type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial(",
"self._serialize.query(\"api_version\", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata",
"ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name, # type: str account_name, #",
"models def __init__(self, client, config, serializer, deserializer): self._client = client",
"that returns either GremlinGraphGetResults or the result of cls(response) :rtype:",
"= self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') body_content_kwargs",
"Construct URL url = self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments =",
"if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None):",
"= \"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\" #",
"Azure Cosmos DB Gremlin database from manual throughput to autoscale.",
"# type: (...) -> LROPoller[None] \"\"\"Deletes an existing Azure Cosmos",
"raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs",
"The name of the resource group. The name is case",
"second of the Gremlin database under an existing Azure Cosmos",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if",
"self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in",
"cont_token is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda",
"from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat",
"of either GremlinDatabaseListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult]",
"for the current Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable",
") cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token",
"= config def list_gremlin_databases( self, resource_group_name, # type: str account_name,",
"azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if TYPE_CHECKING: #",
"type: str graph_name, # type: str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\"",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, #",
"= \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type:",
"database. :param resource_group_name: The name of the resource group. The",
"~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} #",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return",
"Cosmos DB Gremlin database from autoscale to manual throughput. :param",
"graph_name, # type: str **kwargs # type: Any ): #",
"NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling",
"\"\"\"Create or update an Azure Cosmos DB Gremlin database. :param",
"import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling",
"str :param database_name: Cosmos DB database name. :type database_name: str",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name,",
"# type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return",
"deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def",
"An instance of LROPoller that returns either ThroughputSettingsGetResults or the",
"parameters to provide for the current Gremlin graph. :type create_update_gremlin_graph_parameters:",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs )",
"= \"application/json\" # Construct URL url = self._create_update_gremlin_database_initial.metadata['url'] # type:",
"accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request,",
"return deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def",
"query_parameters, header_parameters) else: url = next_link query_parameters = {} #",
"in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if",
":raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"]",
"= kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval',",
"LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin graph from manual",
"Azure Cosmos DB Gremlin database. :param resource_group_name: The name of",
"{} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str')",
"database_name: str :param graph_name: Cosmos DB graph name. :type graph_name:",
"self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if",
"Cosmos DB Gremlin graph. :param resource_group_name: The name of the",
"None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None,",
"self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
":raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type: Union[bool,",
"if cont_token is None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda",
"type: ignore def begin_create_update_gremlin_database( self, resource_group_name, # type: str account_name,",
"'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) #",
"return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'}",
":rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) #",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_delete_gremlin_database( self, resource_group_name, #",
"be lost if the code is regenerated. # -------------------------------------------------------------------------- from",
"body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request,",
"_update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_database_throughput( self,",
"RUs per second of the parameters to provide for the",
"Any ): # type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata = {'url':",
"account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
":rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) #",
"\"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases under an existing Azure Cosmos",
"name. :type graph_name: str :param update_throughput_parameters: The RUs per second",
"'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)",
"= self._serialize.header(\"accept\", accept, 'str') body_content_kwargs = {} # type: Dict[str,",
"list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def get_gremlin_graph( self,",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _create_update_gremlin_graph_initial( self, resource_group_name, #",
"the direct response :return: An iterator like instance of either",
"passed the direct response :return: ThroughputSettingsGetResults, or the result of",
"Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments =",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata =",
"response :return: GremlinGraphGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults",
"type: Any ): # type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the",
"polls for LRO operations if no Retry-After header is present.",
"# type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] =",
"-> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per second of the Gremlin",
"type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1),",
"database_name, # type: str graph_name, # type: str create_update_gremlin_graph_parameters, #",
"begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def get_gremlin_database_throughput( self,",
"get_next, extract_data ) list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore",
"self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type:",
"import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest,",
"_delete_gremlin_database_initial( self, resource_group_name, # type: str account_name, # type: str",
"~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]",
"Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay",
"return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'}",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata",
"= {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept,",
"-> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin database from",
"Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph under an existing Azure Cosmos",
"graph throughput under an existing Azure Cosmos DB database account",
"an Azure Cosmos DB Gremlin database from manual throughput to",
"LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin graph from autoscale",
"account_name, # type: str database_name, # type: str graph_name, #",
"\"application/json\") accept = \"application/json\" # Construct URL url = self._create_update_gremlin_graph_initial.metadata['url']",
"prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str,",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None,",
"create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any ): #",
"accept = \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] #",
"polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_graph_to_autoscale_initial(",
"header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\",",
"for license information. # Code generated by Microsoft (R) AutoRest",
"url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an Azure Cosmos DB Gremlin database.",
":return: An instance of LROPoller that returns either GremlinDatabaseGetResults or",
":keyword polling: True for ARMPolling, False for no polling, or",
"Gremlin graph from autoscale to manual throughput. :param resource_group_name: The",
"self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs",
"URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = {",
"or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\"",
"URL url = self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments = {",
"PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller,",
"from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError,",
"header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') body_content_kwargs = {} # type:",
"api_version = \"2020-04-01\" # Construct URL url = self._delete_gremlin_database_initial.metadata['url'] #",
"): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_create_update_gremlin_graph( self, resource_group_name, #",
"URL url = self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments = {",
"# type: Optional[str] if cont_token is None: raw_result = self._update_gremlin_graph_throughput_initial(",
"type: str database_name, # type: str **kwargs # type: Any",
"Azure Cosmos DB Gremlin database from autoscale to manual throughput.",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _create_update_gremlin_database_initial( self, resource_group_name, # type:",
"class directly. Instead, you should create a Client instance that",
"resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50,",
"get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_gremlin_database_throughput_initial( self,",
"map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from",
"of service client. :param serializer: An object model serializer. :param",
"str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any ):",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _create_update_gremlin_graph_initial( self, resource_group_name, # type:",
"# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.",
"insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name, #",
"graph_name, # type: str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs #",
"not instantiate this class directly. Instead, you should create a",
"(...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph under an existing",
"~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type:",
"graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type",
"# type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None) #",
"type: Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name,",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data )",
":return: ThroughputSettingsGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises:",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type:",
"return deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def",
"# type: str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type:",
"type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name,",
"def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"present. :return: An instance of LROPoller that returns either None",
"polling object for personal polling strategy :paramtype polling: bool or",
"return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata = {'url':",
"~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type:",
"disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional,",
"service requests. :param config: Configuration of service client. :param serializer:",
"graph name. :type graph_name: str :keyword callable cls: A custom",
"ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import",
"= { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name,",
"type: ignore def _update_gremlin_database_throughput_initial( self, resource_group_name, # type: str account_name,",
"\"\"\"Update RUs per second of an Azure Cosmos DB Gremlin",
"cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop(",
"None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z:",
"{} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters)",
"kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls:",
"stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200,",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata",
"self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters,",
"will be passed the direct response :keyword str continuation_token: A",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, #",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, #",
"str :param graph_name: Cosmos DB graph name. :type graph_name: str",
"GremlinGraphGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError:",
"return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def",
"{} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters)",
"self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') body_content_kwargs =",
"\"application/json\" # Construct URL url = self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore",
"in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized =",
"update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any ): #",
"raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore",
"PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay =",
"\"2020-04-01\" accept = \"application/json\" def prepare_request(next_link=None): # Construct headers header_parameters",
"# type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"Any ): # type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin",
"{}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_delete_gremlin_graph(",
"-> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second of an Azure Cosmos",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph.metadata",
"be passed the direct response :return: GremlinDatabaseGetResults, or the result",
"in the project root for license information. # Code generated",
"self, resource_group_name, # type: str account_name, # type: str database_name,",
"cls: A custom type or function that will be passed",
"None, {}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def",
"None) # type: Optional[str] if cont_token is None: raw_result =",
"None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword",
"begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def get_gremlin_graph_throughput( self,",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, #",
"pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable,",
"header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.post(url, query_parameters, header_parameters)",
"DB Gremlin database. :param resource_group_name: The name of the resource",
"extract_data ) list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def",
"direct response :return: GremlinDatabaseGetResults, or the result of cls(response) :rtype:",
"instance that instantiates it for you and attaches it as",
"return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'}",
"'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name,",
":type account_name: str :keyword callable cls: A custom type or",
"type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per second of",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata",
"None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda",
"# type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token",
"-> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph throughput under an existing",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name,",
"deserialized, {}) return deserialized if polling is True: polling_method =",
"create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A custom type or function",
"models: ~azure.mgmt.cosmosdb.models :param client: Client for service requests. :param config:",
"DB database account name. :type account_name: str :keyword callable cls:",
"direct response :return: ThroughputSettingsGetResults, or the result of cls(response) :rtype:",
"request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)",
"raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x,",
"ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept = \"application/json\"",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type:",
"cont_token is None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name,",
"accept = \"application/json\" # Construct URL url = self.get_gremlin_database_throughput.metadata['url'] #",
"# type: str **kwargs # type: Any ): # type:",
"= self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem =",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self.get_gremlin_graph.metadata['url']",
"# type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"{}) return deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore",
"the Gremlin databases under an existing Azure Cosmos DB database",
"ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, #",
"type: Any ): # type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls =",
"(...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases under an existing",
"parameters to provide for the current Gremlin database. :type create_update_gremlin_database_parameters:",
"# Construct headers header_parameters = {} # type: Dict[str, Any]",
"kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError,",
"database_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs #",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database_throughput.metadata =",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _create_update_gremlin_database_initial( self, resource_group_name, #",
"Gremlin database. :param resource_group_name: The name of the resource group.",
"is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z:",
"ignore def begin_update_gremlin_database_throughput( self, resource_group_name, # type: str account_name, #",
"self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), } url =",
"current Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A",
"Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType",
"autoscale. :param resource_group_name: The name of the resource group. The",
"is None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda",
"cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} #",
"graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"that will be passed the direct response :keyword str continuation_token:",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url']",
"**kwargs # type: Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"]",
"_migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_database_to_autoscale( self,",
"'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)",
"\"application/json\" # Construct URL url = self._create_update_gremlin_database_initial.metadata['url'] # type: ignore",
"from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling,",
"# type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial(",
"self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"instantiates it for you and attaches it as an attribute.",
"LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second of an Azure Cosmos DB",
"begin_create_update_gremlin_database( self, resource_group_name, # type: str account_name, # type: str",
"account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), }",
"Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A custom",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'}",
"deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_database_throughput(",
"license information. # Code generated by Microsoft (R) AutoRest Code",
"Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.get(url,",
"deserializer: An object model deserializer. \"\"\" models = models def",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_create_update_gremlin_database( self, resource_group_name, # type:",
"Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments =",
"type: str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any",
"Code generated by Microsoft (R) AutoRest Code Generator. # Changes",
"name. :type graph_name: str :param create_update_gremlin_graph_parameters: The parameters to provide",
"cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} #",
"~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map",
":rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) #",
"str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any ):",
"waiting time between two polls for LRO operations if no",
"def _update_gremlin_database_throughput_initial( self, resource_group_name, # type: str account_name, # type:",
"Any ): # type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin",
"accept = \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] #",
"type: Any ): # type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls =",
"DB database name. :type database_name: str :param graph_name: Cosmos DB",
"database from manual throughput to autoscale. :param resource_group_name: The name",
"account_name: Cosmos DB database account name. :type account_name: str :param",
"None, {}) if polling is True: polling_method = ARMPolling(lro_delay, **kwargs)",
"Any ): # type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls',",
"attribute. :ivar models: Alias to model classes used in this",
"# type: ignore def begin_delete_gremlin_graph( self, resource_group_name, # type: str",
"azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from",
"to provide for the current Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters",
"if the code is regenerated. # -------------------------------------------------------------------------- from typing import",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def list_gremlin_graphs( self, resource_group_name,",
"type: ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type: str account_name,",
"_migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self,",
"error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" # Construct URL url =",
"url = self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata = {'url':",
"deserialized = None if response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults',",
"header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if",
"\"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per second of the Gremlin database",
"= {} # type: Dict[str, Any] request = self._client.get(url, query_parameters,",
"~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs )",
"response :return: ThroughputSettingsGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults",
"you should create a Client instance that instantiates it for",
"type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases under an",
"ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" # Construct URL",
"== 200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"to provide for the current Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters",
"type: str graph_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\"",
"Licensed under the MIT License. See License.txt in the project",
"None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401: ClientAuthenticationError, 404:",
"result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls =",
"the RUs per second of the Gremlin database under an",
"def get_gremlin_database_throughput( self, resource_group_name, # type: str account_name, # type:",
"\"2020-04-01\" # Construct URL url = self._delete_gremlin_database_initial.metadata['url'] # type: ignore",
"self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs )",
"Retry-After header is present. :return: An instance of LROPoller that",
"database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters",
"None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return",
"self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"\"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any ): # type: (...) ->",
"the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls",
"str **kwargs # type: Any ): # type: (...) ->",
"DB Gremlin database from autoscale to manual throughput. :param resource_group_name:",
"None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if",
"200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"**path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str,",
"ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"GremlinGraphGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError",
"\"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map =",
"if no Retry-After header is present. :return: An instance of",
"import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T",
"def _create_update_gremlin_graph_initial( self, resource_group_name, # type: str account_name, # type:",
"raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z:",
"RUs per second of an Azure Cosmos DB Gremlin database.",
"Cosmos DB graph name. :type graph_name: str :param create_update_gremlin_graph_parameters: The",
"the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls",
"be passed the direct response :return: ThroughputSettingsGetResults, or the result",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} #",
"update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type or function",
"[202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls:",
"None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z:",
"Construct URL url = self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments =",
"Cosmos DB database name. :type database_name: str :param update_throughput_parameters: The",
"self, resource_group_name, # type: str account_name, # type: str **kwargs",
"the Gremlin graph under an existing Azure Cosmos DB database",
"database_name, # type: str **kwargs # type: Any ): #",
"min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'),",
"ignore def _delete_gremlin_graph_initial( self, resource_group_name, # type: str account_name, #",
"{}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore",
"def begin_update_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, # type:",
"-> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map",
"ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName':",
"provided name. :param resource_group_name: The name of the resource group.",
"to manual throughput. :param resource_group_name: The name of the resource",
"Optional[str] if cont_token is None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name,",
"None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401: ClientAuthenticationError, 404:",
"will be passed the direct response :return: GremlinGraphGetResults, or the",
"# type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"= pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response,",
"_update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_graph_throughput( self,",
"deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {})",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} #",
"= self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response",
"result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling =",
"Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept']",
"type: str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any",
"AutoRest Code Generator. # Changes may cause incorrect behavior and",
"graph_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def get_gremlin_database_throughput( self, resource_group_name, # type:",
"LRO operations if no Retry-After header is present. :return: An",
"not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return",
"Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.post(url,",
"self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response",
"Construct URL url = self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments =",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _delete_gremlin_database_initial( self, resource_group_name, # type:",
"# type: ignore def _delete_gremlin_graph_initial( self, resource_group_name, # type: str",
"error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept = \"application/json\" def prepare_request(next_link=None):",
"or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\"",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval',",
"database_name: Cosmos DB database name. :type database_name: str :param update_throughput_parameters:",
"~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls",
"resource_group_name: str :param account_name: Cosmos DB database account name. :type",
"Any ): # type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls',",
"deserializer. \"\"\" models = models def __init__(self, client, config, serializer,",
"polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls =",
"kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401: ClientAuthenticationError,",
"or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\"",
"like instance of either GremlinDatabaseListResult or the result of cls(response)",
"api_version = \"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\"",
"DB database name. :type database_name: str :keyword callable cls: A",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata",
"name. :type account_name: str :keyword callable cls: A custom type",
"service client. :param serializer: An object model serializer. :param deserializer:",
"~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type:",
"passed the direct response :keyword str continuation_token: A continuation token",
"or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\"",
") kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults',",
"**kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized =",
"LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import",
"\"\"\"Gets the Gremlin graph under an existing Azure Cosmos DB",
"ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if",
"serializer: An object model serializer. :param deserializer: An object model",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200:",
"self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult',",
"database account name. :type account_name: str :param database_name: Cosmos DB",
"url = self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"serializer. :param deserializer: An object model deserializer. \"\"\" models =",
"Azure Cosmos DB database account with the provided name. :param",
"return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'}",
"cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} #",
"get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _update_gremlin_graph_throughput_initial( self,",
"manual throughput. :param resource_group_name: The name of the resource group.",
"name. :type account_name: str :param database_name: Cosmos DB database name.",
"ThroughputSettingsGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError",
"cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} #",
"time between two polls for LRO operations if no Retry-After",
"\"application/json\" # Construct URL url = self.get_gremlin_graph_throughput.metadata['url'] # type: ignore",
"result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling =",
"ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401:",
"# Construct URL url = self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments",
"get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is",
"type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token =",
"Cosmos DB Gremlin graph from autoscale to manual throughput. :param",
"LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin database from autoscale",
"this class directly. Instead, you should create a Client instance",
"# type: ignore def _delete_gremlin_database_initial( self, resource_group_name, # type: str",
"header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') if not next_link: # Construct",
"create_update_gremlin_database_parameters: The parameters to provide for the current Gremlin database.",
"# type: Any ): # type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists",
"{ 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {}))",
"type: ignore def begin_delete_gremlin_database( self, resource_group_name, # type: str account_name,",
"Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay",
"\"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any ): # type: (...) ->",
"polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _delete_gremlin_graph_initial(",
"\"application/json\" # Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore",
"~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type:",
"deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type:",
"# type: ignore def _create_update_gremlin_database_initial( self, resource_group_name, # type: str",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} #",
"graph_name: str :keyword callable cls: A custom type or function",
"{}) return deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore",
"= kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\" # Construct URL url",
"get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def",
"type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"# type: Optional[str] if cont_token is None: raw_result = self._update_gremlin_database_throughput_initial(",
"cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = {",
"existing Azure Cosmos DB Gremlin graph. :param resource_group_name: The name",
"Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.get(url, query_parameters,",
"None if response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_delete_gremlin_database( self, resource_group_name, # type:",
"= TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]",
"str continuation_token: A continuation token to restart a poller from",
"kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401: ClientAuthenticationError,",
"'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), } url",
"**kwargs) elif polling is False: polling_method = NoPolling() else: polling_method",
"token to restart a poller from a saved state. :keyword",
".. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing",
"accept = \"application/json\" # Construct URL url = self.get_gremlin_database.metadata['url'] #",
"= \"2020-04-01\" # Construct URL url = self._delete_gremlin_database_initial.metadata['url'] # type:",
"the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name, # type:",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response)",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name,",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def get_gremlin_graph_throughput( self, resource_group_name, # type:",
"'str') # Construct headers header_parameters = {} # type: Dict[str,",
"**kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls:",
"cont_token is None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name,",
"ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\",",
"cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None)",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type:",
"it for you and attaches it as an attribute. :ivar",
"= ARMPolling(lro_delay, **kwargs) elif polling is False: polling_method = NoPolling()",
"for ARMPolling, False for no polling, or a polling object",
"= self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs",
"query_parameters = {} # type: Dict[str, Any] request = self._client.get(url,",
"**kwargs # type: Any ): # type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"]",
"ignore def get_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, #",
"if response.status_code == 200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls:",
"DB database account name. :type account_name: str :param database_name: Cosmos",
"Changes may cause incorrect behavior and will be lost if",
"type: Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an",
"Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str,",
"404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\"",
"deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem",
"state. :keyword polling: True for ARMPolling, False for no polling,",
"raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore",
"= \"application/json\" # Construct URL url = self.get_gremlin_database.metadata['url'] # type:",
":type graph_name: str :param update_throughput_parameters: The RUs per second of",
"URL url = self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = {",
"True: polling_method = ARMPolling(lro_delay, **kwargs) elif polling is False: polling_method",
"def _delete_gremlin_database_initial( self, resource_group_name, # type: str account_name, # type:",
"type: ignore def get_gremlin_graph( self, resource_group_name, # type: str account_name,",
"Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map =",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_graph_throughput( self, resource_group_name, #",
"str account_name, # type: str database_name, # type: str create_update_gremlin_database_parameters,",
"\"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph throughput under an existing Azure",
"): # type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None)",
"~azure.mgmt.cosmosdb.models :param client: Client for service requests. :param config: Configuration",
"polling_method = NoPolling() else: polling_method = polling if cont_token: return",
"ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" content_type = kwargs.pop(\"content_type\",",
"deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer",
"Default waiting time between two polls for LRO operations if",
"type: (...) -> LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB",
"the current Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls:",
"Instead, you should create a Client instance that instantiates it",
"MIT License. See License.txt in the project root for license",
"type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type: str account_name,",
"self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"= pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map)",
"{}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore",
"pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\",",
"operation group. :type models: ~azure.mgmt.cosmosdb.models :param client: Client for service",
"type: str database_name, # type: str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\"",
"self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult',",
"= self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return",
"HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"update an Azure Cosmos DB Gremlin database. :param resource_group_name: The",
"self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"= self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized =",
"or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\"",
"database name. :type database_name: str :param graph_name: Cosmos DB graph",
"= kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval',",
"instantiate this class directly. Instead, you should create a Client",
"the direct response :return: GremlinGraphGetResults, or the result of cls(response)",
"either GremlinDatabaseListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises:",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url':",
"cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True)",
"cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True)",
"content_type = kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\" # Construct URL",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_graph_throughput( self, resource_group_name, # type:",
"azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import",
"kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls:",
"HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import",
"self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem)",
"Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version']",
"iterator like instance of either GremlinGraphListResult or the result of",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url']",
"name of the resource group. The name is case insensitive.",
"= self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters,",
"for you and attaches it as an attribute. :ivar models:",
":rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) #",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata =",
"database_name: str :param create_update_gremlin_database_parameters: The parameters to provide for the",
"create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)",
"\"application/json\" # Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore",
"\"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph under an existing Azure Cosmos",
"kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response)",
"None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x,",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url']",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type:",
"URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = {",
"return cls(pipeline_response, deserialized, {}) return deserialized if polling is True:",
"no Retry-After header is present. :return: An instance of LROPoller",
"azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling",
"def list_gremlin_databases( self, resource_group_name, # type: str account_name, # type:",
"def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, # type:",
"query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters)",
"as an attribute. :ivar models: Alias to model classes used",
"return ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} #",
"_delete_gremlin_graph_initial( self, resource_group_name, # type: str account_name, # type: str",
"LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB Gremlin graph. :param",
"if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else:",
"All rights reserved. # Licensed under the MIT License. See",
"An iterator like instance of either GremlinDatabaseListResult or the result",
"[200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults',",
"= self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"-> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases under an existing Azure",
"lost if the code is regenerated. # -------------------------------------------------------------------------- from typing",
"# Construct URL url = self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments",
"database_name: str :param update_throughput_parameters: The RUs per second of the",
"body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url,",
"**kwargs # type: Any ): # type: (...) -> \"models.ThroughputSettingsGetResults\"",
"self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters,",
"account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'}",
"ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"-> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin graph from",
"of an Azure Cosmos DB Gremlin graph. :param resource_group_name: The",
"of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling',",
"# Construct URL url = self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments",
"is True: polling_method = ARMPolling(lro_delay, **kwargs) elif polling is False:",
"is False: polling_method = NoPolling() else: polling_method = polling if",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata",
"the parameters to provide for the current Gremlin graph. :type",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = {",
"= \"application/json\" # Construct URL url = self.get_gremlin_graph_throughput.metadata['url'] # type:",
"of the parameters to provide for the current Gremlin database.",
"_update_gremlin_graph_throughput_initial( self, resource_group_name, # type: str account_name, # type: str",
"Dict[str, Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should not",
"None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x,",
"Code Generator. # Changes may cause incorrect behavior and will",
"_create_update_gremlin_graph_initial( self, resource_group_name, # type: str account_name, # type: str",
"# type: Any ): # type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create",
"result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls =",
"# type: Any ): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets",
"type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"function that will be passed the direct response :return: ThroughputSettingsGetResults,",
"attaches it as an attribute. :ivar models: Alias to model",
"accept = \"application/json\" # Construct URL url = self.get_gremlin_graph_throughput.metadata['url'] #",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_graph_throughput( self, resource_group_name,",
"of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling',",
"for the current Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable",
"RUs per second of an Azure Cosmos DB Gremlin graph.",
"self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'),",
"deserialized = None if response.status_code == 200: deserialized = self._deserialize('GremlinDatabaseGetResults',",
"raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore",
"URL url = self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments = {",
"function that will be passed the direct response :return: GremlinGraphGetResults,",
":raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"]",
"Cosmos DB database name. :type database_name: str :param graph_name: Cosmos",
"ignore def begin_create_update_gremlin_graph( self, resource_group_name, # type: str account_name, #",
":param account_name: Cosmos DB database account name. :type account_name: str",
"= {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters,",
"): # type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph",
"# type: ignore def get_gremlin_graph( self, resource_group_name, # type: str",
"result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls =",
"def list_gremlin_graphs( self, resource_group_name, # type: str account_name, # type:",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type:",
"pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url",
"type: ignore def list_gremlin_graphs( self, resource_group_name, # type: str account_name,",
"name. :param resource_group_name: The name of the resource group. The",
"Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') # Construct headers",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name,",
"not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat)",
"from autoscale to manual throughput. :param resource_group_name: The name of",
"cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} #",
"# type: Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_graph_initial(",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database.metadata = {'url':",
":type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type or",
"either GremlinDatabaseGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises",
"type: Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs",
"# type: ignore def begin_create_update_gremlin_database( self, resource_group_name, # type: str",
"url = self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version",
"typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError,",
"# type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') if",
"cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True)",
"= kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401:",
":rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) #",
"object model serializer. :param deserializer: An object model deserializer. \"\"\"",
"Cosmos DB Gremlin database from manual throughput to autoscale. :param",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type:",
"[200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults',",
"\"\"\"Migrate an Azure Cosmos DB Gremlin graph from manual throughput",
"None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return",
"cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} #",
"type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content",
"'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False,",
"continuation_token: A continuation token to restart a poller from a",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata =",
"an Azure Cosmos DB Gremlin database from autoscale to manual",
"begin_delete_gremlin_graph( self, resource_group_name, # type: str account_name, # type: str",
"Construct URL url = self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments =",
"-> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases under an existing Azure",
"an existing Azure Cosmos DB Gremlin database. :param resource_group_name: The",
"# type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases under",
"ignore def begin_delete_gremlin_database( self, resource_group_name, # type: str account_name, #",
"polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def list_gremlin_graphs(",
"request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized",
"An instance of LROPoller that returns either GremlinDatabaseGetResults or the",
"the Gremlin database under an existing Azure Cosmos DB database",
"name. :type database_name: str :param update_throughput_parameters: The RUs per second",
"account_name, # type: str database_name, # type: str update_throughput_parameters, #",
"# type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None) #",
"self._serialize.header(\"accept\", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response =",
"graph from manual throughput to autoscale. :param resource_group_name: The name",
"group. :type models: ~azure.mgmt.cosmosdb.models :param client: Client for service requests.",
"'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3,",
"current Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A",
"cls(pipeline_response, None, {}) if polling is True: polling_method = ARMPolling(lro_delay,",
") kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return",
"= \"application/json\" def prepare_request(next_link=None): # Construct headers header_parameters = {}",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map = {",
"get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response =",
"# type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph throughput",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata",
":type models: ~azure.mgmt.cosmosdb.models :param client: Client for service requests. :param",
"account name. :type account_name: str :keyword callable cls: A custom",
":return: GremlinGraphGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises:",
"of LROPoller that returns either None or the result of",
"if cont_token is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"Configuration of service client. :param serializer: An object model serializer.",
"deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_graph_to_manual_throughput(",
"type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any ): # type: (...)",
"begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_database_to_autoscale_initial( self,",
"\"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any ): # type: (...) ->",
"# type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial(",
"x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if",
"used in this operation group. :type models: ~azure.mgmt.cosmosdb.models :param client:",
"Gremlin database under an existing Azure Cosmos DB database account",
"**kwargs) response = pipeline_response.http_response if response.status_code not in [202, 204]:",
"polling_interval: Default waiting time between two polls for LRO operations",
"not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized",
"TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict,",
"Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name,",
"None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval )",
") list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def get_gremlin_graph(",
"# type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph under",
"of either GremlinGraphListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult]",
"begin_update_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, # type: str",
"not next_link: # Construct URL url = self.list_gremlin_databases.metadata['url'] # type:",
"database_name: Cosmos DB database name. :type database_name: str :param create_update_gremlin_database_parameters:",
"# type: ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type: str",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"type: Any ): # type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls =",
"with the provided name. :param resource_group_name: The name of the",
"returns either ThroughputSettingsGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]",
"= deserializer self._config = config def list_gremlin_databases( self, resource_group_name, #",
"Gremlin databases under an existing Azure Cosmos DB database account.",
"deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type:",
"update_throughput_parameters: The RUs per second of the parameters to provide",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata =",
"**kwargs # type: Any ): # type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"]",
"account name. :type account_name: str :param database_name: Cosmos DB database",
"header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem",
"# type: str graph_name, # type: str create_update_gremlin_graph_parameters, # type:",
"account with the provided name. :param resource_group_name: The name of",
"= {} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters')",
"begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type: str account_name, # type: str",
"kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {})",
"min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), } url = self._client.format_url(url,",
"cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} #",
"the parameters to provide for the current Gremlin database. :type",
"type: Any ): # type: (...) -> LROPoller[None] \"\"\"Deletes an",
"URL url = self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = {",
"database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type",
"cont_token is None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name,",
"# Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments",
"deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type:",
"\"application/json\") accept = \"application/json\" # Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url']",
"# type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token",
"begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def list_gremlin_graphs( self,",
"Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments =",
"query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response",
"(...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]]",
"None if response.status_code == 200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if",
"return deserialized if polling is True: polling_method = ARMPolling(lro_delay, **kwargs)",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map = { 401: ClientAuthenticationError,",
"{}) return deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore",
"**kwargs # type: Any ): # type: (...) -> LROPoller[None]",
"LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin database from manual",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database_throughput.metadata",
"type: ignore def _delete_gremlin_database_initial( self, resource_group_name, # type: str account_name,",
"[200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return",
"operations. You should not instantiate this class directly. Instead, you",
"HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs )",
"'str') if not next_link: # Construct URL url = self.list_gremlin_databases.metadata['url']",
"str account_name, # type: str database_name, # type: str **kwargs",
"): # type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None)",
"= self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.get(url, query_parameters, header_parameters)",
"begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self,",
":type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A custom type or",
"min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName':",
"type: Any ): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the",
"if cont_token is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def get_gremlin_graph_throughput( self, resource_group_name,",
"Any ): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs",
"See License.txt in the project root for license information. #",
"_create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_create_update_gremlin_graph( self,",
"ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version =",
"self._serialize.url(\"database_name\", database_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct",
"that instantiates it for you and attaches it as an",
"url = self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\"",
"= {} # type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters')",
"return cls(pipeline_response, None, {}) if polling is True: polling_method =",
"pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map)",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url':",
"content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') body_content_kwargs = {}",
"database name. :type database_name: str :param update_throughput_parameters: The RUs per",
"~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type:",
"object model deserializer. \"\"\" models = models def __init__(self, client,",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def get_gremlin_graph_throughput( self, resource_group_name, #",
"Client instance that instantiates it for you and attaches it",
"Client for service requests. :param config: Configuration of service client.",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _delete_gremlin_graph_initial( self, resource_group_name, #",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls:",
"raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x,",
"information. # Code generated by Microsoft (R) AutoRest Code Generator.",
"# type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') #",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url':",
"url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database_throughput.metadata = {'url':",
"type: ignore def begin_update_gremlin_graph_throughput( self, resource_group_name, # type: str account_name,",
":type account_name: str :param database_name: Cosmos DB database name. :type",
"graph from autoscale to manual throughput. :param resource_group_name: The name",
"The RUs per second of the parameters to provide for",
"deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type:",
"Cosmos DB Gremlin graph from manual throughput to autoscale. :param",
"error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\") accept",
"name. :type graph_name: str :keyword callable cls: A custom type",
"Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request =",
"= {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version,",
"= self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"\"application/json\" # Construct URL url = self.get_gremlin_database_throughput.metadata['url'] # type: ignore",
"Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name,",
"ARMPolling from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports",
"URL url = self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments = {",
"model serializer. :param deserializer: An object model deserializer. \"\"\" models",
"url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {}",
"type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None) # type:",
"def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type: str account_name, # type:",
"# Changes may cause incorrect behavior and will be lost",
"~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A custom type or function that",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _delete_gremlin_graph_initial( self, resource_group_name, # type:",
"personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int",
"deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _update_gremlin_graph_throughput_initial(",
"begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type: str account_name, # type: str",
"# Construct URL url = self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments",
"# type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type: str",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def get_gremlin_database( self, resource_group_name, #",
"in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized",
"if cls: return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'}",
"raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x,",
"type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request",
"Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_database_throughput( self, resource_group_name,",
"= self._serialize.query(\"api_version\", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else:",
"# type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second of",
"An object model serializer. :param deserializer: An object model deserializer.",
"cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True)",
"model classes used in this operation group. :type models: ~azure.mgmt.cosmosdb.models",
"accept = \"application/json\" # Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url'] #",
"parameters to provide for the current Gremlin database. :type update_throughput_parameters:",
"parameters to provide for the current Gremlin graph. :type update_throughput_parameters:",
"get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def",
"from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport",
"{} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content']",
":keyword int polling_interval: Default waiting time between two polls for",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type:",
"# type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases under",
"# type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any ): # type:",
"graph_name=graph_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)",
":param database_name: Cosmos DB database name. :type database_name: str :keyword",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = {",
"root for license information. # Code generated by Microsoft (R)",
"# type: Any ): # type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets",
"str database_name, # type: str graph_name, # type: str create_update_gremlin_graph_parameters,",
"or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'}",
"cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = {",
"= self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs",
"config: Configuration of service client. :param serializer: An object model",
"self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str',",
":keyword str continuation_token: A continuation token to restart a poller",
"409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept =",
"= self._serialize.header(\"accept\", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response",
"= kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401:",
"if response.status_code == 200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls:",
"deserializer self._config = config def list_gremlin_databases( self, resource_group_name, # type:",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any ):",
"is None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z:",
"account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments)",
"# type: str database_name, # type: str update_throughput_parameters, # type:",
"that returns either ThroughputSettingsGetResults or the result of cls(response) :rtype:",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self.get_gremlin_graph_throughput.metadata['url']",
"Cosmos DB database account name. :type account_name: str :param database_name:",
":rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) #",
"account_name: str :param database_name: Cosmos DB database name. :type database_name:",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response)",
"): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph",
"cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method",
"def prepare_request(next_link=None): # Construct headers header_parameters = {} # type:",
"response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response,",
"\"application/json\" # Construct URL url = self.get_gremlin_graph.metadata['url'] # type: ignore",
"Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request",
"passed the direct response :return: An iterator like instance of",
"header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str')",
"per second of the parameters to provide for the current",
"error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"header is present. :return: An instance of LROPoller that returns",
"get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def",
"Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType =",
"no polling, or a polling object for personal polling strategy",
"return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def",
"an Azure Cosmos DB Gremlin graph from autoscale to manual",
":type database_name: str :keyword callable cls: A custom type or",
"DB database account. :param resource_group_name: The name of the resource",
"error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized =",
"import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error",
"None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval )",
"classes used in this operation group. :type models: ~azure.mgmt.cosmosdb.models :param",
"type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None) # type:",
"-------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import",
"min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), }",
"url = self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"True for ARMPolling, False for no polling, or a polling",
"self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response =",
"the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_create_update_gremlin_database( self, resource_group_name, #",
"database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None) # type:",
"Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should not instantiate",
"_migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, # type: str",
"cont_token is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name,",
"URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = {",
"deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type:",
"deserialized, {}) return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type:",
"cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response",
"(...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin graph",
"error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x,",
"None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401: ClientAuthenticationError, 404:",
"None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError:",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response)",
"of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling',",
"\"\"\"Migrate an Azure Cosmos DB Gremlin database from autoscale to",
"existing Azure Cosmos DB database account with the provided name.",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} #",
"\"\"\"Migrate an Azure Cosmos DB Gremlin database from manual throughput",
"[200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults',",
"DB Gremlin graph from manual throughput to autoscale. :param resource_group_name:",
"TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class",
"extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value if cls:",
"def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value if",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url':",
"an Azure Cosmos DB Gremlin graph. :param resource_group_name: The name",
"account_name: Cosmos DB database account name. :type account_name: str :keyword",
"Azure Cosmos DB database account. :param resource_group_name: The name of",
"= kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls',",
"url = self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map = { 401:",
"create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)",
"returns either GremlinGraphGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults]",
"account_name, # type: str database_name, # type: str **kwargs #",
"# type: Any ): # type: (...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls",
"_delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_delete_gremlin_database( self,",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} #",
"behavior and will be lost if the code is regenerated.",
"type: str **kwargs # type: Any ): # type: (...)",
"get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response",
"deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type:",
"~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A custom type or function that",
"LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB Gremlin database. :param",
"the direct response :return: GremlinDatabaseGetResults, or the result of cls(response)",
"type: str database_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\"",
"None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return",
"database name. :type database_name: str :param create_update_gremlin_database_parameters: The parameters to",
"or update an Azure Cosmos DB Gremlin graph. :param resource_group_name:",
"self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters,",
"deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_create_update_gremlin_graph(",
"list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def get_gremlin_database( self,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _delete_gremlin_database_initial( self, resource_group_name,",
"type: Any ): # type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the",
"raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore",
"error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata =",
"ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from",
"Azure Cosmos DB Gremlin graph. :param resource_group_name: The name of",
"= self._serialize.query(\"api_version\", api_version, 'str') # Construct headers header_parameters = {}",
"continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method)",
"# type: ClsType[\"models.GremlinGraphListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"callable cls: A custom type or function that will be",
"kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response)",
"ARMPolling(lro_delay, **kwargs) elif polling is False: polling_method = NoPolling() else:",
"= models def __init__(self, client, config, serializer, deserializer): self._client =",
"result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls =",
"= \"application/json\" # Construct URL url = self.get_gremlin_database_throughput.metadata['url'] # type:",
"current Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A",
":type database_name: str :param update_throughput_parameters: The RUs per second of",
"{}) if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) elif",
"str :param account_name: Cosmos DB database account name. :type account_name:",
"# Construct URL url = self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments",
":param resource_group_name: The name of the resource group. The name",
"type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"graph_name: str :param create_update_gremlin_graph_parameters: The parameters to provide for the",
"cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def",
"Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect",
"cont_token is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(",
"\"\"\"Gets the RUs per second of the Gremlin database under",
"): # type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per",
"\"application/json\" # Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore",
"None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request,",
"resource_group_name, # type: str account_name, # type: str **kwargs #",
"Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map =",
"get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"# type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response",
"graph_name: Cosmos DB graph name. :type graph_name: str :param create_update_gremlin_graph_parameters:",
"'str') body_content_kwargs = {} # type: Dict[str, Any] body_content =",
"= None if response.status_code == 200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response)",
"accept = \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] #",
"URL url = self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments = {",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling",
"# Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments",
"DB database account with the provided name. :param resource_group_name: The",
"(...) -> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]]",
"header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem",
"# type: ignore def begin_update_gremlin_database_throughput( self, resource_group_name, # type: str",
"continuation token to restart a poller from a saved state.",
"instance of either GremlinGraphListResult or the result of cls(response) :rtype:",
"Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per",
"_create_update_gremlin_database_initial( self, resource_group_name, # type: str account_name, # type: str",
"): # type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None)",
"return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response =",
"stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]:",
"= self._serialize.header(\"accept\", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type:",
"Cosmos DB database name. :type database_name: str :keyword callable cls:",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def get_gremlin_database( self, resource_group_name, # type:",
"self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"\"\"\"Lists the Gremlin graph under an existing Azure Cosmos DB",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if",
"raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore",
"ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token',",
"def begin_update_gremlin_database_throughput( self, resource_group_name, # type: str account_name, # type:",
":keyword callable cls: A custom type or function that will",
"self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type:",
"str graph_name, # type: str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs",
"ignore def get_gremlin_database_throughput( self, resource_group_name, # type: str account_name, #",
"cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return",
"per second of an Azure Cosmos DB Gremlin database. :param",
"ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token',",
"error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept = \"application/json\" # Construct",
"url = self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type:",
"def get_gremlin_graph( self, resource_group_name, # type: str account_name, # type:",
"URL url = self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments = {",
"either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises",
"'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name,",
"= self._serialize.header(\"accept\", accept, 'str') if not next_link: # Construct URL",
"url = self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"# type: ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name, # type: str",
"cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore",
"polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output )",
"def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type: str account_name, # type:",
"self._config = config def list_gremlin_databases( self, resource_group_name, # type: str",
":rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) #",
"Construct headers header_parameters = {} # type: Dict[str, Any] request",
"self._serialize = serializer self._deserialize = deserializer self._config = config def",
"deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_gremlin_database_throughput_initial(",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name,",
"= self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x,",
"that will be passed the direct response :return: GremlinGraphGetResults, or",
"type: ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type: str account_name,",
"# type: Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update",
"{ 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str',",
"models: Alias to model classes used in this operation group.",
"None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z:",
"accept = \"application/json\" # Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] #",
"the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling",
"HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions",
"None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401: ClientAuthenticationError, 404:",
"instance of LROPoller that returns either GremlinDatabaseGetResults or the result",
"type: ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type: str account_name,",
"= self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs )",
"deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem",
"{} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str')",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_create_update_gremlin_graph( self, resource_group_name, # type:",
"elif polling is False: polling_method = NoPolling() else: polling_method =",
"begin_delete_gremlin_database( self, resource_group_name, # type: str account_name, # type: str",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop(",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def list_gremlin_graphs( self, resource_group_name, # type:",
"generated by Microsoft (R) AutoRest Code Generator. # Changes may",
"name. :type database_name: str :param create_update_gremlin_database_parameters: The parameters to provide",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _create_update_gremlin_graph_initial( self, resource_group_name,",
"models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any,",
"def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'}",
"self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs",
"# type: ignore def _create_update_gremlin_graph_initial( self, resource_group_name, # type: str",
"_create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_create_update_gremlin_database( self,",
"self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response =",
"\"application/json\" # Construct URL url = self.get_gremlin_database.metadata['url'] # type: ignore",
"deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {})",
"be passed the direct response :return: GremlinGraphGetResults, or the result",
"DB graph name. :type graph_name: str :param update_throughput_parameters: The RUs",
"type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name,",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata =",
"} error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept = \"application/json\" def",
"'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False,",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self.get_gremlin_database.metadata['url']",
"return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem =",
"URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments = {",
"self._serialize.header(\"accept\", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any]",
"{})) api_version = \"2020-04-01\" accept = \"application/json\" def prepare_request(next_link=None): #",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name,",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"License. See License.txt in the project root for license information.",
"self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {}",
"create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any ): #",
"(...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin database",
"cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None)",
"type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name,",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} #",
"None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401: ClientAuthenticationError, 404:",
"of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls',",
"operations if no Retry-After header is present. :return: An instance",
"} error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" # Construct URL url",
"api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url =",
"= self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"second of the parameters to provide for the current Gremlin",
"Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request = self._client.post(url, query_parameters,",
"extract_data ) list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def get_gremlin_database_throughput( self, resource_group_name,",
"ignore def begin_create_update_gremlin_database( self, resource_group_name, # type: str account_name, #",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url':",
"Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments =",
"account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token =",
"= serializer self._deserialize = deserializer self._config = config def list_gremlin_databases(",
"database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)",
"will be passed the direct response :return: An iterator like",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def get_gremlin_graph( self, resource_group_name, # type:",
"of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls',",
"existing Azure Cosmos DB database account. :param resource_group_name: The name",
"kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response)",
"): # type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_gremlin_database_throughput_initial( self, resource_group_name, #",
"headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] =",
"polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def get_gremlin_graph_throughput(",
"database name. :type database_name: str :keyword callable cls: A custom",
"accept, 'str') if not next_link: # Construct URL url =",
"\"\"\"Migrate an Azure Cosmos DB Gremlin graph from autoscale to",
"present. :return: An instance of LROPoller that returns either ThroughputSettingsGetResults",
"Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name,",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata",
"raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x,",
"== 200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map",
"deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {})",
"# type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an Azure",
"passed the direct response :return: GremlinDatabaseGetResults, or the result of",
"= NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token(",
"or a polling object for personal polling strategy :paramtype polling:",
"type: Any ): # type: (...) -> None cls =",
"config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize",
"Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\",",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata",
"kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval",
"# type: Any ): # type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls",
"deserialized, {}) return deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type:",
"raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs",
"type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type: str account_name,",
"present. :return: An instance of LROPoller that returns either GremlinGraphGetResults",
"GremlinDatabaseGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError:",
"# type: ignore def get_gremlin_database_throughput( self, resource_group_name, # type: str",
"cls: return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} #",
"**kwargs # type: Any ): # type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"]",
"(...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases under an existing",
"GremlinGraphListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError",
"# -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions",
"cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} #",
"409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" # Construct",
"body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters,",
"type: str account_name, # type: str **kwargs # type: Any",
"request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)",
"# type: ignore def list_gremlin_graphs( self, resource_group_name, # type: str",
"self._deserialize = deserializer self._config = config def list_gremlin_databases( self, resource_group_name,",
"409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" content_type =",
"_migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type: str account_name, # type: str",
"if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) elif polling",
"= \"application/json\" # Construct URL url = self.get_gremlin_graph.metadata['url'] # type:",
"def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, # type:",
"database_name, # type: str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs #",
"deserialized if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) elif",
"-> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph under an existing Azure",
"Optional[str] if cont_token is None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name,",
"return deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def",
"Cosmos DB database account with the provided name. :param resource_group_name:",
"# type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request",
"Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') if not next_link: #",
"get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _create_update_gremlin_graph_initial( self,",
"ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type: str account_name, #",
"database account. :param resource_group_name: The name of the resource group.",
"of LROPoller that returns either ThroughputSettingsGetResults or the result of",
"import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {})",
"): # type: (...) -> None cls = kwargs.pop('cls', None)",
"): # type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph",
"error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata =",
"-> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map",
"-> LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB Gremlin database.",
"of LROPoller that returns either GremlinDatabaseGetResults or the result of",
"response :return: An iterator like instance of either GremlinDatabaseListResult or",
"(...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None]",
"throughput to autoscale. :param resource_group_name: The name of the resource",
"class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should not instantiate this class",
"Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments =",
"= self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second",
"polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial(",
"between two polls for LRO operations if no Retry-After header",
"response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response,",
"database_name: Cosmos DB database name. :type database_name: str :keyword callable",
"The parameters to provide for the current Gremlin graph. :type",
"accept = \"application/json\" # Construct URL url = self._create_update_gremlin_database_initial.metadata['url'] #",
"(...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per second of the",
"extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value if cls:",
"= pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response,",
"polling is True: polling_method = ARMPolling(lro_delay, **kwargs) elif polling is",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls:",
"LROPoller that returns either GremlinGraphGetResults or the result of cls(response)",
"type: ignore def begin_delete_gremlin_graph( self, resource_group_name, # type: str account_name,",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map = { 401: ClientAuthenticationError,",
"HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline",
"type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second of an",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} #",
":rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) #",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database.metadata =",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type:",
"if cont_token is None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata =",
"graph under an existing Azure Cosmos DB database account. :param",
"def begin_create_update_gremlin_database( self, resource_group_name, # type: str account_name, # type:",
"PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay =",
"list_gremlin_databases( self, resource_group_name, # type: str account_name, # type: str",
"Optional[str] if cont_token is None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name,",
"cont_token is None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters,",
"= self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights",
"# type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph under",
"create a Client instance that instantiates it for you and",
"{} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content']",
"'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), } url",
"account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None,",
"cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} #",
"url = self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"if cls: return cls(pipeline_response, None, {}) if polling is True:",
"kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval",
"Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request =",
"= None if response.status_code == 200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response)",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'}",
"ignore def _update_gremlin_database_throughput_initial( self, resource_group_name, # type: str account_name, #",
"and attaches it as an attribute. :ivar models: Alias to",
"str :keyword callable cls: A custom type or function that",
"under the MIT License. See License.txt in the project root",
"URL url = self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments = {",
"= kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) #",
"account_name: str :keyword callable cls: A custom type or function",
"type: Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name,",
"graph_name: Cosmos DB graph name. :type graph_name: str :keyword callable",
"of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls',",
"Any ): # type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update",
"polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_database_to_autoscale_initial(",
"Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name,",
"Gremlin databases under an existing Azure Cosmos DB database account",
"kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls:",
"LROPoller that returns either GremlinDatabaseGetResults or the result of cls(response)",
"= self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response",
"str account_name, # type: str **kwargs # type: Any ):",
"is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda",
"\"application/json\") accept = \"application/json\" # Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url']",
"api_version = \"2020-04-01\" accept = \"application/json\" # Construct URL url",
"polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client,",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, #",
"None, {}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def",
"account_name, # type: str **kwargs # type: Any ): #",
"NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method,",
"type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') request =",
"self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"# type: str account_name, # type: str **kwargs # type:",
"return deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def",
"ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" content_type",
"Construct URL url = self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments =",
"**kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]:",
"result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling =",
"is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings",
"= \"application/json\" # Construct URL url = self._create_update_gremlin_graph_initial.metadata['url'] # type:",
"deserialized _migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_graph_to_autoscale(",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url':",
"PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from",
"{}) return deserialized _create_update_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore",
"GremlinDatabaseListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata =",
"azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_delete_gremlin_graph( self, resource_group_name, #",
"# type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type: str",
"# type: ignore def _update_gremlin_database_throughput_initial( self, resource_group_name, # type: str",
"def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type: str account_name, # type:",
"# type: str graph_name, # type: str **kwargs # type:",
"= prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response",
"ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type: str account_name, #",
"return deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def",
"Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') request = self._client.get(url,",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop(",
"Cosmos DB database account. :param resource_group_name: The name of the",
"def _update_gremlin_graph_throughput_initial( self, resource_group_name, # type: str account_name, # type:",
"error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata = {'url':",
"model deserializer. \"\"\" models = models def __init__(self, client, config,",
"URL url = self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = {",
"raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z:",
"str graph_name, # type: str **kwargs # type: Any ):",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_delete_gremlin_graph( self, resource_group_name, # type:",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name,",
"body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name,",
"str :param create_update_gremlin_graph_parameters: The parameters to provide for the current",
"response :keyword str continuation_token: A continuation token to restart a",
"def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat)",
"{}) return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore",
"# type: ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type: str",
"type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the Gremlin graph under an",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401:",
"if cont_token is None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"# type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token",
":paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting",
"name. :type database_name: str :keyword callable cls: A custom type",
"{}) return deserialized get_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore",
"_migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, # type: str",
"header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url,",
"LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an Azure Cosmos DB Gremlin graph.",
"def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type: str account_name, # type:",
"type: ignore def begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type: str account_name,",
"type: ignore def get_gremlin_database_throughput( self, resource_group_name, # type: str account_name,",
"that will be passed the direct response :return: GremlinDatabaseGetResults, or",
"the current Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls:",
"max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name,",
"str database_name, # type: str graph_name, # type: str update_throughput_parameters,",
"# type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB",
"RUs per second of the Gremlin database under an existing",
"# pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic,",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_gremlin_database_throughput_initial( self, resource_group_name, # type:",
"PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay =",
"list_gremlin_graphs( self, resource_group_name, # type: str account_name, # type: str",
"kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401: ClientAuthenticationError,",
"Gremlin graph throughput under an existing Azure Cosmos DB database",
"name is case insensitive. :type resource_group_name: str :param account_name: Cosmos",
"from a saved state. :keyword polling: True for ARMPolling, False",
"TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError,",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _delete_gremlin_database_initial( self, resource_group_name, #",
"response :return: GremlinDatabaseGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults",
"from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from",
"self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized",
"database under an existing Azure Cosmos DB database account with",
"202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None",
"= body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response =",
"self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"= self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_autoscale.metadata",
"of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls',",
"\"\"\" polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls",
"cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore",
"'accountName': self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url =",
"get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def",
"-> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an Azure Cosmos DB Gremlin",
"accept = \"application/json\" # Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] #",
"Gremlin database from autoscale to manual throughput. :param resource_group_name: The",
"kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response,",
"{} # type: Dict[str, Any] body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content']",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if",
"# type: (...) -> None cls = kwargs.pop('cls', None) #",
"deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _create_update_gremlin_database_initial(",
"get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def",
"# Construct URL url = self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments",
"pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), }",
"database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"def _create_update_gremlin_database_initial( self, resource_group_name, # type: str account_name, # type:",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata =",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_database_throughput( self, resource_group_name, # type:",
"directly. Instead, you should create a Client instance that instantiates",
"DB Gremlin database from manual throughput to autoscale. :param resource_group_name:",
"an Azure Cosmos DB Gremlin graph from manual throughput to",
"second of an Azure Cosmos DB Gremlin database. :param resource_group_name:",
"resource_group_name: The name of the resource group. The name is",
"cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request",
"# type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type:",
"list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request =",
"(...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph throughput under an",
"url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"function that will be passed the direct response :return: An",
"ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class GremlinResourcesOperations(object):",
"type: Optional[str] if cont_token is None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name,",
"accept = \"application/json\" # Construct URL url = self.get_gremlin_graph.metadata['url'] #",
"(...) -> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]]",
"account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName':",
"def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value if",
"client self._serialize = serializer self._deserialize = deserializer self._config = config",
"type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure Cosmos DB Gremlin",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} #",
"self._serialize.url(\"account_name\", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url,",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type:",
"deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type:",
"type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type: Any ): # type: (...)",
"Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name,",
"Construct URL url = self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments =",
"response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code,",
"~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type:",
"ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token',",
":param client: Client for service requests. :param config: Configuration of",
"type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type: str account_name,",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return",
"pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise",
"of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls',",
"ARMPolling, False for no polling, or a polling object for",
"self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response =",
"Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') # Construct headers header_parameters",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def get_gremlin_database( self, resource_group_name,",
"get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def",
"polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def get_gremlin_database_throughput(",
"type: Any ): # type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the",
"'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'), 'accountName':",
"from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar,",
"ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type: str account_name, #",
"type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') request =",
"# Construct URL url = self._migrate_gremlin_database_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments",
") kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ThroughputSettingsGetResults',",
"~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map",
"type: ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"of LROPoller that returns either GremlinGraphGetResults or the result of",
"def begin_delete_gremlin_graph( self, resource_group_name, # type: str account_name, # type:",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata",
"kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None)",
"_migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self,",
"database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"saved state. :keyword polling: True for ARMPolling, False for no",
"of the Gremlin database under an existing Azure Cosmos DB",
"def begin_create_update_gremlin_graph( self, resource_group_name, # type: str account_name, # type:",
"'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]",
"get_gremlin_database_throughput( self, resource_group_name, # type: str account_name, # type: str",
"def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type: str account_name, # type:",
"TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T,",
"cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = {",
"stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [202,",
"if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable,",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map = {",
"resource_group_name, # type: str account_name, # type: str database_name, #",
"= self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"function that will be passed the direct response :keyword str",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def list_gremlin_graphs( self, resource_group_name, #",
"204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type:",
":param update_throughput_parameters: The RUs per second of the parameters to",
"# type: Any ): # type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets",
"self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
":return: An iterator like instance of either GremlinGraphListResult or the",
"(R) AutoRest Code Generator. # Changes may cause incorrect behavior",
"x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response):",
"begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _delete_gremlin_database_initial( self,",
"None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map =",
"type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"]",
"self._serialize.header(\"accept\", accept, 'str') if not next_link: # Construct URL url",
"**kwargs # type: Any ): # type: (...) -> None",
"polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _delete_gremlin_database_initial(",
"an attribute. :ivar models: Alias to model classes used in",
"models = models def __init__(self, client, config, serializer, deserializer): self._client",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata",
"next_link: # Construct URL url = self.list_gremlin_graphs.metadata['url'] # type: ignore",
"to model classes used in this operation group. :type models:",
"T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]],",
"_migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type: str account_name, # type: str",
"type: ignore def get_gremlin_graph_throughput( self, resource_group_name, # type: str account_name,",
"should create a Client instance that instantiates it for you",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata = {'url':",
"= \"2020-04-01\" accept = \"application/json\" # Construct URL url =",
"_delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_delete_gremlin_graph( self,",
"or function that will be passed the direct response :return:",
"pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'}",
"bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between",
"# type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the RUs per second",
"accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request,",
"an existing Azure Cosmos DB Gremlin graph. :param resource_group_name: The",
"a polling object for personal polling strategy :paramtype polling: bool",
"type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any",
"raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore",
"None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x,",
":type graph_name: str :keyword callable cls: A custom type or",
"__init__(self, client, config, serializer, deserializer): self._client = client self._serialize =",
"api_version = \"2020-04-01\" accept = \"application/json\" def prepare_request(next_link=None): # Construct",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata",
"type: (...) -> \"models.ThroughputSettingsGetResults\" \"\"\"Gets the Gremlin graph throughput under",
"-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #",
"deserialized, {}) return deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type:",
"# Construct URL url = self.get_gremlin_database.metadata['url'] # type: ignore path_format_arguments",
"from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging",
":param create_update_gremlin_database_parameters: The parameters to provide for the current Gremlin",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, #",
"name. :type database_name: str :param graph_name: Cosmos DB graph name.",
"GremlinDatabaseGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError",
"request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)",
"from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from",
"incorrect behavior and will be lost if the code is",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata = {'url':",
"header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\",",
"from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from ..",
"Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') if not next_link:",
") kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults',",
"cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None)",
"body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response",
"polling is False: polling_method = NoPolling() else: polling_method = polling",
"-> Optional[\"models.ThroughputSettingsGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map",
"= \"2020-04-01\" accept = \"application/json\" def prepare_request(next_link=None): # Construct headers",
"ignore def _create_update_gremlin_graph_initial( self, resource_group_name, # type: str account_name, #",
"HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized",
"may cause incorrect behavior and will be lost if the",
"Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response):",
"# type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept']",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata",
"if cls: return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'}",
"Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept,",
"type: Any ): # type: (...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'}",
"Azure Cosmos DB Gremlin graph from autoscale to manual throughput.",
"provide for the current Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url':",
"return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client,",
"get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinGraphGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None)",
"is None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda",
"database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A custom type",
"response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response,",
"response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code,",
"cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None)",
"headers header_parameters = {} # type: Dict[str, Any] request =",
"# type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type: str",
"= self._migrate_gremlin_graph_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs",
"if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise",
"= kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None:",
"\"\"\"Create or update an Azure Cosmos DB Gremlin graph. :param",
"Construct URL url = self.list_gremlin_graphs.metadata['url'] # type: ignore path_format_arguments =",
"the project root for license information. # Code generated by",
"} url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters =",
"begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _delete_gremlin_graph_initial( self,",
"Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map =",
"type: str graph_name, # type: str **kwargs # type: Any",
"None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z:",
"# type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] =",
"else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token,",
"headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] =",
"= self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x,",
"# type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') request",
"An instance of LROPoller that returns either GremlinGraphGetResults or the",
"LROPoller that returns either None or the result of cls(response)",
"prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if",
"next_link: # Construct URL url = self.list_gremlin_databases.metadata['url'] # type: ignore",
"# type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters, 'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] =",
"type: ignore def _create_update_gremlin_database_initial( self, resource_group_name, # type: str account_name,",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval',",
"the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling",
"You should not instantiate this class directly. Instead, you should",
"type: str database_name, # type: str graph_name, # type: str",
"passed the direct response :return: GremlinGraphGetResults, or the result of",
"return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type:",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata = {'url':",
"{}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore",
"# type: str database_name, # type: str **kwargs # type:",
"kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type:",
":ivar models: Alias to model classes used in this operation",
"resource group. The name is case insensitive. :type resource_group_name: str",
"self._serialize.header(\"accept\", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response =",
"Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T =",
"pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters",
"parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] =",
"**kwargs # type: Any ): # type: (...) -> \"models.GremlinGraphGetResults\"",
"Cosmos DB graph name. :type graph_name: str :param update_throughput_parameters: The",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata",
"ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type:",
"cls: return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} #",
"= self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)",
"self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"= kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401:",
"= self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z: x, **kwargs )",
"is present. :return: An instance of LROPoller that returns either",
"an Azure Cosmos DB Gremlin database. :param resource_group_name: The name",
"# type: str database_name, # type: str graph_name, # type:",
"a poller from a saved state. :keyword polling: True for",
"): # type: (...) -> LROPoller[None] \"\"\"Deletes an existing Azure",
"result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls =",
"# type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token",
"type: ignore def _create_update_gremlin_graph_initial( self, resource_group_name, # type: str account_name,",
"returns either GremlinDatabaseGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults]",
"ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse",
"Gremlin graph. :param resource_group_name: The name of the resource group.",
"ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type: str account_name, #",
"str account_name, # type: str database_name, # type: str update_throughput_parameters,",
"response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat)",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def begin_delete_gremlin_graph( self, resource_group_name,",
"# Construct URL url = self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments",
"Construct URL url = self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments =",
"~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type:",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = {",
"Optional[str] if cont_token is None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name,",
"= self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem =",
"ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} #",
":return: An iterator like instance of either GremlinDatabaseListResult or the",
"self._serialize.url(\"graph_name\", graph_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct",
"Cosmos DB database account name. :type account_name: str :keyword callable",
"of an Azure Cosmos DB Gremlin database. :param resource_group_name: The",
"under an existing Azure Cosmos DB database account. :param resource_group_name:",
"= self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters,",
"query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response)",
"An instance of LROPoller that returns either None or the",
"str database_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url':",
"database from autoscale to manual throughput. :param resource_group_name: The name",
"direct response :return: GremlinGraphGetResults, or the result of cls(response) :rtype:",
"= \"application/json\" # Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url'] # type:",
"graph_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs #",
":param graph_name: Cosmos DB graph name. :type graph_name: str :param",
"= None if response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response)",
"graph_name: Cosmos DB graph name. :type graph_name: str :param update_throughput_parameters:",
"return deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def",
"(...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Update RUs per second of an Azure",
"ignore def begin_update_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, #",
"-> Optional[\"models.GremlinDatabaseGetResults\"] cls = kwargs.pop('cls', None) # type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type:",
"deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_database_to_manual_throughput(",
"# type: Optional[str] if cont_token is None: raw_result = self._delete_gremlin_database_initial(",
"query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response)",
"type: ignore def begin_update_gremlin_database_throughput( self, resource_group_name, # type: str account_name,",
"the resource group. The name is case insensitive. :type resource_group_name:",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata",
"= client self._serialize = serializer self._deserialize = deserializer self._config =",
"The parameters to provide for the current Gremlin database. :type",
"\"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map =",
"Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom",
"code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import",
"T, Dict[str, Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should",
"error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data",
"deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type:",
"= self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"deserialized _migrate_gremlin_database_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_database_to_autoscale(",
"in this operation group. :type models: ~azure.mgmt.cosmosdb.models :param client: Client",
"ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type: str account_name, #",
"return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'}",
"the MIT License. See License.txt in the project root for",
"**kwargs # type: Any ): # type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"]",
"cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is",
"query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') # Construct headers header_parameters =",
"None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval )",
"cont_token is None: raw_result = self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters,",
"None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404:",
"databases under an existing Azure Cosmos DB database account with",
"the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls",
"present. :return: An instance of LROPoller that returns either GremlinDatabaseGetResults",
"get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def _create_update_gremlin_database_initial( self,",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore def get_gremlin_graph( self, resource_group_name,",
"ignore def _migrate_gremlin_database_to_autoscale_initial( self, resource_group_name, # type: str account_name, #",
"Cosmos DB Gremlin database. :param resource_group_name: The name of the",
"'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments) #",
"to restart a poller from a saved state. :keyword polling:",
"Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters :keyword callable cls: A custom",
"body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_database_parameters,",
"get_next, extract_data ) list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} # type: ignore",
":return: An instance of LROPoller that returns either GremlinGraphGetResults or",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_graph_initial.metadata = {'url':",
"'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link",
"self._create_update_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"group. The name is case insensitive. :type resource_group_name: str :param",
"type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') # Construct",
"if cont_token is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response =",
"~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A custom type or function that",
"instance of LROPoller that returns either None or the result",
"restart a poller from a saved state. :keyword polling: True",
"DB database name. :type database_name: str :param update_throughput_parameters: The RUs",
"Gremlin graph from manual throughput to autoscale. :param resource_group_name: The",
"# type: ignore def get_gremlin_database( self, resource_group_name, # type: str",
"None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if",
"type: Optional[str] if cont_token is None: raw_result = self._update_gremlin_graph_throughput_initial( resource_group_name=resource_group_name,",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"str database_name, # type: str create_update_gremlin_database_parameters, # type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs",
"**kwargs # type: Any ): # type: (...) -> Iterable[\"models.GremlinGraphListResult\"]",
"URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = {",
"# Construct URL url = self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_create_update_gremlin_database( self, resource_group_name,",
"that returns either None or the result of cls(response) :rtype:",
"request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinDatabaseListResult', pipeline_response) list_of_elem = deserialized.value",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_database_to_manual_throughput.metadata = {'url':",
"this operation group. :type models: ~azure.mgmt.cosmosdb.models :param client: Client for",
"# type: ignore def _migrate_gremlin_database_to_manual_throughput_initial( self, resource_group_name, # type: str",
"query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response =",
"ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters",
"be passed the direct response :keyword str continuation_token: A continuation",
"either GremlinGraphListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinGraphListResult] :raises:",
"200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"Construct URL url = self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments =",
"{}) _delete_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_delete_gremlin_database(",
"pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code",
"the current Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls:",
"{})) api_version = \"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\") accept =",
"either ThroughputSettingsGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults] :raises",
"The name is case insensitive. :type resource_group_name: str :param account_name:",
"# Licensed under the MIT License. See License.txt in the",
"def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize",
"two polls for LRO operations if no Retry-After header is",
"= \"2020-04-01\" # Construct URL url = self._delete_gremlin_graph_initial.metadata['url'] # type:",
"type: ignore def _update_gremlin_graph_throughput_initial( self, resource_group_name, # type: str account_name,",
"= kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] error_map = { 401:",
"under an existing Azure Cosmos DB database account with the",
"body_content = self._serialize.body(update_throughput_parameters, 'ThroughputSettingsUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url,",
"get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def",
"A continuation token to restart a poller from a saved",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_graph.metadata =",
"\"\"\"Deletes an existing Azure Cosmos DB Gremlin graph. :param resource_group_name:",
"of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling',",
"Any ): # type: (...) -> Optional[\"models.GremlinGraphGetResults\"] cls = kwargs.pop('cls',",
"for the current Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable",
"type: Any ): # type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists the",
"graph. :param resource_group_name: The name of the resource group. The",
"# type: Any ): # type: (...) -> Iterable[\"models.GremlinGraphListResult\"] \"\"\"Lists",
"lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None)",
"kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\" # Construct URL url =",
"Any ): # type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin",
"deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _create_update_gremlin_graph_initial(",
"url = self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"str graph_name, # type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs",
"type: ClsType[Optional[\"models.GremlinDatabaseGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"# type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"if cont_token is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str') request = self._client.get(url, query_parameters,",
"False: polling_method = NoPolling() else: polling_method = polling if cont_token:",
"get_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, # type: str",
"account_name, # type: str database_name, # type: str create_update_gremlin_database_parameters, #",
"return cls(pipeline_response, None, {}) _delete_gremlin_graph_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type:",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, #",
"graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)",
"kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401: ClientAuthenticationError,",
"response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next,",
"polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time",
"begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self,",
"or function that will be passed the direct response :keyword",
"raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore",
"the current Gremlin database. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls:",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_autoscale_initial.metadata",
"get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def",
"to provide for the current Gremlin database. :type create_update_gremlin_database_parameters: ~azure.mgmt.cosmosdb.models.GremlinDatabaseCreateUpdateParameters",
"cause incorrect behavior and will be lost if the code",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the",
"LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result,",
"self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response",
":raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.ThroughputSettingsGetResults\"]",
"return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata = {'url':",
"of the parameters to provide for the current Gremlin graph.",
"\"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map =",
"= self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"is None: raw_result = self._create_update_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters,",
"cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} #",
"the provided name. :param resource_group_name: The name of the resource",
"if response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls:",
"type: ignore def get_gremlin_database( self, resource_group_name, # type: str account_name,",
"# Code generated by Microsoft (R) AutoRest Code Generator. #",
"pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map)",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is",
"False for no polling, or a polling object for personal",
"None) # type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401: ClientAuthenticationError, 404:",
"accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content",
"begin_create_update_gremlin_graph( self, resource_group_name, # type: str account_name, # type: str",
"(...) -> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an Azure Cosmos DB",
"import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import",
"# type: str create_update_gremlin_graph_parameters, # type: \"models.GremlinGraphCreateUpdateParameters\" **kwargs # type:",
"(...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an Azure Cosmos DB",
"raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return",
"# type: Optional[str] if cont_token is None: raw_result = self._create_update_gremlin_database_initial(",
"database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"throughput. :param resource_group_name: The name of the resource group. The",
"# type: ignore def begin_create_update_gremlin_graph( self, resource_group_name, # type: str",
"{})) api_version = \"2020-04-01\" # Construct URL url = self._delete_gremlin_database_initial.metadata['url']",
"(...) -> LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB Gremlin",
"# type: str database_name, # type: str create_update_gremlin_database_parameters, # type:",
"= self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs",
"= deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem)",
"kwargs.pop('cls', None) # type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401: ClientAuthenticationError,",
"str :param update_throughput_parameters: The RUs per second of the parameters",
"None: raw_result = self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z:",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def _delete_gremlin_graph_initial( self, resource_group_name,",
"return deserialized get_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def",
"{}) return deserialized if polling is True: polling_method = ARMPolling(lro_delay,",
"= { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map',",
"A custom type or function that will be passed the",
"deserialized _create_update_gremlin_database_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_create_update_gremlin_database(",
"import ARMPolling from .. import models if TYPE_CHECKING: # pylint:",
"url = self.get_gremlin_graph.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs )",
"type: ClsType[\"models.GremlinDatabaseGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError,",
"**kwargs # type: Any ): # type: (...) -> Optional[\"models.ThroughputSettingsGetResults\"]",
"or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\"",
"# Construct URL url = self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments",
"): # type: (...) -> \"models.GremlinDatabaseGetResults\" \"\"\"Gets the Gremlin databases",
"second of an Azure Cosmos DB Gremlin graph. :param resource_group_name:",
"ignore def get_gremlin_graph( self, resource_group_name, # type: str account_name, #",
"HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_gremlin_databases.metadata",
"type: ClsType[Optional[\"models.ThroughputSettingsGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"\"\"\"Deletes an existing Azure Cosmos DB Gremlin database. :param resource_group_name:",
"'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'databaseName': self._serialize.url(\"database_name\", database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\",",
"Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False,",
"graph_name: str :param update_throughput_parameters: The RUs per second of the",
"else: url = next_link query_parameters = {} # type: Dict[str,",
"client: Client for service requests. :param config: Configuration of service",
"either GremlinGraphGetResults or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises",
"begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type: str account_name, # type: str",
"Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest,",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata =",
"api_version, 'str') # Construct headers header_parameters = {} # type:",
"ignore def get_gremlin_database( self, resource_group_name, # type: str account_name, #",
"def _delete_gremlin_graph_initial( self, resource_group_name, # type: str account_name, # type:",
"strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default",
"LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type:",
"return deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore def",
"graph name. :type graph_name: str :param create_update_gremlin_graph_parameters: The parameters to",
"account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map',",
"{}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore",
"DB Gremlin graph. :param resource_group_name: The name of the resource",
"for no polling, or a polling object for personal polling",
"str database_name, # type: str graph_name, # type: str **kwargs",
"request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False,",
"# Construct URL url = self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments",
"ClsType[\"models.GremlinGraphListResult\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError",
"Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request,",
":type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters :keyword callable cls: A custom type or",
"self.get_gremlin_database_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def _migrate_gremlin_graph_to_autoscale_initial( self, resource_group_name, # type:",
"like instance of either GremlinGraphListResult or the result of cls(response)",
"HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_gremlin_database_initial.metadata =",
"# type: Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph.metadata = {'url':",
"self._migrate_gremlin_graph_to_autoscale_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"str database_name, # type: str **kwargs # type: Any ):",
"HttpResponse], T, Dict[str, Any]], Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You",
"header_parameters) else: url = next_link query_parameters = {} # type:",
"= self._update_gremlin_database_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"serializer, deserializer): self._client = client self._serialize = serializer self._deserialize =",
"if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise",
"# type: str update_throughput_parameters, # type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type:",
":return: GremlinDatabaseGetResults, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.GremlinDatabaseGetResults :raises:",
"response.status_code == 200: deserialized = self._deserialize('GremlinDatabaseGetResults', pipeline_response) if cls: return",
":param create_update_gremlin_graph_parameters: The parameters to provide for the current Gremlin",
"begin_migrate_gremlin_graph_to_autoscale.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self,",
"Corporation. All rights reserved. # Licensed under the MIT License.",
"or update an Azure Cosmos DB Gremlin database. :param resource_group_name:",
"None if response.status_code == 200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if",
"{})) api_version = \"2020-04-01\" # Construct URL url = self._delete_gremlin_graph_initial.metadata['url']",
"# type: \"models.GremlinDatabaseCreateUpdateParameters\" **kwargs # type: Any ): # type:",
"~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling = kwargs.pop('polling', True) # type:",
"project root for license information. # Code generated by Microsoft",
":param graph_name: Cosmos DB graph name. :type graph_name: str :keyword",
"# type: Optional[str] if cont_token is None: raw_result = self._delete_gremlin_graph_initial(",
"typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union",
"'str') header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') body_content_kwargs = {} #",
"response.status_code == 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return",
"GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should not instantiate this class directly.",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_autoscale.metadata = {'url':",
"for LRO operations if no Retry-After header is present. :return:",
"path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\",",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def _update_gremlin_database_throughput_initial( self, resource_group_name,",
"existing Azure Cosmos DB Gremlin database. :param resource_group_name: The name",
"def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, # type: str account_name, # type:",
"def get_gremlin_graph_throughput( self, resource_group_name, # type: str account_name, # type:",
"\"2020-04-01\" accept = \"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url']",
"\"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"] error_map =",
"is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB",
"to autoscale. :param resource_group_name: The name of the resource group.",
"Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request =",
"import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def begin_migrate_gremlin_graph_to_manual_throughput( self, resource_group_name, #",
"account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None)",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_gremlin_graph.metadata =",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'}",
"= self._update_gremlin_graph_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseGetResults\"]",
"# type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type: str",
"database_name, 'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), } url = self._client.format_url(url,",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'}",
"self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem)",
"\"application/json\" # Construct URL url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore",
"from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if TYPE_CHECKING:",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def get_gremlin_database_throughput( self, resource_group_name, #",
"# type: \"models.ThroughputSettingsUpdateParameters\" **kwargs # type: Any ): # type:",
"be passed the direct response :return: An iterator like instance",
"begin_migrate_gremlin_database_to_manual_throughput( self, resource_group_name, # type: str account_name, # type: str",
"# type: ignore def get_gremlin_graph_throughput( self, resource_group_name, # type: str",
"type: str account_name, # type: str database_name, # type: str",
"None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval )",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'}",
"kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result",
"DB graph name. :type graph_name: str :keyword callable cls: A",
"type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409:",
"Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse],",
"\"\"\"Lists the Gremlin databases under an existing Azure Cosmos DB",
"# Construct parameters query_parameters = {} # type: Dict[str, Any]",
"'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90,",
"Any ): # type: (...) -> LROPoller[\"models.ThroughputSettingsGetResults\"] \"\"\"Migrate an Azure",
"Cosmos DB database name. :type database_name: str :param create_update_gremlin_database_parameters: The",
"is None: raw_result = self._migrate_gremlin_graph_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda",
"'str'), 'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), } url = self._client.format_url(url, **path_format_arguments)",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_database.metadata =",
"custom type or function that will be passed the direct",
"cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"] lro_delay = kwargs.pop(",
"_migrate_gremlin_graph_to_autoscale_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_graph_to_autoscale( self,",
"# type: ClsType[Optional[\"models.GremlinGraphGetResults\"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"): # type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases",
"cls: return cls(pipeline_response, None, {}) if polling is True: polling_method",
"str account_name, # type: str database_name, # type: str graph_name,",
"accept = \"application/json\" def prepare_request(next_link=None): # Construct headers header_parameters =",
"self._create_update_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, create_update_gremlin_database_parameters=create_update_gremlin_database_parameters, cls=lambda x,y,z: x, **kwargs )",
"from manual throughput to autoscale. :param resource_group_name: The name of",
"Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases under an existing Azure Cosmos",
"return ItemPaged( get_next, extract_data ) list_gremlin_graphs.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs'} #",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata =",
"= cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link)",
"Alias to model classes used in this operation group. :type",
"= self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} #",
"it as an attribute. :ivar models: Alias to model classes",
"type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None]",
"direct response :return: An iterator like instance of either GremlinGraphListResult",
"azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import",
"cont_token is None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda",
"map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if",
"-> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph under an existing Azure",
"database_name, # type: str graph_name, # type: str update_throughput_parameters, #",
"# type: ignore def begin_update_gremlin_graph_throughput( self, resource_group_name, # type: str",
"type: Optional[str] if cont_token is None: raw_result = self._update_gremlin_database_throughput_initial( resource_group_name=resource_group_name,",
"polling_method = ARMPolling(lro_delay, **kwargs) elif polling is False: polling_method =",
"Construct URL url = self._delete_gremlin_database_initial.metadata['url'] # type: ignore path_format_arguments =",
"instance of either GremlinDatabaseListResult or the result of cls(response) :rtype:",
"self._delete_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"License.txt in the project root for license information. # Code",
"serializer self._deserialize = deserializer self._config = config def list_gremlin_databases( self,",
"or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults :raises: ~azure.core.exceptions.HttpResponseError \"\"\"",
"= next_link query_parameters = {} # type: Dict[str, Any] request",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'}",
"per second of the Gremlin database under an existing Azure",
"\"application/json\" # Construct URL url = self._migrate_gremlin_database_to_autoscale_initial.metadata['url'] # type: ignore",
"200: deserialized = self._deserialize('GremlinGraphGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized,",
"client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata",
"Generator. # Changes may cause incorrect behavior and will be",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def _migrate_gremlin_graph_to_manual_throughput_initial( self, resource_group_name, # type:",
":raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinDatabaseListResult\"]",
"will be passed the direct response :return: GremlinDatabaseGetResults, or the",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata =",
"raw_result, get_long_running_output, polling_method) begin_delete_gremlin_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore",
"**body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if",
"LROPoller that returns either ThroughputSettingsGetResults or the result of cls(response)",
"iterator like instance of either GremlinDatabaseListResult or the result of",
"query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\",",
"current Gremlin graph. :type update_throughput_parameters: ~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters :keyword callable cls: A",
":param database_name: Cosmos DB database name. :type database_name: str :param",
"next_link query_parameters = {} # type: Dict[str, Any] request =",
"for service requests. :param config: Configuration of service client. :param",
"will be lost if the code is regenerated. # --------------------------------------------------------------------------",
"self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\\w\\._\\(\\)]+$'),",
"Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial( resource_group_name=resource_group_name, account_name=account_name,",
"= self.list_gremlin_databases.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_update_gremlin_database_initial.metadata =",
"database_name=database_name, update_throughput_parameters=update_throughput_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type',",
"type or function that will be passed the direct response",
"True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) #",
"DB graph name. :type graph_name: str :param create_update_gremlin_graph_parameters: The parameters",
"the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.GremlinDatabaseListResult] :raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls",
"deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_graph_throughput(",
":raises: ~azure.core.exceptions.HttpResponseError \"\"\" cls = kwargs.pop('cls', None) # type: ClsType[\"models.GremlinGraphGetResults\"]",
"and will be lost if the code is regenerated. #",
"None) # type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401: ClientAuthenticationError, 404:",
"type: ClsType[\"models.ThroughputSettingsGetResults\"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token =",
"to provide for the current Gremlin graph. :type create_update_gremlin_graph_parameters: ~azure.mgmt.cosmosdb.models.GremlinGraphCreateUpdateParameters",
"if not next_link: # Construct URL url = self.list_gremlin_graphs.metadata['url'] #",
"update an Azure Cosmos DB Gremlin graph. :param resource_group_name: The",
"\"application/json\") accept = \"application/json\" # Construct URL url = self._create_update_gremlin_database_initial.metadata['url']",
"resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, create_update_gremlin_graph_parameters=create_update_gremlin_graph_parameters, cls=lambda x,y,z: x, **kwargs )",
"type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(\"content_type\", content_type, 'str') header_parameters['Accept'] =",
"def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling",
"return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_database_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'}",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_database_throughput.metadata =",
"is None: raw_result = self._migrate_gremlin_database_to_autoscale_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, cls=lambda x,y,z:",
"max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments) # Construct",
":param deserializer: An object model deserializer. \"\"\" models = models",
"str :param create_update_gremlin_database_parameters: The parameters to provide for the current",
") else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata = {'url':",
"\"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\") accept = \"application/json\" # Construct",
"'str') if not next_link: # Construct URL url = self.list_gremlin_graphs.metadata['url']",
"poller from a saved state. :keyword polling: True for ARMPolling,",
"'graphName': self._serialize.url(\"graph_name\", graph_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) #",
"# type: Any ): # type: (...) -> LROPoller[None] \"\"\"Deletes",
"reserved. # Licensed under the MIT License. See License.txt in",
"type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token =",
"you and attaches it as an attribute. :ivar models: Alias",
"return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'}",
"Gremlin database from manual throughput to autoscale. :param resource_group_name: The",
"request def extract_data(pipeline_response): deserialized = self._deserialize('GremlinGraphListResult', pipeline_response) list_of_elem = deserialized.value",
"polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output,",
"url = next_link query_parameters = {} # type: Dict[str, Any]",
"= self._delete_gremlin_graph_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name, graph_name=graph_name, cls=lambda x,y,z: x, **kwargs",
"per second of an Azure Cosmos DB Gremlin graph. :param",
"{} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(\"api_version\", api_version, 'str')",
"# type: ClsType[\"models.ThroughputSettingsGetResults\"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError,",
"raw_result, get_long_running_output, polling_method) begin_migrate_gremlin_graph_to_manual_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore",
"= self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\",",
"Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type']",
"will be passed the direct response :return: ThroughputSettingsGetResults, or the",
"= {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}'} # type: ignore def begin_delete_gremlin_database( self, resource_group_name,",
"self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id,",
"url = self._migrate_gremlin_graph_to_manual_throughput_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId':",
"= self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not",
"'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters",
"{'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default'} # type: ignore def begin_update_gremlin_database_throughput( self, resource_group_name, #",
"type: (...) -> LROPoller[\"models.GremlinGraphGetResults\"] \"\"\"Create or update an Azure Cosmos",
"deserialized = None if response.status_code == 200: deserialized = self._deserialize('GremlinGraphGetResults',",
"self._serialize.url(\"self._config.subscription_id\", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url(\"resource_group_name\", resource_group_name, 'str', max_length=90, min_length=1,",
"self._client = client self._serialize = serializer self._deserialize = deserializer self._config",
"type: ignore def begin_create_update_gremlin_graph( self, resource_group_name, # type: str account_name,",
"the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.GremlinGraphGetResults] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling",
"account. :param resource_group_name: The name of the resource group. The",
"else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_gremlin_graph_throughput.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'}",
"# Construct URL url = self._create_update_gremlin_graph_initial.metadata['url'] # type: ignore path_format_arguments",
"return deserialized _migrate_gremlin_graph_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default/migrateToManualThroughput'} # type: ignore def",
") list_gremlin_databases.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases'} # type: ignore def get_gremlin_database(",
"that will be passed the direct response :return: An iterator",
"Cosmos DB graph name. :type graph_name: str :keyword callable cls:",
":type resource_group_name: str :param account_name: Cosmos DB database account name.",
"# type: str graph_name, # type: str update_throughput_parameters, # type:",
"iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False,",
"create_update_gremlin_graph_parameters: The parameters to provide for the current Gremlin graph.",
"'GremlinDatabaseCreateUpdateParameters') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)",
"== 200: deserialized = self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response,",
"Gremlin graph under an existing Azure Cosmos DB database account.",
"Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T')",
"= {} # type: Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters')",
"type: (...) -> \"models.GremlinGraphGetResults\" \"\"\"Gets the Gremlin graph under an",
"{}) return deserialized get_gremlin_graph.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}'} # type: ignore",
"= self._deserialize('ThroughputSettingsGetResults', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return",
"instance of LROPoller that returns either GremlinGraphGetResults or the result",
"# type: Optional[str] if cont_token is None: raw_result = self._migrate_gremlin_database_to_manual_throughput_initial(",
"deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_update_gremlin_graph.metadata =",
"# type: ignore def begin_migrate_gremlin_graph_to_autoscale( self, resource_group_name, # type: str",
"if cont_token is None: raw_result = self._delete_gremlin_database_initial( resource_group_name=resource_group_name, account_name=account_name, database_name=database_name,",
"return cls(pipeline_response, deserialized, {}) return deserialized _migrate_gremlin_database_to_manual_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput'}",
"\"\"\"GremlinResourcesOperations operations. You should not instantiate this class directly. Instead,",
"the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: \"\"\" polling",
"of the resource group. The name is case insensitive. :type",
"response :return: An iterator like instance of either GremlinGraphListResult or",
"ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" #",
"Construct URL url = self.get_gremlin_graph_throughput.metadata['url'] # type: ignore path_format_arguments =",
"polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval:",
"Any ): # type: (...) -> None cls = kwargs.pop('cls',",
"-> LROPoller[\"models.GremlinDatabaseGetResults\"] \"\"\"Create or update an Azure Cosmos DB Gremlin",
"case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database",
"{})) api_version = \"2020-04-01\" accept = \"application/json\" # Construct URL",
"= polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output",
"rights reserved. # Licensed under the MIT License. See License.txt",
"an existing Azure Cosmos DB database account with the provided",
"function that will be passed the direct response :return: GremlinDatabaseGetResults,",
"return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/graphs/{graphName}/throughputSettings/default'} # type: ignore def",
"= self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response",
"# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All",
"import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import",
"[200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized =",
"None) # type: ClsType[\"models.GremlinGraphListResult\"] error_map = { 401: ClientAuthenticationError, 404:",
"type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(\"accept\", accept, 'str') if not",
"database account with the provided name. :param resource_group_name: The name",
"regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from",
"polling: True for ARMPolling, False for no polling, or a",
"-> LROPoller[None] \"\"\"Deletes an existing Azure Cosmos DB Gremlin graph.",
"ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" accept",
"accept = \"application/json\" # Construct URL url = self._create_update_gremlin_graph_initial.metadata['url'] #",
"cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata = {'url':",
"database_name: Cosmos DB database name. :type database_name: str :param graph_name:",
"pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_gremlin_graph_throughput_initial.metadata",
"} error_map.update(kwargs.pop('error_map', {})) api_version = \"2020-04-01\" content_type = kwargs.pop(\"content_type\", \"application/json\")",
"Any]] class GremlinResourcesOperations(object): \"\"\"GremlinResourcesOperations operations. You should not instantiate this",
"x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized",
"type: (...) -> Iterable[\"models.GremlinDatabaseListResult\"] \"\"\"Lists the Gremlin databases under an",
"Dict[str, Any] body_content = self._serialize.body(create_update_gremlin_graph_parameters, 'GremlinGraphCreateUpdateParameters') body_content_kwargs['content'] = body_content request",
"database account name. :type account_name: str :keyword callable cls: A",
"'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/gremlinDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale'} # type: ignore def begin_migrate_gremlin_database_to_autoscale( self, resource_group_name, # type:",
"api_version = \"2020-04-01\" # Construct URL url = self._delete_gremlin_graph_initial.metadata['url'] #"
] |
[
"registry entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id =",
"in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def async_start( hass:",
"HomeAssistantType from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS =",
"entity.\"\"\" if not tasmota_entity_config: # Entity disabled, clean up entity",
"unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType",
"async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new entity: %s",
"config_entries_key = f\"{platform}.tasmota\" if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup(",
"\"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\"",
"not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async",
"platform): continue await _load_platform(platform) for platform in SUPPORTED_PLATFORMS: tasmota_entities =",
"added, sending update: %s %s\", platform, discovery_hash, ) async_dispatcher_send( hass,",
"asyncio import logging from hatasmota.discovery import ( TasmotaDiscovery, get_device_config as",
"async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if not payload: return",
"tasmota device: %s\", mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE,",
"= \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry",
"\"\"\"Process the received message.\"\"\" if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED]",
"def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash]",
"if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform )",
"import logging from hatasmota.discovery import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config,",
"TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity,",
"discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass,",
"unique_id) if entity_id: _LOGGER.debug(\"Removing entity: %s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id)",
"import asyncio import logging from hatasmota.discovery import ( TasmotaDiscovery, get_device_config",
"( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as",
"= tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity,",
"\"\"\"Start MQTT Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load a Tasmota platform",
"done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if config_entries_key not",
"platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding",
"discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added, sending update: %s",
"{} _LOGGER.debug(\"Received discovery data for tasmota device: %s\", mac) tasmota_device_config",
"import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity",
"set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {}",
"async def _load_platform(platform): \"\"\"Load a Tasmota platform if not already",
"await hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash,",
"entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing entity: %s",
"entity_registry.async_remove(entity_id) return if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added,",
"for (tasmota_entity_config, discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK]",
"entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform,",
"= {} _LOGGER.debug(\"Received discovery data for tasmota device: %s\", mac)",
"homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from .const import",
"ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE",
"discovered entity.\"\"\" if not tasmota_entity_config: # Entity disabled, clean up",
"for MQTT discovery.\"\"\" import asyncio import logging from hatasmota.discovery import",
"platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send(",
"_discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery",
"tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import",
"%s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug(",
"the received message.\"\"\" if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] =",
"get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform",
"tasmota_entity_config: # Entity disabled, clean up entity registry entity_registry =",
"list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def async_start( hass: HomeAssistantType, discovery_topic,",
"tasmota_mqtt ) -> bool: \"\"\"Start MQTT Discovery.\"\"\" async def _load_platform(platform):",
"return if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added, sending",
"from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN _LOGGER =",
"DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing entity: %s %s\", platform, discovery_hash)",
"platform in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform)",
"tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash,",
"ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def async_start( hass: HomeAssistantType,",
"\"\"\"Load a Tasmota platform if not already done.\"\"\" async with",
"\"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK =",
"_discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding or updating a discovered entity.\"\"\"",
"Entity disabled, clean up entity registry entity_registry = await hass.helpers.entity_registry.async_get_registry()",
"platform, discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity",
"MQTT Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load a Tasmota platform if",
"discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already",
"async def async_device_discovered(payload, mac): \"\"\"Process the received message.\"\"\" if ALREADY_DISCOVERED",
"if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery",
"device: %s\", mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config,",
"= {} async def async_start( hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt",
"tasmota_device_config, mac ) if not payload: return for platform in",
"logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP",
"_LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\", ] ALREADY_DISCOVERED =",
"import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN",
"async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async def async_device_discovered(payload, mac):",
"CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW",
"discovery_topic, config_entry, tasmota_mqtt ) -> bool: \"\"\"Start MQTT Discovery.\"\"\" async",
"platform if not already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key =",
"%s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash in hass.data[ALREADY_DISCOVERED]:",
"already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if config_entries_key",
"_LOGGER.debug(\"Adding new entity: %s %s\", platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config,",
"received message.\"\"\" if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = {}",
"SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash) in tasmota_entities:",
"tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash) in tasmota_entities: await",
"%s %s\", platform, discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, )",
") if not payload: return for platform in SUPPORTED_PLATFORMS: if",
"as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import",
"def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] =",
"data for tasmota device: %s\", mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send(",
"mac): \"\"\"Process the received message.\"\"\" if ALREADY_DISCOVERED not in hass.data:",
"hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new entity: %s %s\",",
"SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform) for platform",
"TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if not payload: return for platform",
"has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from",
"in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash) in",
"message.\"\"\" if ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received",
"hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery data for tasmota device:",
") else: _LOGGER.debug(\"Adding new entity: %s %s\", platform, discovery_hash) tasmota_entity",
"in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP]",
"platform in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash)",
"await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set()",
"%s %s\", platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] =",
") -> bool: \"\"\"Start MQTT Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load",
"as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as",
"discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery =",
".const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\",",
"= await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN,",
"entity: %s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash in",
"DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED",
"= None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async def",
"tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform),",
"= tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config, discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config,",
"HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt ) -> bool: \"\"\"Start MQTT Discovery.\"\"\"",
"disabled, clean up entity registry entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id",
"async_device_discovered(payload, mac): \"\"\"Process the received message.\"\"\" if ALREADY_DISCOVERED not in",
"platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery = TasmotaDiscovery(discovery_topic,",
"async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN _LOGGER",
"= asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery = TasmotaDiscovery(discovery_topic, tasmota_mqtt) await",
"entity registry entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id",
"for platform in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform): continue await",
"TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def",
"in hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery data for tasmota",
"up entity registry entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash)",
"None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async def async_device_discovered(payload,",
"in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added, sending update: %s %s\",",
"adding or updating a discovered entity.\"\"\" if not tasmota_entity_config: #",
"tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, )",
"platform): \"\"\"Handle adding or updating a discovered entity.\"\"\" if not",
"DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\", ] ALREADY_DISCOVERED",
"def async_device_discovered(payload, mac): \"\"\"Process the received message.\"\"\" if ALREADY_DISCOVERED not",
"entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def async_start(",
"discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass,",
"discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new",
"tasmota_entity, discovery_hash, ) async def async_device_discovered(payload, mac): \"\"\"Process the received",
"= logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\"",
"mac ) if not payload: return for platform in SUPPORTED_PLATFORMS:",
"clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def",
"\"\"\"Handle adding or updating a discovered entity.\"\"\" if not tasmota_entity_config:",
"from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [",
"hatasmota.discovery import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform,",
") hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding or",
"async def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding or updating a",
"else: _LOGGER.debug(\"Adding new entity: %s %s\", platform, discovery_hash) tasmota_entity =",
"tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new entity: %s %s\", platform, discovery_hash)",
"unique_id = unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id:",
"as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, )",
"discovery_hash, platform): \"\"\"Handle adding or updating a discovered entity.\"\"\" if",
"ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in",
"a discovered entity.\"\"\" if not tasmota_entity_config: # Entity disabled, clean",
"f\"{platform}.tasmota\" if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform",
"hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery = TasmotaDiscovery(discovery_topic, tasmota_mqtt) await tasmota_discovery.start_discovery(async_device_discovered, None)",
"from hatasmota.discovery import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as",
"= [ \"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\"",
"import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ \"switch\", ]",
"= \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass,",
"= entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing entity: %s %s\",",
"hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery = TasmotaDiscovery(discovery_topic, tasmota_mqtt)",
"= tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if not",
"tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform) for platform in SUPPORTED_PLATFORMS: tasmota_entities",
"await hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id)",
"in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform) for",
"in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def",
"\"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\"",
"hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash, platform):",
"for platform in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for (tasmota_entity_config,",
"platform, discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding",
"\"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\" del",
"_LOGGER.debug(\"Received discovery data for tasmota device: %s\", mac) tasmota_device_config =",
"= \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\"",
"get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher",
"tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if",
"\"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in",
"tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from",
"{} async def async_start( hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt )",
"def async_start( hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt ) -> bool:",
"async_start( hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt ) -> bool: \"\"\"Start",
"sending update: %s %s\", platform, discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash),",
"TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async def async_device_discovered(payload, mac): \"\"\"Process the",
"hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash]",
"Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load a Tasmota platform if not",
"update: %s %s\", platform, discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config,",
"not in hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery data for",
"= \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE =",
"hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async def async_device_discovered(payload, mac): \"\"\"Process",
"if not tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform) for platform in",
"discovery.\"\"\" import asyncio import logging from hatasmota.discovery import ( TasmotaDiscovery,",
"(tasmota_entity_config, discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] =",
"tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash,",
"get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash,",
"SUPPORTED_PLATFORMS = [ \"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP =",
"async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if config_entries_key not in",
"from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from .const",
"hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config,",
"discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async",
"discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock()",
"\"Entity already added, sending update: %s %s\", platform, discovery_hash, )",
"= \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED =",
"_LOGGER.debug( \"Entity already added, sending update: %s %s\", platform, discovery_hash,",
"homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN _LOGGER = logging.getLogger(__name__)",
"if discovery_hash in hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added, sending update:",
"config_entry, tasmota_mqtt ) -> bool: \"\"\"Start MQTT Discovery.\"\"\" async def",
"TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear entry in ALREADY_DISCOVERED",
"tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform,",
"= unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing",
"hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt ) -> bool: \"\"\"Start MQTT",
"not tasmota_entity_config: # Entity disabled, clean up entity registry entity_registry",
"asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] = set() tasmota_discovery = TasmotaDiscovery(discovery_topic, tasmota_mqtt) await tasmota_discovery.start_discovery(async_device_discovered,",
"hass.helpers.entity_registry.async_get_registry() unique_id = unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if",
"new entity: %s %s\", platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt)",
"entry in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set",
"= \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW =",
"continue await _load_platform(platform) for platform in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload,",
"async def async_start( hass: HomeAssistantType, discovery_topic, config_entry, tasmota_mqtt ) ->",
"with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]:",
"mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac )",
"as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing",
"tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if not payload:",
"not tasmota_has_entities_with_platform(payload, platform): continue await _load_platform(platform) for platform in SUPPORTED_PLATFORMS:",
"hass.data[ALREADY_DISCOVERED][discovery_hash] = None async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_NEW.format(platform), tasmota_entity, discovery_hash, ) async",
"if not payload: return for platform in SUPPORTED_PLATFORMS: if not",
"del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\"",
"hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding or updating",
"ALREADY_DISCOVERED not in hass.data: hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery data",
"\"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\" TASMOTA_DISCOVERY_DEVICE = \"tasmota_discovery_device\"",
"[ \"switch\", ] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK",
"config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key)",
"for tasmota device: %s\", mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass,",
"in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry",
"\"\"\"Set entry in ALREADY_DISCOVERED list.\"\"\" hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def",
") async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new entity:",
"updating a discovered entity.\"\"\" if not tasmota_entity_config: # Entity disabled,",
"a Tasmota platform if not already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]:",
"discovery_hash, ) async def async_device_discovered(payload, mac): \"\"\"Process the received message.\"\"\"",
"tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform) hass.data[DATA_CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[CONFIG_ENTRY_IS_SETUP] =",
"hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await",
"\"tasmota_discovery_device\" TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash):",
"config_entry, platform ) hass.data[CONFIG_ENTRY_IS_SETUP].add(config_entries_key) async def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle",
"already added, sending update: %s %s\", platform, discovery_hash, ) async_dispatcher_send(",
"list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): \"\"\"Set entry in ALREADY_DISCOVERED",
") from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from",
"not payload: return for platform in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload,",
"MQTT discovery.\"\"\" import asyncio import logging from hatasmota.discovery import (",
"or updating a discovered entity.\"\"\" if not tasmota_entity_config: # Entity",
"return for platform in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform): continue",
"%s\", platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash] = None",
"] ALREADY_DISCOVERED = \"tasmota_discovered_components\" CONFIG_ENTRY_IS_SETUP = \"tasmota_config_entry_is_setup\" DATA_CONFIG_ENTRY_LOCK = \"tasmota_config_entry_lock\"",
"if not already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\"",
"if not tasmota_entity_config: # Entity disabled, clean up entity registry",
"_LOGGER.debug(\"Removing entity: %s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return if discovery_hash",
"hass.data[ALREADY_DISCOVERED]: _LOGGER.debug( \"Entity already added, sending update: %s %s\", platform,",
"\"\"\"Clear entry in ALREADY_DISCOVERED list.\"\"\" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash):",
"Tasmota platform if not already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key",
"tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send",
"TASMOTA_DISCOVERY_ENTITY_NEW = \"tasmota_discovery_entity_new_{}\" TASMOTA_DISCOVERY_ENTITY_UPDATED = \"tasmota_discovery_entity_updated_{}_{}_{}_{}\" def clear_discovery_hash(hass, discovery_hash): \"\"\"Clear",
"def _discover_entity(tasmota_entity_config, discovery_hash, platform): \"\"\"Handle adding or updating a discovered",
"bool: \"\"\"Start MQTT Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load a Tasmota",
"entity_id: _LOGGER.debug(\"Removing entity: %s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return if",
"entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing entity: %s %s\", platform,",
"entity: %s %s\", platform, discovery_hash) tasmota_entity = tasmota_get_entity(tasmota_entity_config, tasmota_mqtt) hass.data[ALREADY_DISCOVERED][discovery_hash]",
"_load_platform(platform): \"\"\"Load a Tasmota platform if not already done.\"\"\" async",
"-> bool: \"\"\"Start MQTT Discovery.\"\"\" async def _load_platform(platform): \"\"\"Load a",
"discovery data for tasmota device: %s\", mac) tasmota_device_config = tasmota_get_device_config(payload)",
"TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else: _LOGGER.debug(\"Adding new entity: %s %s\", platform,",
"\"\"\"Support for MQTT discovery.\"\"\" import asyncio import logging from hatasmota.discovery",
") async def async_device_discovered(payload, mac): \"\"\"Process the received message.\"\"\" if",
"if entity_id: _LOGGER.debug(\"Removing entity: %s %s\", platform, discovery_hash) entity_registry.async_remove(entity_id) return",
"unique_id_from_hash(discovery_hash) entity_id = entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) if entity_id: _LOGGER.debug(\"Removing entity:",
"# Entity disabled, clean up entity registry entity_registry = await",
"clean up entity registry entity_registry = await hass.helpers.entity_registry.async_get_registry() unique_id =",
"platform) for (tasmota_entity_config, discovery_hash) in tasmota_entities: await _discover_entity(tasmota_entity_config, discovery_hash, platform)",
"%s\", platform, discovery_hash, ) async_dispatcher_send( hass, TASMOTA_DISCOVERY_ENTITY_UPDATED.format(*discovery_hash), tasmota_entity_config, ) else:",
"hass.data[ALREADY_DISCOVERED] = {} _LOGGER.debug(\"Received discovery data for tasmota device: %s\",",
"def _load_platform(platform): \"\"\"Load a Tasmota platform if not already done.\"\"\"",
"not already done.\"\"\" async with hass.data[DATA_CONFIG_ENTRY_LOCK]: config_entries_key = f\"{platform}.tasmota\" if",
"hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac ) if not payload: return for",
"payload: return for platform in SUPPORTED_PLATFORMS: if not tasmota_has_entities_with_platform(payload, platform):",
"logging from hatasmota.discovery import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform",
"_load_platform(platform) for platform in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform) for",
"= f\"{platform}.tasmota\" if config_entries_key not in hass.data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setup( config_entry,",
"import HomeAssistantType from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS",
"await _load_platform(platform) for platform in SUPPORTED_PLATFORMS: tasmota_entities = tasmota_get_entities_for_platform(payload, platform)",
"hass.data[ALREADY_DISCOVERED][discovery_hash] = {} async def async_start( hass: HomeAssistantType, discovery_topic, config_entry,",
"%s\", mac) tasmota_device_config = tasmota_get_device_config(payload) async_dispatcher_send( hass, TASMOTA_DISCOVERY_DEVICE, tasmota_device_config, mac"
] |
[
"kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import base_executor from",
"serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec)",
"successfully queried. if requests: client.SendRequests(requests) finally: logging.info('Stopping %r.', runner) runner.Stop()",
"self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager",
"from tfx.components.infra_validator import request_builder from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator",
"# flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path)",
"2.0 (the \"License\"); # you may not use this file",
"run in LOAD_ONLY mode.') requests = [] model_path = self._PrepareModelPath(model,",
"infra blessing artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename",
"logging.info('InfraValidator will be run in LOAD_AND_QUERY mode.') requests = request_builder.build_requests(",
"validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX",
"from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import base_executor from tfx.proto",
"conforms to the tensorflow serving # model path flavor. (Parsed",
"import threading import time from typing import Any, Dict, List,",
"message keys for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER =",
"tfx.dsl.components.base import base_executor from tfx.proto import infra_validator_pb2 from tfx.types import",
"InfraValidator currently only recognizes SIGTERM signal as a graceful shutdown.",
"loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check",
"not a MainThread, it is not allowed to register #",
"validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries:",
"tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import",
"and optinally validated model if warmup requests are appended. Artifact",
"'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename of infra blessing artifact",
"# Check model can be successfully queried. if requests: client.SendRequests(requests)",
"# Every trial has failed. Marking model as not blessed.",
"blessing artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of",
"shutdown behavior. Caveat: InfraValidator currently only recognizes SIGTERM signal as",
"_NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\"",
"' '(name=%s). SIGTERM will not be handled.', threading.current_thread().name) old_handler =",
"path_utils from tfx.utils import proto_utils from tfx.utils.model_paths import tf_serving_flavor from",
"shutdown. Furthermore, SIGTERM can be handled only if the executor",
"to be used for test requests. output_dict: - `blessing`: Single",
"'ValidationSpec.max_loading_time_seconds.') else: # If validation has passed without any exception,",
"License for the specific language governing permissions and # limitations",
"= artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY],",
"the grace period. When the executor is run by the",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing) if requests and request_spec.make_warmup:",
"types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model))",
"artifacts to be used for test requests. output_dict: - `blessing`:",
"self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: # GracefulShutdown",
"tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC",
"fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary,",
"structure flavor. If current model_path does not conform to the",
"validation. Returns: A ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform') if platform",
"str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for",
"threading import time from typing import Any, Dict, List, Optional",
"request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact,",
"Every trial has failed. Marking model as not blessed. return",
"Kubernetes). \"\"\" def _handler(signum, frame): del frame # Unused. raise",
"graceful shutdown behavior. Caveat: InfraValidator currently only recognizes SIGTERM signal",
"tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import",
"without any exception, succeeded. return True # Every trial has",
"io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY,",
"# Filename of infra blessing artifact on succeed. _BLESSED_FILENAME =",
"_TENSORFLOW_SERVING: # TensorFlow Serving requires model to be stored in",
"(e.g. activeDeadlineSeconds in Kubernetes). \"\"\" def _handler(signum, frame): del frame",
"proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec =",
"_BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename of infra",
"Dict[str, Any]) -> None: \"\"\"Contract for running InfraValidator Executor. Args:",
"artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of infra",
"_DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' #",
"to register signal handler for non-MainThread ' '(name=%s). SIGTERM will",
"from typing import Any, Dict, List, Optional from absl import",
"OF ANY KIND, either express or implied. # See the",
"logging.info('Consider increasing the value of ' 'ValidationSpec.max_loading_time_seconds.') else: # If",
"See the License for the specific language governing permissions and",
"to in writing, software # distributed under the License is",
"exc_info=True) def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties:",
"import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2",
"on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of infra blessing",
"return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform == 'kubernetes':",
"@contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior.",
"Beam DirectRunner, the executor thread is one of the worker",
"or agreed to in writing, software # distributed under the",
"request_spec: logging.info('InfraValidator will be run in LOAD_AND_QUERY mode.') requests =",
"yield finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do( self,",
"except error_types.GracefulShutdown: # GracefulShutdown means infra validation aborted. No more",
"grace period. When the executor is run by the local",
"from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs",
"that we're validating. - `examples`: `Examples` artifacts to be used",
"One of ServingBinary instances parsed from the `serving_spec`. serving_spec: A",
"'(name=%s). SIGTERM will not be handled.', threading.current_thread().name) old_handler = None",
"5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model'",
"model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: # GracefulShutdown means",
"- `validation_spec`: Serialized `ValidationSpec` configuration. - `request_spec`: Serialized `RequestSpec` configuration.",
"will not be handled.', threading.current_thread().name) old_handler = None try: yield",
"compliance with the License. # You may obtain a copy",
"tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import",
"All Rights Reserved. # # Licensed under the Apache License,",
"requests=requests) except error_types.GracefulShutdown: # GracefulShutdown means infra validation aborted. No",
"True # Every trial has failed. Marking model as not",
"iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from",
"ServingBinary and a ServingSpec. Args: model_path: An IV-flavored model path.",
") elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec",
"- `blessing`: Single `InfraBlessing` artifact containing the validated result and",
"def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior. Caveat:",
"= infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME",
"either of MainThread or worker thread receives SIGTERM, executor will",
"not use this file except in compliance with the License.",
"serving_binary=serving_binary, serving_spec=serving_spec ) elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path,",
"Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context] =",
"you may not use this file except in compliance with",
"&= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing)",
"self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def",
"validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i in range(validation_spec.num_tries): logging.info('Starting infra",
"types from tfx.components.infra_validator import error_types from tfx.components.infra_validator import request_builder from",
"requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will",
"SIGTERM is a standard way to signal the graceful shutdown.",
"a ModelServerRunner from a model, a ServingBinary and a ServingSpec.",
"import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"# Proto message keys for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving'",
"\"\"\" platform = serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return local_docker_runner.LocalDockerRunner(",
"model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples =",
"raise except Exception as e: # pylint: disable=broad-except # Other",
"period. When the executor is run by the local Beam",
"if examples and request_spec: logging.info('InfraValidator will be run in LOAD_AND_QUERY",
"on signal, we can effectively transform the signal to an",
"classification_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from",
"serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY],",
"pylint: disable=broad-except # Other exceptions indicates validation failure. Log the",
"bare-except logging.warning('Error occurred during cleanup.', exc_info=True) def Do(self, input_dict: Dict[str,",
"import local_docker_runner from tfx.dsl.components.base import base_executor from tfx.proto import infra_validator_pb2",
"NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra validation",
"None with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec,",
"\"\"\"Try convert infra validation request to TF-Serving PredictionLog.\"\"\" if isinstance(request,",
"import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY",
"to terminate the process without raising any exception. By registering",
"has failed. Marking model as not blessed. return False def",
"List[iv_types.Request]): deadline = time.time() + validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path,",
"1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the value of",
"examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): #",
"current model_path conforms to the tensorflow serving # model path",
"signal.signal(signal.SIGTERM, old_handler) def _Do( self, model: types.Artifact, examples: Optional[types.Artifact], blessing:",
"exec_properties: Dict[str, Any]) -> None: \"\"\"Contract for running InfraValidator Executor.",
"Exception as e: # pylint: disable=broad-except # Other exceptions indicates",
"= infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries: validation_spec.num_tries",
"`model`: Single `Model` artifact that we're validating. - `examples`: `Examples`",
"_mark_blessed(blessing: types.Artifact) -> None: logging.info('Model passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri,",
"- `model`: Single `Model` artifact that we're validating. - `examples`:",
"If current model_path does not conform to the flavor, #",
"function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self): for cleanup",
"self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do( self, model: types.Artifact,",
"\"\"\" def _handler(signum, frame): del frame # Unused. raise error_types.GracefulShutdown('Got",
"PredictionLog') def _mark_blessed(blessing: types.Artifact) -> None: logging.info('Model passed infra validation.')",
"types as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import",
"import VALIDATION_SPEC_KEY from tfx.utils import io_utils from tfx.utils import path_utils",
"the graceful shutdown. Python default behavior for receiving SIGTERM is",
"Proto message keys for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER",
"_convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra validation request to TF-Serving PredictionLog.\"\"\"",
"language governing permissions and # limitations under the License. \"\"\"TFX",
"import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC =",
"does not conform to the flavor, # we need to",
"`ValidationSpec` configuration. - `request_spec`: Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"True for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary,",
"List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: \"\"\"Contract for running InfraValidator",
"def _ValidateWithRetry( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec:",
"Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ):",
"flavor, # we need to make a copy to the",
"str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline",
"exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples",
"logging.warning('Error occurred during cleanup.', exc_info=True) def Do(self, input_dict: Dict[str, List[types.Artifact]],",
"*args, **kwargs)) def _Cleanup(self): for cleanup in self._cleanups: try: cleanup()",
"file except in compliance with the License. # You may",
"# we need to make a copy to the temporary",
"serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request):",
"1) def _PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path",
"= 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto",
"is running on Kubernetes, SIGTERM is a standard way to",
"validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact)",
"with the tensorflow serving model path # flavor. temp_model_path =",
"contextlib import functools import os import signal import threading import",
"value of ' 'ValidationSpec.max_loading_time_seconds.') else: # If validation has passed",
"grace period. Even if the executor fails to shutdown gracefully,",
"= signal.signal(signal.SIGTERM, _handler) except ValueError: # If current thread is",
"i + 1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec,",
"`serving_spec`: Serialized `ServingSpec` configuration. - `validation_spec`: Serialized `ValidationSpec` configuration. -",
"import logging from tfx import types from tfx.components.infra_validator import error_types",
"(attempt %d/%d) failed.', i + 1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded):",
"if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the value of ' 'ValidationSpec.max_loading_time_seconds.')",
"a MainThread, it is not allowed to register # the",
"exception. By registering a handler that raises on signal, we",
"Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY])",
"will be run in LOAD_ONLY mode.') requests = [] model_path",
"runs the python interpreter) due to the limitation of Python",
"model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def",
"SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import io_utils from",
"KIND, either express or implied. # See the License for",
"except Exception as e: # pylint: disable=broad-except # Other exceptions",
"input_dict: - `model`: Single `Model` artifact that we're validating. -",
"import signal import threading import time from typing import Any,",
"default behavior for receiving SIGTERM is to terminate the process",
"warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r)",
"tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import types as iv_types from",
"serving model path # flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name,",
"old_handler) def _Do( self, model: types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact,",
"(the \"License\"); # you may not use this file except",
"request_spec=request_spec) else: logging.info('InfraValidator will be run in LOAD_ONLY mode.') requests",
"blessing: types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path,",
"directory # structure flavor. If current model_path does not conform",
"a copy to the temporary path. try: # Check whether",
"SIGTERM, executor will die immediately without grace period. Even if",
"# # Unless required by applicable law or agreed to",
"has passed without any exception, succeeded. return True # Every",
"else: raise NotImplementedError( f'Cannot convert {type(request)} to PredictionLog') def _mark_blessed(blessing:",
"[] model_path = self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make logic parallel.",
"0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\" def __init__(self, context:",
"failure. Log the error and # retry. logging.exception('Infra validation (attempt",
"own directory # structure flavor. If current model_path does not",
"an empty file with the name either of INFRA_BLESSED or",
"tfx.utils import proto_utils from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import",
"platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else:",
"implied. # See the License for the specific language governing",
"infra_validator_pb2 from tfx.types import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from",
"run by the local Beam DirectRunner, the executor thread is",
"base_executor from tfx.proto import infra_validator_pb2 from tfx.types import artifact_utils from",
"validation has passed without any exception, succeeded. return True #",
"if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return",
"Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context) self._cleanups = [] def _AddCleanup(self,",
"in Kubernetes). \"\"\" def _handler(signum, frame): del frame # Unused.",
"else: request_spec = None with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing,",
"retry. logging.exception('Infra validation (attempt %d/%d) failed.', i + 1, validation_spec.num_tries)",
"a handler that raises on signal, we can effectively transform",
"escalate the error. raise except Exception as e: # pylint:",
"path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING: # TensorFlow",
"tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import predict_pb2 from",
"logging.info('Unable to register signal handler for non-MainThread ' '(name=%s). SIGTERM",
"requests. output_dict: - `blessing`: Single `InfraBlessing` artifact containing the validated",
"serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline = time.time()",
"is not a MainThread, it is not allowed to register",
"absl import logging from tfx import types from tfx.components.infra_validator import",
"from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1",
"behavior. Caveat: InfraValidator currently only recognizes SIGTERM signal as a",
"is to terminate the process without raising any exception. By",
"from tfx import types from tfx.components.infra_validator import error_types from tfx.components.infra_validator",
"serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from a model,",
"_mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]): output_model_path",
"import Any, Dict, List, Optional from absl import logging from",
"Unless required by applicable law or agreed to in writing,",
"_handler) except ValueError: # If current thread is not a",
"frame # Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler =",
"model to comply with the tensorflow serving model path #",
"# GracefulShutdown means infra validation aborted. No more retry and",
"disable=broad-except # Other exceptions indicates validation failure. Log the error",
"serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from a model, a",
"running on the MainThread (the thread that runs the python",
"the specific language governing permissions and # limitations under the",
"`ServingSpec` configuration. - `validation_spec`: Serialized `ValidationSpec` configuration. - `request_spec`: Serialized",
"= request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will be",
"model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will be run in LOAD_ONLY",
"VALIDATION_SPEC_KEY from tfx.utils import io_utils from tfx.utils import path_utils from",
"Returns: A ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform') if platform ==",
"import types as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners",
"import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY",
"logging.info('InfraValidator will be run in LOAD_ONLY mode.') requests = []",
"convert infra validation request to TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest):",
"cleanup in self._cleanups: try: cleanup() except: # pylint: disable=broad-except, bare-except",
"to signal the graceful shutdown. Python default behavior for receiving",
"limitations under the License. \"\"\"TFX InfraValidator executor definition.\"\"\" import contextlib",
"as not blessed. return False def _ValidateOnce( self, model_path: str,",
"try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: #",
"logging.exception('Infra validation (attempt %d/%d) failed.', i + 1, validation_spec.num_tries) if",
"is running on the MainThread (the thread that runs the",
"kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform {}'.format(platform))",
"serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can be successfully",
"model_path, expected_model_name=serving_spec.model_name) except ValueError: # Copy the model to comply",
"our cleanup code inside \"except\" or \"finally\" block during the",
"If either of MainThread or worker thread receives SIGTERM, executor",
"and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing:",
"is successfully loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC)",
"class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context]",
"serving_spec) if not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec()",
"\"finally\" block during the grace period. When the executor is",
"# Other exceptions indicates validation failure. Log the error and",
"tfx.utils import path_utils from tfx.utils import proto_utils from tfx.utils.model_paths import",
"- `request_spec`: Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties) model",
"containing the validated result and optinally validated model if warmup",
"return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform",
"validation_spec) if not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds:",
"blessing artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path:",
"graceful shutdown. Furthermore, SIGTERM can be handled only if the",
"as e: # pylint: disable=broad-except # Other exceptions indicates validation",
"Artifact URI includes an empty file with the name either",
"_DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not",
"for i in range(validation_spec.num_tries): logging.info('Starting infra validation (attempt %d/%d).', i",
"import infra_validator_pb2 from tfx.types import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY",
"in range(validation_spec.num_tries): logging.info('Starting infra validation (attempt %d/%d).', i + 1,",
"def _mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model failed infra validation.') io_utils.write_string_file(",
"path. (See model_path_utils.py) serving_binary: One of ServingBinary instances parsed from",
"= _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.', runner) runner.Start()",
"path. try: # Check whether current model_path conforms to the",
"inside \"except\" or \"finally\" block during the grace period. When",
"logging from tfx import types from tfx.components.infra_validator import error_types from",
"os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator",
"to be stored in its own directory # structure flavor.",
"'has_model' # Filename of infra blessing artifact on succeed. _BLESSED_FILENAME",
"serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request:",
"tfx.proto import infra_validator_pb2 from tfx.types import artifact_utils from tfx.types.standard_component_specs import",
"proto_utils from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from",
"Other exceptions indicates validation failure. Log the error and #",
"from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs",
"== 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform",
"*args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self): for cleanup in",
"'INFRA_BLESSED' # Filename of infra blessing artifact on fail. _NOT_BLESSED_FILENAME",
"validating. - `examples`: `Examples` artifacts to be used for test",
"run in LOAD_AND_QUERY mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples,",
"You may obtain a copy of the License at #",
"if serving_binary == _TENSORFLOW_SERVING: # TensorFlow Serving requires model to",
"ModelServerRunner from a model, a ServingBinary and a ServingSpec. Args:",
"_InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior. Caveat: InfraValidator",
"Caveat: InfraValidator currently only recognizes SIGTERM signal as a graceful",
"# Copyright 2019 Google LLC. All Rights Reserved. # #",
"mode.') requests = [] model_path = self._PrepareModelPath(model, serving_spec) # TODO(jjong):",
"request_spec) else: request_spec = None with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples,",
"1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message",
"= serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can be",
"such mechanism (e.g. activeDeadlineSeconds in Kubernetes). \"\"\" def _handler(signum, frame):",
"time.time() + validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try:",
"validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples and request_spec: logging.info('InfraValidator",
"io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact) ->",
"a graceful shutdown. Furthermore, SIGTERM can be handled only if",
"interpreter) due to the limitation of Python API. When the",
"MainThread, it is not allowed to register # the signal",
"isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the value of ' 'ValidationSpec.max_loading_time_seconds.') else:",
"trial has failed. Marking model as not blessed. return False",
"to the limitation of Python API. When the executor is",
"SIGTERM signal as a graceful shutdown. Furthermore, SIGTERM can be",
"raising any exception. By registering a handler that raises on",
"prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert {type(request)} to PredictionLog')",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"receives SIGTERM, executor will die immediately without grace period. Even",
"all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed:",
"\"\"\"Create a ModelServerRunner from a model, a ServingBinary and a",
"NotImplementedError( f'Cannot convert {type(request)} to PredictionLog') def _mark_blessed(blessing: types.Artifact) ->",
"infra validation (attempt %d/%d).', i + 1, validation_spec.num_tries) try: self._ValidateOnce(",
"= 'has_model' # Filename of infra blessing artifact on succeed.",
"convert {type(request)} to PredictionLog') def _mark_blessed(blessing: types.Artifact) -> None: logging.info('Model",
"executor is run by the local Beam DirectRunner, the executor",
"model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner(",
"serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING: # TensorFlow Serving requires model",
"\"\"\"Contract for running InfraValidator Executor. Args: input_dict: - `model`: Single",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. # You may obtain a copy of the License",
"output_dict: - `blessing`: Single `InfraBlessing` artifact containing the validated result",
"self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing) if",
"elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec )",
"a ServingBinary and a ServingSpec. Args: model_path: An IV-flavored model",
"Serialized `ServingSpec` configuration. - `validation_spec`: Serialized `ValidationSpec` configuration. - `request_spec`:",
"def _ValidateOnce( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec:",
"of Python API. When the executor is running on Kubernetes,",
"not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY):",
"comply with the tensorflow serving model path # flavor. temp_model_path",
"be used for test requests. output_dict: - `blessing`: Single `InfraBlessing`",
"used for test requests. output_dict: - `blessing`: Single `InfraBlessing` artifact",
"model as not blessed. return False def _ValidateOnce( self, model_path:",
"to TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif",
"the MainThread (the thread that runs the python interpreter) due",
"request_builder from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import types as",
"thread that runs the python interpreter) due to the limitation",
"Serving requires model to be stored in its own directory",
"whether current model_path conforms to the tensorflow serving # model",
"to make a copy to the temporary path. try: #",
"one of the worker threads (not a MainThread) therefore SIGTERM",
"optinally validated model if warmup requests are appended. Artifact URI",
"empty file with the name either of INFRA_BLESSED or INFRA_NOT_BLESSED.",
"No more retry and # escalate the error. raise except",
"to comply with the tensorflow serving model path # flavor.",
"therefore SIGTERM cannot be recognized. If either of MainThread or",
"requires model to be stored in its own directory #",
"temp_model_path return model_path def _ValidateWithRetry( self, model_path: str, serving_binary: serving_bins.ServingBinary,",
"tfx.utils import io_utils from tfx.utils import path_utils from tfx.utils import",
"signal as a graceful shutdown. Furthermore, SIGTERM can be handled",
"proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec = None with self._InstallGracefulShutdownHandler(): self._Do( model=model,",
"Make logic parallel. all_passed = True for serving_binary in serving_bins.parse_serving_binaries(serving_spec):",
"from tfx.proto import infra_validator_pb2 from tfx.types import artifact_utils from tfx.types.standard_component_specs",
"import tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import predict_pb2",
"self).__init__(context) self._cleanups = [] def _AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function,",
"if not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds",
"# limitations under the License. \"\"\"TFX InfraValidator executor definition.\"\"\" import",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert {type(request)} to",
"in self._cleanups: try: cleanup() except: # pylint: disable=broad-except, bare-except logging.warning('Error",
"tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import base_executor from tfx.proto import",
"_BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of infra blessing artifact on",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"try: cleanup() except: # pylint: disable=broad-except, bare-except logging.warning('Error occurred during",
"model_path: An IV-flavored model path. (See model_path_utils.py) serving_binary: One of",
"old_handler = signal.signal(signal.SIGTERM, _handler) except ValueError: # If current thread",
"of ' 'ValidationSpec.max_loading_time_seconds.') else: # If validation has passed without",
"else: logging.info('InfraValidator will be run in LOAD_ONLY mode.') requests =",
"required by applicable law or agreed to in writing, software",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import",
"serving_binary: One of ServingBinary instances parsed from the `serving_spec`. serving_spec:",
"if platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec )",
"or \"finally\" block during the grace period. When the executor",
"exception, succeeded. return True # Every trial has failed. Marking",
"validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.',",
"thread receives SIGTERM, executor will die immediately without grace period.",
"# structure flavor. If current model_path does not conform to",
"Copy the model to comply with the tensorflow serving model",
"test requests. output_dict: - `blessing`: Single `InfraBlessing` artifact containing the",
"examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec],",
"logic parallel. all_passed = True for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed",
"agreed to in writing, software # distributed under the License",
"distributed under the License is distributed on an \"AS IS\"",
"os import signal import threading import time from typing import",
"(attempt %d/%d).', i + 1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary,",
"infra validation. Returns: A ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform') if",
"ServingBinary instances parsed from the `serving_spec`. serving_spec: A ServingSpec instance",
"local_docker_runner from tfx.dsl.components.base import base_executor from tfx.proto import infra_validator_pb2 from",
"When the executor is running on Kubernetes, SIGTERM is a",
"the worker threads (not a MainThread) therefore SIGTERM cannot be",
"as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner",
"and we can reuse our cleanup code inside \"except\" or",
"tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import",
"validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install",
"def __init__(self, context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context) self._cleanups =",
"handled.', threading.current_thread().name) old_handler = None try: yield finally: self._Cleanup() if",
"[] def _AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def",
"'infra-validation-model' # Proto message keys for oneof block. _TENSORFLOW_SERVING =",
"the executor fails to shutdown gracefully, external resources that are",
"'local_docker' _KUBERNETES = 'kubernetes' # Artifact property keys _BLESSED_KEY =",
"{}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra validation request to",
"the License. \"\"\"TFX InfraValidator executor definition.\"\"\" import contextlib import functools",
"tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import",
"self._log_startup(input_dict, output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if",
"logging.info('Starting infra validation (attempt %d/%d).', i + 1, validation_spec.num_tries) try:",
"logging.info('Model failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0)",
"transform the signal to an exception, and we can reuse",
"serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra validation request",
"conform to the flavor, # we need to make a",
"# Artifact property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model'",
"): if examples and request_spec: logging.info('InfraValidator will be run in",
"predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES",
"tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError: # Copy the model to",
"oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES =",
"this infra validation. Returns: A ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform')",
"def _mark_blessed(blessing: types.Artifact) -> None: logging.info('Model passed infra validation.') io_utils.write_string_file(",
"model_path def _ValidateWithRetry( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec,",
"URI includes an empty file with the name either of",
"we can reuse our cleanup code inside \"except\" or \"finally\"",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"= artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY])",
"serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline =",
"the License is distributed on an \"AS IS\" BASIS, #",
"SIGTERM cannot be recognized. If either of MainThread or worker",
"keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename of",
"= 'infra-validation-model' # Proto message keys for oneof block. _TENSORFLOW_SERVING",
"model is successfully loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline,",
"validation request to TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog(",
"infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor):",
"means infra validation aborted. No more retry and # escalate",
"= None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name:",
"= _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY):",
"# TODO(jjong): Make logic parallel. all_passed = True for serving_binary",
"validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec)",
"and a ServingSpec. Args: model_path: An IV-flavored model path. (See",
"law or agreed to in writing, software # distributed under",
"receiving SIGTERM is to terminate the process without raising any",
"temporary path. try: # Check whether current model_path conforms to",
"activeDeadlineSeconds in Kubernetes). \"\"\" def _handler(signum, frame): del frame #",
"failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class",
"model if warmup requests are appended. Artifact URI includes an",
"only if the executor is running on the MainThread (the",
"try: old_handler = signal.signal(signal.SIGTERM, _handler) except ValueError: # If current",
"_PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path = path_utils.serving_model_path(",
"a MainThread) therefore SIGTERM cannot be recognized. If either of",
"signal {}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM, _handler) except ValueError: #",
"artifact containing the validated result and optinally validated model if",
"self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return model_path def _ValidateWithRetry( self, model_path:",
"may obtain a copy of the License at # #",
"# the signal handler (ValueError raised). logging.info('Unable to register signal",
"artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str,",
"artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else:",
"= 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message keys for",
"self._context.get_tmp_path()) return temp_model_path return model_path def _ValidateWithRetry( self, model_path: str,",
"exceptions indicates validation failure. Log the error and # retry.",
"model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact, model_path: str,",
"Optional[infra_validator_pb2.RequestSpec], ): if examples and request_spec: logging.info('InfraValidator will be run",
"the local Beam DirectRunner, the executor thread is one of",
"infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries: validation_spec.num_tries =",
"InfraValidator Executor. Args: input_dict: - `model`: Single `Model` artifact that",
"be cleaned up if the platform supports such mechanism (e.g.",
"may not use this file except in compliance with the",
"register # the signal handler (ValueError raised). logging.info('Unable to register",
"the error and # retry. logging.exception('Infra validation (attempt %d/%d) failed.',",
"this file except in compliance with the License. # You",
"By registering a handler that raises on signal, we can",
"is not allowed to register # the signal handler (ValueError",
"`blessing`: Single `InfraBlessing` artifact containing the validated result and optinally",
"executor thread is one of the worker threads (not a",
"cleaned up if the platform supports such mechanism (e.g. activeDeadlineSeconds",
"# # Licensed under the Apache License, Version 2.0 (the",
"except: # pylint: disable=broad-except, bare-except logging.warning('Error occurred during cleanup.', exc_info=True)",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"None: logging.info('Model failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY,",
"behavior for receiving SIGTERM is to terminate the process without",
"warmup requests are appended. Artifact URI includes an empty file",
"requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self,",
"- `examples`: `Examples` artifacts to be used for test requests.",
"its own directory # structure flavor. If current model_path does",
"model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return",
"artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None",
"configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing =",
"try: logging.info('Starting %r.', runner) runner.Start() # Check model is successfully",
"DirectRunner, the executor thread is one of the worker threads",
"exception, and we can reuse our cleanup code inside \"except\"",
"{type(request)} to PredictionLog') def _mark_blessed(blessing: types.Artifact) -> None: logging.info('Model passed",
"None): super(Executor, self).__init__(context) self._cleanups = [] def _AddCleanup(self, function, *args,",
"pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior. Caveat: InfraValidator currently only",
"SIGTERM will not be handled.', threading.current_thread().name) old_handler = None try:",
"serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i in",
"import proto_utils from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import classification_pb2",
"or implied. # See the License for the specific language",
"serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i",
"cleanup code inside \"except\" or \"finally\" block during the grace",
"= [] def _AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs))",
"the model to comply with the tensorflow serving model path",
"**kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self): for cleanup in self._cleanups:",
"model server runner can be cleaned up if the platform",
"_CreateWarmupModel(self, blessing: types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri)",
"Artifact property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model' #",
"up if the platform supports such mechanism (e.g. activeDeadlineSeconds in",
"prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request,",
"types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples",
"`examples`: `Examples` artifacts to be used for test requests. output_dict:",
"error_types.GracefulShutdown: # GracefulShutdown means infra validation aborted. No more retry",
"allowed to register # the signal handler (ValueError raised). logging.info('Unable",
"effectively transform the signal to an exception, and we can",
"model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]):",
"output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r",
"else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]):",
"validation failure. Log the error and # retry. logging.exception('Infra validation",
"model to be stored in its own directory # structure",
"infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples and request_spec:",
"validation (attempt %d/%d) failed.', i + 1, validation_spec.num_tries) if isinstance(e,",
"as a graceful shutdown. Furthermore, SIGTERM can be handled only",
"from the `serving_spec`. serving_spec: A ServingSpec instance of this infra",
"Google LLC. All Rights Reserved. # # Licensed under the",
"tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import",
"a model, a ServingBinary and a ServingSpec. Args: model_path: An",
"def _CreateWarmupModel(self, blessing: types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]): output_model_path =",
"'') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\" def",
"import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY",
"# model path flavor. (Parsed without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name)",
"infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec",
"thread is not a MainThread, it is not allowed to",
"except ValueError: # If current thread is not a MainThread,",
"# TensorFlow Serving requires model to be stored in its",
"infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i in range(validation_spec.num_tries): logging.info('Starting",
"_create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner",
"1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except",
"else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert",
"error. raise except Exception as e: # pylint: disable=broad-except #",
"for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES",
"REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from",
"def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a",
"client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can be successfully queried.",
"validator executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context)",
"on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary:",
"ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return",
"request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will be run",
"from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import types as iv_types",
"output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY):",
"need to make a copy to the temporary path. try:",
"model, a ServingBinary and a ServingSpec. Args: model_path: An IV-flavored",
"for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model: types.Artifact,",
"examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None serving_spec = infra_validator_pb2.ServingSpec()",
"by model server runner can be cleaned up if the",
"types.Artifact) -> None: logging.info('Model passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME),",
"= 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes' # Artifact",
"shutdown gracefully, external resources that are created by model server",
"aborted. No more retry and # escalate the error. raise",
"in writing, software # distributed under the License is distributed",
"requests = [] model_path = self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make",
"instance of this infra validation. Returns: A ModelServerRunner. \"\"\" platform",
"be stored in its own directory # structure flavor. If",
"successfully loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) #",
"standard way to signal the graceful shutdown. Python default behavior",
"old_handler = None try: yield finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM,",
"_ValidateWithRetry( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec,",
"List, Optional from absl import logging from tfx import types",
"that are created by model server runner can be cleaned",
"version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return model_path def",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"configuration. - `validation_spec`: Serialized `ValidationSpec` configuration. - `request_spec`: Serialized `RequestSpec`",
"(not a MainThread) therefore SIGTERM cannot be recognized. If either",
"of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized `ServingSpec` configuration.",
"tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import io_utils from tfx.utils import",
"tensorflow serving model path # flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(),",
"\"\"\" self._log_startup(input_dict, output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY])",
"graceful shutdown. Python default behavior for receiving SIGTERM is to",
"shutdown. Python default behavior for receiving SIGTERM is to terminate",
"platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif",
"the License for the specific language governing permissions and #",
"signal.signal(signal.SIGTERM, _handler) except ValueError: # If current thread is not",
"import base_executor from tfx.proto import infra_validator_pb2 from tfx.types import artifact_utils",
"error_types.DeadlineExceeded): logging.info('Consider increasing the value of ' 'ValidationSpec.max_loading_time_seconds.') else: #",
"= 'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename of infra blessing",
"old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do( self, model: types.Artifact, examples: Optional[types.Artifact],",
"dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return model_path def _ValidateWithRetry( self,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"fails to shutdown gracefully, external resources that are created by",
"not blessed. return False def _ValidateOnce( self, model_path: str, serving_binary:",
"artifact that we're validating. - `examples`: `Examples` artifacts to be",
"elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot",
"parsed from the `serving_spec`. serving_spec: A ServingSpec instance of this",
"validation aborted. No more retry and # escalate the error.",
"model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING: #",
"= _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else:",
"if the platform supports such mechanism (e.g. activeDeadlineSeconds in Kubernetes).",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes' # Artifact property",
"currently only recognizes SIGTERM signal as a graceful shutdown. Furthermore,",
"# Copy the model to comply with the tensorflow serving",
"types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec:",
"model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path = path_utils.serving_model_path( model.uri,",
"period. Even if the executor fails to shutdown gracefully, external",
"# If current thread is not a MainThread, it is",
"handler that raises on signal, we can effectively transform the",
"be recognized. If either of MainThread or worker thread receives",
"during cleanup.', exc_info=True) def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str,",
"# distributed under the License is distributed on an \"AS",
"import serving_bins from tfx.components.infra_validator import types as iv_types from tfx.components.infra_validator.model_server_runners",
"# Unless required by applicable law or agreed to in",
"blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str:",
"+ 1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the value",
"handler for non-MainThread ' '(name=%s). SIGTERM will not be handled.',",
"be run in LOAD_ONLY mode.') requests = [] model_path =",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis",
"predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert {type(request)}",
"cleanup.', exc_info=True) def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]],",
"str, warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path),",
"the signal handler (ValueError raised). logging.info('Unable to register signal handler",
"output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: \"\"\"Contract for",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"requests are appended. Artifact URI includes an empty file with",
"1) def _mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model failed infra validation.')",
"be handled.', threading.current_thread().name) old_handler = None try: yield finally: self._Cleanup()",
"file with the name either of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties:",
"_LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes' # Artifact property keys",
"`Model` artifact that we're validating. - `examples`: `Examples` artifacts to",
"ServingSpec. Args: model_path: An IV-flavored model path. (See model_path_utils.py) serving_binary:",
"threads (not a MainThread) therefore SIGTERM cannot be recognized. If",
"regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300",
"= [] model_path = self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make logic",
"model path. (See model_path_utils.py) serving_binary: One of ServingBinary instances parsed",
"MainThread (the thread that runs the python interpreter) due to",
"typing import Any, Dict, List, Optional from absl import logging",
"(the thread that runs the python interpreter) due to the",
"tfx.types import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import",
"LOAD_ONLY mode.') requests = [] model_path = self._PrepareModelPath(model, serving_spec) #",
"recognizes SIGTERM signal as a graceful shutdown. Furthermore, SIGTERM can",
"to PredictionLog') def _mark_blessed(blessing: types.Artifact) -> None: logging.info('Model passed infra",
"in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec)",
"# pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior. Caveat: InfraValidator currently",
"'') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model failed",
"import functools import os import signal import threading import time",
"platform supports such mechanism (e.g. activeDeadlineSeconds in Kubernetes). \"\"\" def",
"validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY],",
"serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline = time.time() +",
"under the License is distributed on an \"AS IS\" BASIS,",
"InfraValidator executor definition.\"\"\" import contextlib import functools import os import",
"validation (attempt %d/%d).', i + 1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path,",
"= path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary ==",
"worker threads (not a MainThread) therefore SIGTERM cannot be recognized.",
"IV-flavored model path. (See model_path_utils.py) serving_binary: One of ServingBinary instances",
"_TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes' #",
"range(validation_spec.num_tries): logging.info('Starting infra validation (attempt %d/%d).', i + 1, validation_spec.num_tries)",
"return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else:",
"Kubernetes, SIGTERM is a standard way to signal the graceful",
"infra validation aborted. No more retry and # escalate the",
"`serving_spec`. serving_spec: A ServingSpec instance of this infra validation. Returns:",
"current model_path does not conform to the flavor, # we",
"= _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if",
"import error_types from tfx.components.infra_validator import request_builder from tfx.components.infra_validator import serving_bins",
"request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install graceful",
"BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from",
"model: types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec,",
"import contextlib import functools import os import signal import threading",
"artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from",
"tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5",
"we're validating. - `examples`: `Examples` artifacts to be used for",
"def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra validation request to TF-Serving",
"'kubernetes' # Artifact property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY =",
"model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.', runner) runner.Start() # Check",
"+ validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting",
"def _AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self):",
"tfx.components.infra_validator import request_builder from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import",
"terminate the process without raising any exception. By registering a",
"requests: List[iv_types.Request]): for i in range(validation_spec.num_tries): logging.info('Starting infra validation (attempt",
"all_passed: _mark_blessed(blessing) if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else:",
"\"except\" or \"finally\" block during the grace period. When the",
"under the License. \"\"\"TFX InfraValidator executor definition.\"\"\" import contextlib import",
"infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline = time.time() + validation_spec.max_loading_time_seconds runner =",
"raise NotImplementedError( f'Cannot convert {type(request)} to PredictionLog') def _mark_blessed(blessing: types.Artifact)",
"runner can be cleaned up if the platform supports such",
"from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES =",
"runner.Start() # Check model is successfully loaded. runner.WaitUntilRunning(deadline) client =",
"runner) runner.Start() # Check model is successfully loaded. runner.WaitUntilRunning(deadline) client",
"ANY KIND, either express or implied. # See the License",
"the License. # You may obtain a copy of the",
"can reuse our cleanup code inside \"except\" or \"finally\" block",
"A ServingSpec instance of this infra validation. Returns: A ModelServerRunner.",
"tensorflow serving # model path flavor. (Parsed without exception) tf_serving_flavor.parse_model_path(",
"# See the License for the specific language governing permissions",
"serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name: serving_spec.model_name =",
"import io_utils from tfx.utils import path_utils from tfx.utils import proto_utils",
"raised). logging.info('Unable to register signal handler for non-MainThread ' '(name=%s).",
"logging.info('Model passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1)",
"import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import base_executor",
"self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self): for cleanup in self._cleanups: try:",
"blessing = artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples",
"exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec = None",
"`RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties) model = artifact_utils.get_single_instance(input_dict[MODEL_KEY]) blessing",
"from tfx.types import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs",
"in its own directory # structure flavor. If current model_path",
"# Filename of infra blessing artifact on fail. _NOT_BLESSED_FILENAME =",
"from tfx.components.infra_validator import types as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner",
"= time.time() + validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec)",
"def _handler(signum, frame): del frame # Unused. raise error_types.GracefulShutdown('Got signal",
"infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing:",
"infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline = time.time() + validation_spec.max_loading_time_seconds",
"self._cleanups: try: cleanup() except: # pylint: disable=broad-except, bare-except logging.warning('Error occurred",
"def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str,",
"on Kubernetes, SIGTERM is a standard way to signal the",
"raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM, _handler) except",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"writing, software # distributed under the License is distributed on",
"regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError(",
"Any]) -> None: \"\"\"Contract for running InfraValidator Executor. Args: input_dict:",
"if not serving_spec.model_name: serving_spec.model_name = _DEFAULT_MODEL_NAME validation_spec = infra_validator_pb2.ValidationSpec() if",
"executor definition.\"\"\" import contextlib import functools import os import signal",
"recognized. If either of MainThread or worker thread receives SIGTERM,",
"not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec()",
"registering a handler that raises on signal, we can effectively",
"from tfx.utils import proto_utils from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis",
"model_path: str, warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file(",
"only recognizes SIGTERM signal as a graceful shutdown. Furthermore, SIGTERM",
"artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec)",
"INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized `ServingSpec` configuration. -",
"raises on signal, we can effectively transform the signal to",
"Optional from absl import logging from tfx import types from",
"succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of infra blessing artifact",
"GracefulShutdown means infra validation aborted. No more retry and #",
"that runs the python interpreter) due to the limitation of",
"License. \"\"\"TFX InfraValidator executor definition.\"\"\" import contextlib import functools import",
"(ValueError raised). logging.info('Unable to register signal handler for non-MainThread '",
"executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context) self._cleanups",
"a standard way to signal the graceful shutdown. Python default",
"A ModelServerRunner. \"\"\" platform = serving_spec.WhichOneof('serving_platform') if platform == 'local_docker':",
"_DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message keys for oneof block.",
"**kwargs)) def _Cleanup(self): for cleanup in self._cleanups: try: cleanup() except:",
"Check model is successfully loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded(",
"infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec = None with self._InstallGracefulShutdownHandler(): self._Do(",
"self, model: types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec:",
"governing permissions and # limitations under the License. \"\"\"TFX InfraValidator",
"_ValidateOnce( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec,",
"e: # pylint: disable=broad-except # Other exceptions indicates validation failure.",
"due to the limitation of Python API. When the executor",
"any exception. By registering a handler that raises on signal,",
"input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None serving_spec =",
"the tensorflow serving model path # flavor. temp_model_path = tf_serving_flavor.make_model_path(",
"(Parsed without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError: # Copy",
"import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import io_utils",
"{}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM, _handler) except ValueError: # If",
"model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self):",
"context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context) self._cleanups = [] def",
"io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return model_path def _ValidateWithRetry(",
"includes an empty file with the name either of INFRA_BLESSED",
"not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds =",
"import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC",
"error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM, _handler) except ValueError:",
"signal handler (ValueError raised). logging.info('Unable to register signal handler for",
"\"\"\"Install graceful shutdown behavior. Caveat: InfraValidator currently only recognizes SIGTERM",
"from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs",
"infra blessing artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner(",
"serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec,",
"-> None: logging.info('Model passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '')",
"warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact, model_path: str, warmup_requests:",
"== _TENSORFLOW_SERVING: # TensorFlow Serving requires model to be stored",
"be successfully queried. if requests: client.SendRequests(requests) finally: logging.info('Stopping %r.', runner)",
"serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec",
"serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from a model, a ServingBinary",
"signal, we can effectively transform the signal to an exception,",
"serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples and",
"for running InfraValidator Executor. Args: input_dict: - `model`: Single `Model`",
"the name either of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`:",
"server runner can be cleaned up if the platform supports",
"model_path = self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make logic parallel. all_passed",
"model_path_utils.py) serving_binary: One of ServingBinary instances parsed from the `serving_spec`.",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError: # Copy the",
"tfx import types from tfx.components.infra_validator import error_types from tfx.components.infra_validator import",
"non-MainThread ' '(name=%s). SIGTERM will not be handled.', threading.current_thread().name) old_handler",
"model can be successfully queried. if requests: client.SendRequests(requests) finally: logging.info('Stopping",
"for non-MainThread ' '(name=%s). SIGTERM will not be handled.', threading.current_thread().name)",
"'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"python interpreter) due to the limitation of Python API. When",
"= 'INFRA_BLESSED' # Filename of infra blessing artifact on fail.",
"input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) ->",
"deadline = time.time() + validation_spec.max_loading_time_seconds runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary,",
"signal import threading import time from typing import Any, Dict,",
"the executor is running on the MainThread (the thread that",
"if exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES",
"_Cleanup(self): for cleanup in self._cleanups: try: cleanup() except: # pylint:",
"executor is running on the MainThread (the thread that runs",
"If validation has passed without any exception, succeeded. return True",
"types.Artifact, model_path: str, warmup_requests: List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path)",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"mechanism (e.g. activeDeadlineSeconds in Kubernetes). \"\"\" def _handler(signum, frame): del",
"deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can be successfully queried. if",
"path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in warmup_requests])",
"ValueError: # Copy the model to comply with the tensorflow",
"LOAD_AND_QUERY mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else:",
"SIGTERM is to terminate the process without raising any exception.",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary",
"Check whether current model_path conforms to the tensorflow serving #",
"signal to an exception, and we can reuse our cleanup",
"str: model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if",
"Rights Reserved. # # Licensed under the Apache License, Version",
"client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can",
"proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if not",
"from tfx.utils import io_utils from tfx.utils import path_utils from tfx.utils",
"specific language governing permissions and # limitations under the License.",
"configuration. - `request_spec`: Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties)",
"be handled only if the executor is running on the",
"Single `Model` artifact that we're validating. - `examples`: `Examples` artifacts",
"300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message keys for oneof",
"reuse our cleanup code inside \"except\" or \"finally\" block during",
"will die immediately without grace period. Even if the executor",
"= 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec):",
"created by model server runner can be cleaned up if",
"model_path does not conform to the flavor, # we need",
"MainThread) therefore SIGTERM cannot be recognized. If either of MainThread",
"model_path conforms to the tensorflow serving # model path flavor.",
"# you may not use this file except in compliance",
"if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec =",
"super(Executor, self).__init__(context) self._cleanups = [] def _AddCleanup(self, function, *args, **kwargs):",
"can be successfully queried. if requests: client.SendRequests(requests) finally: logging.info('Stopping %r.',",
"%r.', runner) runner.Start() # Check model is successfully loaded. runner.WaitUntilRunning(deadline)",
"if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def",
"frame): del frame # Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try:",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"serving_spec: A ServingSpec instance of this infra validation. Returns: A",
"_AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args, **kwargs)) def _Cleanup(self): for",
"error and # retry. logging.exception('Infra validation (attempt %d/%d) failed.', i",
"= serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary,",
"predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert {type(request)} to PredictionLog') def",
"validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC",
"= None with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec,",
"= infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec = None with self._InstallGracefulShutdownHandler():",
"we need to make a copy to the temporary path.",
"handled only if the executor is running on the MainThread",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"requests=requests) if all_passed: _mark_blessed(blessing) if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path,",
"import os import signal import threading import time from typing",
"= serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING: # TensorFlow Serving requires",
"serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING: # TensorFlow Serving",
"model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from",
"the signal to an exception, and we can reuse our",
"\"\"\"TFX InfraValidator executor definition.\"\"\" import contextlib import functools import os",
"dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1)",
"_KUBERNETES = 'kubernetes' # Artifact property keys _BLESSED_KEY = 'blessed'",
"def _Do( self, model: types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec:",
"return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif",
"or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized `ServingSpec` configuration. - `validation_spec`:",
"Serialized `ValidationSpec` configuration. - `request_spec`: Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict,",
"= artifact_utils.get_single_instance(output_dict[BLESSING_KEY]) if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples =",
"%d/%d).', i + 1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec,",
"not allowed to register # the signal handler (ValueError raised).",
"regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request))",
"and # limitations under the License. \"\"\"TFX InfraValidator executor definition.\"\"\"",
"requests: List[iv_types.Request]): deadline = time.time() + validation_spec.max_loading_time_seconds runner = _create_model_server_runner(",
"request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples and request_spec: logging.info('InfraValidator will be",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"try: yield finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do(",
"exec_properties: - `serving_spec`: Serialized `ServingSpec` configuration. - `validation_spec`: Serialized `ValidationSpec`",
"for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec,",
"validated model if warmup requests are appended. Artifact URI includes",
"and request_spec: logging.info('InfraValidator will be run in LOAD_AND_QUERY mode.') requests",
"PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest):",
"API. When the executor is running on Kubernetes, SIGTERM is",
"passed without any exception, succeeded. return True # Every trial",
"the executor thread is one of the worker threads (not",
"with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, )",
"Filename of infra blessing artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED'",
"-> str: model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary')",
"Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None:",
"serving_bins from tfx.components.infra_validator import types as iv_types from tfx.components.infra_validator.model_server_runners import",
"with the name either of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: -",
"the platform supports such mechanism (e.g. activeDeadlineSeconds in Kubernetes). \"\"\"",
"import path_utils from tfx.utils import proto_utils from tfx.utils.model_paths import tf_serving_flavor",
"_mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri,",
"logging.info('Starting %r.', runner) runner.Start() # Check model is successfully loaded.",
"`request_spec`: Serialized `RequestSpec` configuration. \"\"\" self._log_startup(input_dict, output_dict, exec_properties) model =",
"= None try: yield finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler)",
"the temporary path. try: # Check whether current model_path conforms",
"warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) ->",
"the flavor, # we need to make a copy to",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"from a model, a ServingBinary and a ServingSpec. Args: model_path:",
"thread is one of the worker threads (not a MainThread)",
"List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: \"\"\"Contract",
"-> None: logging.info('Model failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '')",
"disable=broad-except, bare-except logging.warning('Error occurred during cleanup.', exc_info=True) def Do(self, input_dict:",
"result and optinally validated model if warmup requests are appended.",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.', runner) runner.Start() # Check model",
"either express or implied. # See the License for the",
"def _PrepareModelPath(self, model: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path =",
"signal handler for non-MainThread ' '(name=%s). SIGTERM will not be",
"infra_validator_pb2.ServingSpec) -> str: model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary =",
"handler (ValueError raised). logging.info('Unable to register signal handler for non-MainThread",
"the validated result and optinally validated model if warmup requests",
"local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform == 'kubernetes': return",
"is run by the local Beam DirectRunner, the executor thread",
"the error. raise except Exception as e: # pylint: disable=broad-except",
"model path flavor. (Parsed without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except",
"appended. Artifact URI includes an empty file with the name",
"Executor. Args: input_dict: - `model`: Single `Model` artifact that we're",
"= tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return",
"Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict: Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any])",
"MainThread or worker thread receives SIGTERM, executor will die immediately",
"validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown:",
"def _Cleanup(self): for cleanup in self._cleanups: try: cleanup() except: #",
"limitation of Python API. When the executor is running on",
"except ValueError: # Copy the model to comply with the",
"not be handled.', threading.current_thread().name) old_handler = None try: yield finally:",
"request to TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request))",
"infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i in range(validation_spec.num_tries): logging.info('Starting infra validation",
"infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if examples and request_spec: logging.info('InfraValidator will",
"== 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise",
"# pylint: disable=broad-except, bare-except logging.warning('Error occurred during cleanup.', exc_info=True) def",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"not conform to the flavor, # we need to make",
"without raising any exception. By registering a handler that raises",
"classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request))",
"Any, Dict, List, Optional from absl import logging from tfx",
"# pylint: disable=broad-except # Other exceptions indicates validation failure. Log",
"in LOAD_ONLY mode.') requests = [] model_path = self._PrepareModelPath(model, serving_spec)",
"runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint()) client.WaitUntilModelLoaded( deadline, polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model",
"running on Kubernetes, SIGTERM is a standard way to signal",
"tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import",
"flavor. (Parsed without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError: #",
"r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model: types.Artifact, serving_spec:",
"increasing the value of ' 'ValidationSpec.max_loading_time_seconds.') else: # If validation",
"exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError: # Copy the model",
"_DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME",
"self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests:",
"on the MainThread (the thread that runs the python interpreter)",
"raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try convert infra",
"import classification_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2",
"INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized `ServingSpec` configuration. - `validation_spec`: Serialized",
"of this infra validation. Returns: A ModelServerRunner. \"\"\" platform =",
"- `serving_spec`: Serialized `ServingSpec` configuration. - `validation_spec`: Serialized `ValidationSpec` configuration.",
"the value of ' 'ValidationSpec.max_loading_time_seconds.') else: # If validation has",
"property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename",
"path # flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path,",
"None try: yield finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler) def",
"import time from typing import Any, Dict, List, Optional from",
"by the local Beam DirectRunner, the executor thread is one",
"prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise",
"can be cleaned up if the platform supports such mechanism",
"validation_spec.num_tries = _DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if",
"disable=g-doc-return-or-yield \"\"\"Install graceful shutdown behavior. Caveat: InfraValidator currently only recognizes",
"Copyright 2019 Google LLC. All Rights Reserved. # # Licensed",
"finally: self._Cleanup() if old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do( self, model:",
"%d/%d) failed.', i + 1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider",
"os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact) -> None:",
"the `serving_spec`. serving_spec: A ServingSpec instance of this infra validation.",
"LLC. All Rights Reserved. # # Licensed under the Apache",
"from tfx.components.infra_validator import error_types from tfx.components.infra_validator import request_builder from tfx.components.infra_validator",
"i in range(validation_spec.num_tries): logging.info('Starting infra validation (attempt %d/%d).', i +",
"str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from a",
"Check model can be successfully queried. if requests: client.SendRequests(requests) finally:",
"indicates validation failure. Log the error and # retry. logging.exception('Infra",
"use this file except in compliance with the License. #",
"definition.\"\"\" import contextlib import functools import os import signal import",
"the limitation of Python API. When the executor is running",
"_DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec",
"that raises on signal, we can effectively transform the signal",
"from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis",
"_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model",
"an exception, and we can reuse our cleanup code inside",
"SIGTERM can be handled only if the executor is running",
"return True # Every trial has failed. Marking model as",
"# Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM,",
"of the worker threads (not a MainThread) therefore SIGTERM cannot",
"flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir,",
"any exception, succeeded. return True # Every trial has failed.",
"retry and # escalate the error. raise except Exception as",
"tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import",
"without grace period. Even if the executor fails to shutdown",
"in compliance with the License. # You may obtain a",
"code inside \"except\" or \"finally\" block during the grace period.",
"software # distributed under the License is distributed on an",
"self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing) def _CreateWarmupModel(self, blessing: types.Artifact, model_path:",
"is a standard way to signal the graceful shutdown. Python",
"= self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make logic parallel. all_passed =",
"`InfraBlessing` artifact containing the validated result and optinally validated model",
"if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec =",
"permissions and # limitations under the License. \"\"\"TFX InfraValidator executor",
"way to signal the graceful shutdown. Python default behavior for",
"serving_spec=serving_spec ) elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary,",
"for test requests. output_dict: - `blessing`: Single `InfraBlessing` artifact containing",
"_create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.', runner) runner.Start() #",
"if the executor fails to shutdown gracefully, external resources that",
"Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler = signal.signal(signal.SIGTERM, _handler)",
"*[_convert_to_prediction_log(r) for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self, model:",
"'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): \"\"\"Create",
"serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: # GracefulShutdown means infra validation",
"running InfraValidator Executor. Args: input_dict: - `model`: Single `Model` artifact",
"# Check whether current model_path conforms to the tensorflow serving",
"examples and request_spec: logging.info('InfraValidator will be run in LOAD_AND_QUERY mode.')",
"can effectively transform the signal to an exception, and we",
"with the License. # You may obtain a copy of",
"error_types from tfx.components.infra_validator import request_builder from tfx.components.infra_validator import serving_bins from",
"register signal handler for non-MainThread ' '(name=%s). SIGTERM will not",
"_mark_blessed(blessing) if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests) else: _mark_not_blessed(blessing)",
"types.Artifact) -> None: logging.info('Model failed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME),",
"validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the value of '",
"Dict[str, List[types.Artifact]], exec_properties: Dict[str, Any]) -> None: \"\"\"Contract for running",
"for cleanup in self._cleanups: try: cleanup() except: # pylint: disable=broad-except,",
"io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def",
"serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield",
"from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis",
"i + 1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing the",
"functools import os import signal import threading import time from",
"from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import io_utils from tfx.utils",
"TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request,",
"from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs",
"self._PrepareModelPath(model, serving_spec) # TODO(jjong): Make logic parallel. all_passed = True",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes'",
"Furthermore, SIGTERM can be handled only if the executor is",
"blessing=blessing, serving_spec=serving_spec, validation_spec=validation_spec, request_spec=request_spec, ) @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint:",
"serving_spec: infra_validator_pb2.ServingSpec) -> str: model_path = path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary",
"False def _ValidateOnce( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec,",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"of infra blessing artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def",
"validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: # GracefulShutdown means infra validation aborted.",
"gracefully, external resources that are created by model server runner",
"during the grace period. When the executor is run by",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"from tfx.utils import path_utils from tfx.utils import proto_utils from tfx.utils.model_paths",
"current thread is not a MainThread, it is not allowed",
"blessed. return False def _ValidateOnce( self, model_path: str, serving_binary: serving_bins.ServingBinary,",
"List[iv_types.Request]): output_model_path = path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for",
"List[iv_types.Request]): for i in range(validation_spec.num_tries): logging.info('Starting infra validation (attempt %d/%d).',",
"from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils",
"serving # model path flavor. (Parsed without exception) tf_serving_flavor.parse_model_path( model_path,",
"from tfx.dsl.components.base import base_executor from tfx.proto import infra_validator_pb2 from tfx.types",
"process without raising any exception. By registering a handler that",
"the process without raising any exception. By registering a handler",
"try: # Check whether current model_path conforms to the tensorflow",
"infra validation request to TF-Serving PredictionLog.\"\"\" if isinstance(request, classification_pb2.ClassificationRequest): return",
"infra_validator_pb2.ServingSpec): \"\"\"Create a ModelServerRunner from a model, a ServingBinary and",
"flavor. If current model_path does not conform to the flavor,",
"instances parsed from the `serving_spec`. serving_spec: A ServingSpec instance of",
"return False def _ValidateOnce( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec:",
"temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path())",
"examples = None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not",
"Dict, List, Optional from absl import logging from tfx import",
"# retry. logging.exception('Infra validation (attempt %d/%d) failed.', i + 1,",
"Args: model_path: An IV-flavored model path. (See model_path_utils.py) serving_binary: One",
"and # retry. logging.exception('Infra validation (attempt %d/%d) failed.', i +",
"request_spec = None with self._InstallGracefulShutdownHandler(): self._Do( model=model, examples=examples, blessing=blessing, serving_spec=serving_spec,",
"of MainThread or worker thread receives SIGTERM, executor will die",
"None: logging.info('Model passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY,",
"(See model_path_utils.py) serving_binary: One of ServingBinary instances parsed from the",
"None: \"\"\"Contract for running InfraValidator Executor. Args: input_dict: - `model`:",
"are appended. Artifact URI includes an empty file with the",
"model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will be run in",
"will be run in LOAD_AND_QUERY mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name,",
"validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing) if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing,",
"time from typing import Any, Dict, List, Optional from absl",
"name either of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized",
"executor will die immediately without grace period. Even if the",
"tfx.components.infra_validator import types as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from",
"EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from",
"iv_types.Request): \"\"\"Try convert infra validation request to TF-Serving PredictionLog.\"\"\" if",
"immediately without grace period. Even if the executor fails to",
"platform = serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path,",
"executor fails to shutdown gracefully, external resources that are created",
"make a copy to the temporary path. try: # Check",
"= 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME =",
"= path_utils.stamped_model_path(blessing.uri) io_utils.copy_dir(src=model_path, dst=output_model_path) io_utils.write_tfrecord_file( path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in",
"block during the grace period. When the executor is run",
"import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY",
"# Check model is successfully loaded. runner.WaitUntilRunning(deadline) client = serving_binary.MakeClient(runner.GetEndpoint())",
"model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing) if requests",
"failed.', i + 1, validation_spec.num_tries) if isinstance(e, error_types.DeadlineExceeded): logging.info('Consider increasing",
"ServingSpec instance of this infra validation. Returns: A ModelServerRunner. \"\"\"",
"die immediately without grace period. Even if the executor fails",
"keys for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker'",
"worker thread receives SIGTERM, executor will die immediately without grace",
"return model_path def _ValidateWithRetry( self, model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec:",
"_MODEL_FLAG_KEY = 'has_model' # Filename of infra blessing artifact on",
"to register # the signal handler (ValueError raised). logging.info('Unable to",
"the executor is running on Kubernetes, SIGTERM is a standard",
"blessing.set_int_custom_property(_BLESSED_KEY, 1) def _mark_not_blessed(blessing: types.Artifact) -> None: logging.info('Model failed infra",
"to the tensorflow serving # model path flavor. (Parsed without",
"-> None: \"\"\"Contract for running InfraValidator Executor. Args: input_dict: -",
"more retry and # escalate the error. raise except Exception",
"mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec) else: logging.info('InfraValidator",
"else: examples = None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if",
"runner = _create_model_server_runner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec) try: logging.info('Starting %r.', runner)",
"tfx.components.infra_validator import error_types from tfx.components.infra_validator import request_builder from tfx.components.infra_validator import",
"all_passed = True for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry(",
"Even if the executor fails to shutdown gracefully, external resources",
"f'Cannot convert {type(request)} to PredictionLog') def _mark_blessed(blessing: types.Artifact) -> None:",
"`validation_spec`: Serialized `ValidationSpec` configuration. - `request_spec`: Serialized `RequestSpec` configuration. \"\"\"",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or worker thread receives SIGTERM, executor will die immediately without",
"threading.current_thread().name) old_handler = None try: yield finally: self._Cleanup() if old_handler:",
"= 'kubernetes' # Artifact property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY",
"to the temporary path. try: # Check whether current model_path",
"stored in its own directory # structure flavor. If current",
"import types from tfx.components.infra_validator import error_types from tfx.components.infra_validator import request_builder",
"Python API. When the executor is running on Kubernetes, SIGTERM",
"copy to the temporary path. try: # Check whether current",
"model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path return model_path",
"to shutdown gracefully, external resources that are created by model",
"passed infra validation.') io_utils.write_string_file( os.path.join(blessing.uri, _BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 1) def",
"resources that are created by model server runner can be",
"if input_dict.get(EXAMPLES_KEY): examples = artifact_utils.get_single_instance(input_dict[EXAMPLES_KEY]) else: examples = None serving_spec",
"request_spec = infra_validator_pb2.RequestSpec() proto_utils.json_to_proto(exec_properties[REQUEST_SPEC_KEY], request_spec) else: request_spec = None with",
"import request_builder from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import types",
"None serving_spec = infra_validator_pb2.ServingSpec() proto_utils.json_to_proto(exec_properties[SERVING_SPEC_KEY], serving_spec) if not serving_spec.model_name: serving_spec.model_name",
"path flavor. (Parsed without exception) tf_serving_flavor.parse_model_path( model_path, expected_model_name=serving_spec.model_name) except ValueError:",
"Version 2.0 (the \"License\"); # you may not use this",
"When the executor is run by the local Beam DirectRunner,",
"path_utils.serving_model_path( model.uri, path_utils.is_old_model_artifact(model)) serving_binary = serving_spec.WhichOneof('serving_binary') if serving_binary == _TENSORFLOW_SERVING:",
"ValueError: # If current thread is not a MainThread, it",
"pylint: disable=broad-except, bare-except logging.warning('Error occurred during cleanup.', exc_info=True) def Do(self,",
"the executor is run by the local Beam DirectRunner, the",
") @contextlib.contextmanager def _InstallGracefulShutdownHandler(self): # pylint: disable=g-doc-return-or-yield \"\"\"Install graceful shutdown",
"failed. Marking model as not blessed. return False def _ValidateOnce(",
"validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): deadline = time.time() + validation_spec.max_loading_time_seconds runner",
"= True for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path,",
"succeeded. return True # Every trial has failed. Marking model",
"isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert",
"classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest):",
"\"\"\"TFX infra validator executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context] = None):",
"by applicable law or agreed to in writing, software #",
"serving_binary == _TENSORFLOW_SERVING: # TensorFlow Serving requires model to be",
"if the executor is running on the MainThread (the thread",
"from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base",
"blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra validator executor.\"\"\" def __init__(self,",
"2019 Google LLC. All Rights Reserved. # # Licensed under",
"in serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests)",
"to an exception, and we can reuse our cleanup code",
"_Do( self, model: types.Artifact, examples: Optional[types.Artifact], blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec,",
"from absl import logging from tfx import types from tfx.components.infra_validator",
"is one of the worker threads (not a MainThread) therefore",
"we can effectively transform the signal to an exception, and",
"isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog(",
"Single `InfraBlessing` artifact containing the validated result and optinally validated",
"a ServingSpec. Args: model_path: An IV-flavored model path. (See model_path_utils.py)",
"An IV-flavored model path. (See model_path_utils.py) serving_binary: One of ServingBinary",
"parallel. all_passed = True for serving_binary in serving_bins.parse_serving_binaries(serving_spec): all_passed &=",
"if warmup requests are appended. Artifact URI includes an empty",
"local Beam DirectRunner, the executor thread is one of the",
"blessing: types.Artifact, serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, request_spec: Optional[infra_validator_pb2.RequestSpec], ): if",
"serving_spec: infra_validator_pb2.ServingSpec, validation_spec: infra_validator_pb2.ValidationSpec, requests: List[iv_types.Request]): for i in range(validation_spec.num_tries):",
"Marking model as not blessed. return False def _ValidateOnce( self,",
"prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC =",
"MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from",
"io_utils.write_string_file( os.path.join(blessing.uri, _NOT_BLESSED_FILENAME), '') blessing.set_int_custom_property(_BLESSED_KEY, 0) class Executor(base_executor.BaseExecutor): \"\"\"TFX infra",
"__init__(self, context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor, self).__init__(context) self._cleanups = []",
"serving_spec=serving_spec) try: logging.info('Starting %r.', runner) runner.Start() # Check model is",
"Filename of infra blessing artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED'",
"applicable law or agreed to in writing, software # distributed",
"for receiving SIGTERM is to terminate the process without raising",
"Python default behavior for receiving SIGTERM is to terminate the",
"model path # flavor. temp_model_path = tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time()))",
"supports such mechanism (e.g. activeDeadlineSeconds in Kubernetes). \"\"\" def _handler(signum,",
"io_utils from tfx.utils import path_utils from tfx.utils import proto_utils from",
"Log the error and # retry. logging.exception('Infra validation (attempt %d/%d)",
"either of INFRA_BLESSED or INFRA_NOT_BLESSED. exec_properties: - `serving_spec`: Serialized `ServingSpec`",
"Args: input_dict: - `model`: Single `Model` artifact that we're validating.",
"' 'ValidationSpec.max_loading_time_seconds.') else: # If validation has passed without any",
"polling_interval_sec=_DEFAULT_POLLING_INTERVAL_SEC) # Check model can be successfully queried. if requests:",
"of ServingBinary instances parsed from the `serving_spec`. serving_spec: A ServingSpec",
"# You may obtain a copy of the License at",
"are created by model server runner can be cleaned up",
"TODO(jjong): Make logic parallel. all_passed = True for serving_binary in",
"to the flavor, # we need to make a copy",
"the python interpreter) due to the limitation of Python API.",
"_DEFAULT_NUM_TRIES if not validation_spec.max_loading_time_seconds: validation_spec.max_loading_time_seconds = _DEFAULT_MAX_LOADING_TIME_SEC if exec_properties.get(REQUEST_SPEC_KEY): request_spec",
"it is not allowed to register # the signal handler",
"If current thread is not a MainThread, it is not",
"serving_bins.parse_serving_binaries(serving_spec): all_passed &= self._ValidateWithRetry( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if",
"infra validator executor.\"\"\" def __init__(self, context: Optional[base_executor.BaseExecutor.Context] = None): super(Executor,",
"occurred during cleanup.', exc_info=True) def Do(self, input_dict: Dict[str, List[types.Artifact]], output_dict:",
"_DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message keys",
"expected_model_name=serving_spec.model_name) except ValueError: # Copy the model to comply with",
"the tensorflow serving # model path flavor. (Parsed without exception)",
"# If validation has passed without any exception, succeeded. return",
"TensorFlow Serving requires model to be stored in its own",
"of infra blessing artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' #",
"del frame # Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum)) try: old_handler",
"serving_spec) # TODO(jjong): Make logic parallel. all_passed = True for",
"path_utils.warmup_file_path(output_model_path), *[_convert_to_prediction_log(r) for r in warmup_requests]) blessing.set_int_custom_property(_MODEL_FLAG_KEY, 1) def _PrepareModelPath(self,",
"in LOAD_AND_QUERY mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model, examples=examples, request_spec=request_spec)",
") else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): \"\"\"Try",
"_NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec:",
"return temp_model_path return model_path def _ValidateWithRetry( self, model_path: str, serving_binary:",
"# escalate the error. raise except Exception as e: #",
"isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog(",
"tf_serving_flavor.make_model_path( model_base_path=self._get_tmp_dir(), model_name=serving_spec.model_name, version=int(time.time())) io_utils.copy_dir(src=model_path, dst=temp_model_path) self._AddCleanup(io_utils.delete_dir, self._context.get_tmp_path()) return temp_model_path",
"= 'local_docker' _KUBERNETES = 'kubernetes' # Artifact property keys _BLESSED_KEY",
"examples=examples, request_spec=request_spec) else: logging.info('InfraValidator will be run in LOAD_ONLY mode.')",
"'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform ==",
"executor is running on Kubernetes, SIGTERM is a standard way",
"else: # If validation has passed without any exception, succeeded.",
"= None): super(Executor, self).__init__(context) self._cleanups = [] def _AddCleanup(self, function,",
"\"License\"); # you may not use this file except in",
"exec_properties.get(VALIDATION_SPEC_KEY): proto_utils.json_to_proto(exec_properties[VALIDATION_SPEC_KEY], validation_spec) if not validation_spec.num_tries: validation_spec.num_tries = _DEFAULT_NUM_TRIES if",
"serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) if all_passed: _mark_blessed(blessing) if requests and",
"and # escalate the error. raise except Exception as e:",
"cleanup() except: # pylint: disable=broad-except, bare-except logging.warning('Error occurred during cleanup.',",
"be run in LOAD_AND_QUERY mode.') requests = request_builder.build_requests( model_name=serving_spec.model_name, model=model,",
"if all_passed: _mark_blessed(blessing) if requests and request_spec.make_warmup: self._CreateWarmupModel(blessing, model_path, warmup_requests=requests)",
"_handler(signum, frame): del frame # Unused. raise error_types.GracefulShutdown('Got signal {}.'.format(signum))",
"serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests) except error_types.GracefulShutdown: # GracefulShutdown means infra",
"elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return",
"validated result and optinally validated model if warmup requests are",
"+ 1, validation_spec.num_tries) try: self._ValidateOnce( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec, validation_spec=validation_spec, requests=requests)",
"cannot be recognized. If either of MainThread or worker thread",
"`Examples` artifacts to be used for test requests. output_dict: -",
"if old_handler: signal.signal(signal.SIGTERM, old_handler) def _Do( self, model: types.Artifact, examples:",
"signal the graceful shutdown. Python default behavior for receiving SIGTERM",
"external resources that are created by model server runner can",
"self._cleanups = [] def _AddCleanup(self, function, *args, **kwargs): self._cleanups.append(functools.partial(function, *args,",
"can be handled only if the executor is running on"
] |
[
"write(message: str): print(\"org.allnix\", message) def read() -> str: \"\"\"Returns a",
"str): print(\"org.allnix\", message) def read() -> str: \"\"\"Returns a string\"\"\"",
"def write(message: str): print(\"org.allnix\", message) def read() -> str: \"\"\"Returns",
"print(\"org.allnix\", message) def read() -> str: \"\"\"Returns a string\"\"\" return",
"message) def read() -> str: \"\"\"Returns a string\"\"\" return \"org.allnix\""
] |
[
"len_q, d_v], attn: [batch_size, n_heads, len_q, len_k] context = ScaledDotProductAttention()(Q,",
"# 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim * self.heads,",
"64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded",
"self).__init__() # Temporal embedding One hot self.time_num = time_num #",
") self.dropout = nn.Dropout(dropout) def forward(self, x, t): # x:",
"[B, N, T, h, d_k] --> [B, h, T, N,",
"output_T_dim = 12 # Output Expected length heads = 4",
",代表着是spatial attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1, 3)",
"[batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] K:",
"size needs to be divisible by heads\" # 用Linear来做投影矩阵 #",
"* heads == embed_size ), \"Embedding size needs to be",
"if len(sys.argv) == 2 else '1' device = torch.device(\"cuda:{}\".format(GPU)) if",
"[B, h, T, N, d_k] V = self.W_V(input_V).view(B, N, T,",
"2, 3, 1, 4) # [B, N, T, h, d_k]",
"adj, embed_size, num_layers, heads, time_num, forward_expansion, cheb_K, dropout=0 ) #",
"C + 其他 # input_Transformer = input_Transformer.squeeze(0) # input_Transformer =",
"attention = self.attention(query, query, query) # Add skip connection, run",
"embed_size, num_layers, heads, time_num, forward_expansion, ##? cheb_K, dropout, device=DEVICE ):",
"query: [N, T, C] [B, N, T, C] # Add",
"A, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion,",
"# 融合 STransformer and GCN g = torch.sigmoid(self.fs(U_S)) # (7)",
"= output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) # 等号左边 out shape: [1,",
"= self.I[0: (i + T) % self.time_num, :] onehot =",
"def __init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads",
"N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # Q:",
"+ x)) # 融合 STransformer and GCN g = torch.sigmoid(self.fs(U_S))",
"skip connection,run through normalization and finally dropout x1 = self.norm1(self.STransformer(value,",
"def main(): GPU = sys.argv[-1] if len(sys.argv) == 2 else",
"的版本,跑出PEMSBAY的结果 12 步in 12 步 out 2. 设计 only Temporal",
"numpy as np from scipy.sparse.linalg import eigs from Param import",
"C] --[B, N, T, self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial",
"device self.layers = nn.ModuleList( [ STTransformerBlock( embed_size, heads, adj, time_num,",
"o2 = self.I[0: (i + T) % self.time_num, :] onehot",
"Transformer: Total Model class STTransformer(nn.Module): def __init__( self, adj, in_channels,",
"out = self.dropout(x) # In the Encoder the query, key,",
"T, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) #",
"C = query.shape # D_T = self.one_hot(t, N, T) #",
"self.head_dim).permute(0, 3, 1, 2, 4) # V: [B, h, N,",
"# In the Encoder the query, key, value are all",
"time_num, dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout",
"### ST Transformer: Total Model class STTransformer(nn.Module): def __init__( self,",
"= 12 # Input length, should be the same as",
"temporal embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding",
"C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) # [B, N, T, C]",
"# from folder workMETRLA # MODEL CODE # -*- coding:",
"out 3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步",
"+ query)) forward = self.feed_forward(x) U_S = self.dropout(self.norm2(forward + x))",
"nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.fc_out = nn.Linear(heads * self.head_dim,",
"key, query) + query) # (B, N, T, C) x2",
"[N, C] ---position encoding D_S = D_S.expand(B, T, N, C)",
"N, T] # C:通道数量。 N:传感器数量。 T:时间数量 # x = x.unsqueeze(0)",
"h, N, T, d_k] T,dk 就代表是temporal attention K = self.W_K(input_K).view(B,",
"ST Block T_dim = 12 # Input length, should be",
"2. 设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步",
"线性层改变one hot编码维度 def forward(self, i, N=25, T=12): if i %",
"Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 2. 设计 only",
"# return out shape: [N, output_dim] def print_params(model_name, model): param_count",
"self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T = D_T.expand(B, N, T,",
"input_Q: [batch_size, N, T, C] input_K: [batch_size, N, T, C]",
"forward(self, value, key, query): # value, key, query: [N, T,",
"V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # V:",
"self.fc_out(context) # [batch_size, len_q, d_model] return output ''' T 代表Temporal",
"shape: [1, output_T_dim, N, C] out = out.permute(0, 3, 2,",
"import torch import torch.nn as nn import math # from",
"T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) + x1))",
"the query, key, value are all the same. for layer",
"= self.fc_out(context) # [batch_size, len_q, d_model] return output class STransformer(nn.Module):",
"# attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask :",
"len_q, d_model] return output class STransformer(nn.Module): def __init__(self, embed_size, heads,",
"device, forward_expansion, cheb_K, dropout, ): super(Encoder, self).__init__() self.embed_size = embed_size",
"self.dropout(x) # In the Encoder the query, key, value are",
"3, 1) # input_Transformer shape[N, T, C] [B, N, T,",
"--> [B, N, T, h, d_k] --> [B, h, N,",
"forward_expansion): super(STransformer, self).__init__() # Spatial Embedding self.adj = adj self.D_S",
"C] # output_Transformer = output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) # 等号左边",
"### Construct Network model = STTransformer( A, in_channels, embed_size, time_num,",
"[B, h, N, T, d_k] Q = self.W_Q(input_Q).view(B, N, T,",
"key, query): # value, key, query: [N, T, C] [B,",
"= self.attention(query, query, query) # (B, N, T, C) #",
"self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size) #",
"embed_size, heads, time_num, dropout, forward_expansion): super(TTransformer, self).__init__() # Temporal embedding",
"N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # V:",
"skip connection, run through normalization and finally dropout x =",
"[B, 1, N, output_T_dim] # out = out.squeeze(1) out =",
"C] B, N, T, C = query.shape D_S = self.embed_liner(self.D_S)",
"self.dropout(self.norm2(forward + x)) return out ### STBlock class STTransformerBlock(nn.Module): def",
"len_k] context = ScaledDotProductAttention()(Q, K, V) # [B, h, T,",
"SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size",
"self.embed_liner(self.D_S) # [N, C] ---position encoding D_S = D_S.expand(B, T,",
"embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads",
"self.dropout = nn.Dropout(dropout) def forward(self, x, t): # x: [N,",
"d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1,",
"STTransformer(nn.Module): def __init__( self, adj, in_channels, embed_size, time_num, num_layers, T_dim,",
"ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self, Q, K, V):",
"= ScaledDotProductAttention()(Q, K, V) # [B, h, N, T, d_k]",
"Q: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]",
"+ query) # (B, N, T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1,",
"--> [B, N, T, h, d_k] --> [B, h, T,",
"of Heads in MultiHeadAttention cheb_K = 2 # Order for",
"the same as prepareData.py output_T_dim = 12 # Output Expected",
"# Number of Heads in MultiHeadAttention cheb_K = 2 #",
"import math # from GCN_models import GCN # from One_hot_encoder",
"C] [B, N, T, C] enc_src = self.encoder(src, t) return",
"\"\"\" Created on Mon Sep 28 10:28:06 2020 @author: wb",
"normalization and finally dropout x1 = self.norm1(self.STransformer(value, key, query) +",
"adj self.D_S = adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention =",
"+ x1)) return x2 ### Encoder class Encoder(nn.Module): # 堆叠多层",
"forward_expansion # feed forward 的 embeded size 8,16,32....1024 # 第一次卷积扩充通道数",
"self.head_dim).transpose(1, 3) # V: [B, h, T, N, d_k] #",
"给 扩维,成 embeded size self.Transformer = Transformer( adj, embed_size, num_layers,",
"= 12 # Output Expected length heads = 4 #",
"with value where mask is True. attn = nn.Softmax(dim=-1)(scores) context",
"# (B, N, T, C) # Add skip connection, run",
"#[T, N, C]相当于在第一维复制了T份 # D_S = D_S.permute(1, 0, 2) #[N,",
"input_V: [batch_size, N, T, C] attn_mask: [batch_size, seq_len, seq_len] '''",
"device=device) print_params('STTransformer', model) if __name__ == '__main__': main() ''' 布置作业:",
"= 0 A = pd.read_csv(ADJPATH).values A = torch.Tensor(A) ### Construct",
"''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def __init__(self,",
"T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T = D_T.expand(B, N, T, C)",
"o1 = self.I[i % self.time_num:, :] o2 = self.I[0: (i",
"cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for _ in range(num_layers) ] )",
"self.fc_out = nn.Linear(heads * self.head_dim, embed_size) def forward(self, input_Q, input_K,",
"x, t): # x: [N, T, C] [B, N, T,",
"TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward =",
"[N, T, C] [B, N, T, C] # Add skip",
"def forward(self, value, key, query, t): B, N, T, C",
"0) else: onehot = self.I[i % self.time_num: i % self.time_num",
"cheb_K, dropout, device=DEVICE ): super(Transformer, self).__init__() self.encoder = Encoder( embed_size,",
"param_count += param.numel() print(f'{model_name}, {param_count} trainable parameters in total.') return",
"N(Spatial) or T(Temporal), d_k] V: [batch_size, n_heads, T(Spatial) or N(Temporal),",
"divisible by heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size,",
"C) #[T, N, C]相当于在第一维复制了T份 # D_S = D_S.permute(1, 0, 2)",
"= query.shape # D_T = self.one_hot(t, N, T) # temporal",
"import summary DEVICE = 'cuda:1' class One_hot_encoder(nn.Module): def __init__(self, embed_size,",
"T, C = query.shape # D_S = self.embed_liner(self.D_S) # [N,",
"= self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) + x1)) return x2 ###",
"T, C] --> [B, N, T, h * d_k] -->",
"x1 = self.norm1(self.STransformer(value, key, query) + query) # (B, N,",
"1) # attn_mask : [batch_size, n_heads, seq_len, seq_len] # context:",
"context = torch.matmul(attn, V) # [batch_size, n_heads, T(Spatial) or N(Temporal),",
"12 步in 12 步 out 3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果",
"T) % self.time_num, :] onehot = torch.cat((o1, o2), 0) else:",
"原论文采用concatenated query = query + D_T attention = self.attention(query, query,",
"N, T, h * d_k] --> [B, N, T, h,",
"[B, N, T, C] enc_src = self.encoder(src, t) return enc_src",
"= self.relu(self.conv2(output_Transformer)) # 等号左边 out shape: [1, output_T_dim, N, C]",
"''' class SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size",
"##? cheb_K, dropout, device=DEVICE ): super(Transformer, self).__init__() self.encoder = Encoder(",
"attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1,",
"output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN), device=device)",
"attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) #",
"time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度 def",
"8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size, 1) # Channel",
"* embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) # 调用GCN",
"__init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num = time_num self.I =",
"C, N, output_T_dim] out = self.conv3(out) # 等号左边 out shape:",
"nn.Dropout(dropout) def forward(self, x, t): # x: [N, T, C]",
"query) # (B, N, T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1,",
"\"Embedding size needs to be divisible by heads\" # 用Linear来做投影矩阵",
"= 2 # Channels of input embed_size = 32 #",
"/ np.sqrt(d_k) # scores : [batch_size, n_heads, T(Spatial) or N(Temporal),",
"= query + D_S attention = self.attention(query, query, query) #",
"= D_T.expand(B, N, T, C) # temporal embedding加到query。 原论文采用concatenated query",
"h, d_k] --> [B, h, T, N, d_k] Q =",
"parameters in total.') return import sys import pandas as pd",
"T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] V: [batch_size, n_heads,",
"forward_expansion, cheb_K, dropout ) self.device = device def forward(self, src,",
"= Q.shape scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) #",
"embed_size ), \"Embedding size needs to be divisible by heads\"",
"--> [B, N, T, h * d_k] --> [B, N,",
"1) # input_Transformer shape[N, T, C] [B, N, T, C]",
"query, query) # Add skip connection, run through normalization and",
"self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) #",
"Add skip connection, run through normalization and finally dropout x",
"STransformer(embed_size, heads, adj, cheb_K, dropout, forward_expansion) self.TTransformer = TTransformer(embed_size, heads,",
"out # (B, N, T, C) class TTransformer(nn.Module): def __init__(self,",
"K: [B, h, N, T, d_k] V = self.W_V(input_V).view(B, N,",
"1, 2, 4) # Q: [B, h, N, T, d_k]",
"heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer',",
"nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V) # [batch_size, n_heads, T(Spatial) or",
"部分 # N, T, C = query.shape # D_S =",
"model = STTransformer( A, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim,",
"time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size, heads,",
"0) input_Transformer = input_Transformer.permute(0, 2, 3, 1) # input_Transformer shape[N,",
"self.onehot_Linear = nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度 def forward(self, i,",
"= self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) U_S = self.dropout(self.norm2(forward",
"TTransformer(embed_size, heads, time_num, dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2 =",
"input_Transformer = input_Transformer.permute(0, 2, 3, 1) # input_Transformer shape[N, T,",
"T, :] # onehot = onehot.repeat(N, 1, 1) onehot =",
"embed_size), ) # 调用GCN self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout",
"2) #[N, T, C] B, N, T, C = query.shape",
"self.attention = TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size)",
"[batch_size, N, T, C] input_K: [batch_size, N, T, C] input_V:",
"adj, cheb_K, dropout, forward_expansion): super(STransformer, self).__init__() # Spatial Embedding self.adj",
"= self.I[i % self.time_num:, :] o2 = self.I[0: (i +",
"3, 1, 2, 4) # V: [B, h, N, T,",
"## scr: [N, T, C] [B, N, T, C] enc_src",
"out.permute(0, 3, 2, 1) # 等号左边 out shape: [B, C,",
"[N, output_dim] def print_params(model_name, model): param_count = 0 for name,",
"model.named_parameters(): if param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count} trainable parameters",
"query + D_T attention = self.attention(query, query, query) # Add",
"= nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size, embed_size)",
"connection,run through normalization and finally dropout x1 = self.norm1(self.STransformer(value, key,",
"wb \"\"\" import torch import torch.nn as nn import math",
"x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) # conv",
"t): B, N, T, C = query.shape # D_T =",
"[N, T, C] [B, N, T, C] out = self.dropout(x)",
"''' input_Q: [batch_size, N, T, C] input_K: [batch_size, N, T,",
"N, T, C] # Add skip connection,run through normalization and",
"步 out 2. 设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in",
"forward(self, value, key, query, t): # value, key, query: [N,",
"name, param in model.named_parameters(): if param.requires_grad: param_count += param.numel() print(f'{model_name},",
"input embed_size = 32 # Dimension of hidden embedding features",
"dropout, forward_expansion) self.TTransformer = TTransformer(embed_size, heads, time_num, dropout, forward_expansion) self.norm1",
"t) return out ### Transformer class Transformer(nn.Module): def __init__( self,",
"T, C] # Spatial Embedding 部分 # N, T, C",
"d_k] context = context.permute(0, 3, 2, 1, 4) # [B,",
"One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num = time_num",
"1, 1) # attn_mask : [batch_size, n_heads, seq_len, seq_len] #",
"] ) self.dropout = nn.Dropout(dropout) def forward(self, x, t): #",
"# [B, h, T, N, d_k] context = context.permute(0, 3,",
"adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for _ in range(num_layers)",
"= sys.argv[-1] if len(sys.argv) == 2 else '1' device =",
"seq_len, seq_len] 可能没有 ''' B, n_heads, len1, len2, d_k =",
"self.dropout = nn.Dropout(dropout) def forward(self, value, key, query, t): B,",
"nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads) self.norm1",
"output = self.fc_out(context) # [batch_size, len_q, d_model] return output '''",
"T(Temporal), d_k] V: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or",
"forward(self, x, t): # x: [N, T, C] [B, N,",
"= query.shape D_S = self.embed_liner(self.D_S) # [N, C] ---position encoding",
"1) # 等号左边 out shape: [B, C, N, output_T_dim] out",
"main(): GPU = sys.argv[-1] if len(sys.argv) == 2 else '1'",
"* d_v) # context: [batch_size, len_q, n_heads * d_v] output",
"= embed_size // heads assert ( self.head_dim * heads ==",
"param.numel() print(f'{model_name}, {param_count} trainable parameters in total.') return import sys",
"or T(Temporal), N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) # Fills",
"query)) forward = self.feed_forward(x) out = self.dropout(self.norm2(forward + x)) return",
"super(Encoder, self).__init__() self.embed_size = embed_size self.device = device self.layers =",
"x = self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) out =",
"scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores :",
"# print('out: ',out.shape) return out # [B, N, output_dim] #",
"heads, adj, cheb_K, dropout, forward_expansion): super(STransformer, self).__init__() # Spatial Embedding",
"= TTransformer(embed_size, heads, time_num, dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2",
"# attn_mask : [batch_size, n_heads, seq_len, seq_len] seq_len = N",
"num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE,",
"N, T, C] out = self.dropout(x) # In the Encoder",
"''' 布置作业: 1. 设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in",
"2, 0) input_Transformer = input_Transformer.permute(0, 2, 3, 1) # input_Transformer",
"heads, adj, time_num, device, forward_expansion, cheb_K, dropout, ): super(Encoder, self).__init__()",
"'1' device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\") in_channels =",
"out.permute(0, 1, 3, 2) # print('out: ',out.shape) return out #",
"T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]] return context '''",
"onehot.expand(N, T, self.time_num) onehot = self.onehot_Linear(onehot) return onehot ''' Attention",
"self tensor with value where mask is True. attn =",
"class SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size =",
"len_q, len_k] context = ScaledDotProductAttention()(Q, K, V) # [B, h,",
"or N(Temporal), N(Spatial) or T(Temporal), N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask,",
"T) # temporal embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) #",
"# Output Expected length heads = 4 # Number of",
"部分 query = query + D_S attention = self.attention(query, query,",
"self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def",
"def __init__( self, adj, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim,",
"N, T, C) # temporal embedding加到query。 原论文采用concatenated query = query",
"Temporal embedding One hot self.time_num = time_num # self.one_hot =",
"Transformer 部分 query = query + D_S attention = self.attention(query,",
"heads = 4 # Number of Heads in MultiHeadAttention cheb_K",
"# 等号左边 out shape: [1, output_T_dim, N, C] out =",
"heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential(",
"time_num, forward_expansion, cheb_K, dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in",
"N, d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1, 3)",
"same. for layer in self.layers: out = layer(out, out, out,",
"= ScaledDotProductAttention()(Q, K, V) # [B, h, T, N, d_k]",
"+ query)) forward = self.feed_forward(x) out = self.dropout(self.norm2(forward + x))",
"device def forward(self, src, t): ## scr: [N, T, C]",
"class One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num =",
"Created on Mon Sep 28 10:28:06 2020 @author: wb \"\"\"",
"input_K, input_V): ''' input_Q: [batch_size, N, T, C] input_K: [batch_size,",
"forward_expansion, dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion = forward_expansion # feed",
"embeded size self.Transformer = Transformer( adj, embed_size, num_layers, heads, time_num,",
"步in 12 步 out 3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12",
"nn.Linear(forward_expansion * embed_size, embed_size), ) self.dropout = nn.Dropout(dropout) def forward(self,",
"normalization and finally dropout x = self.dropout(self.norm1(attention + query)) forward",
"len2, d_k = Q.shape scores = torch.matmul(Q, K.transpose(-1, -2)) /",
"T, h, d_k] --> [B, h, N, T, d_k] Q",
":] o2 = self.I[0: (i + T) % self.time_num, :]",
"context ''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def",
"N, T, C] --[B, N, T, self.heads, self.head_dim] -> [B,h,T,N,dk]",
"model): param_count = 0 for name, param in model.named_parameters(): if",
"4) # Q: [B, h, N, T, d_k] T,dk 就代表是temporal",
": [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), N(Spatial)",
"self.W_Q = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.fc_out = nn.Linear(heads",
"out = self.relu(self.conv2(output_Transformer)) # 等号左边 out shape: [1, output_T_dim, N,",
"self).__init__() self.embed_size = embed_size self.heads = heads self.head_dim = embed_size",
"C] # Spatial Embedding 部分 # N, T, C =",
"12 步in 12 步 out 2. 设计 only Temporal Transformer",
"self.feed_forward(x) U_S = self.dropout(self.norm2(forward + x)) # 融合 STransformer and",
"x): # platform: (CHANNEL, TIMESTEP_IN, N_NODE) # input x shape[",
"import GCN # from One_hot_encoder import One_hot_encoder import torch.nn.functional as",
"DEVICE = 'cuda:1' class One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288): super(One_hot_encoder,",
"# [N, C] # D_S = D_S.expand(T, N, C) #[T,",
"in MultiHeadAttention cheb_K = 2 # Order for Chebyshev Polynomials",
"seq_len, seq_len] # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size,",
"out = self.dropout(self.norm2(forward + x)) return out ### STBlock class",
"# [batch_size, len_q, d_model] return output class STransformer(nn.Module): def __init__(self,",
"T, C] [B, N, T, C] # Add skip connection,run",
"np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) # conv 要求第二维度是C, 也就是必须得B C +",
"run through normalization and finally dropout x = self.dropout(self.norm1(attention +",
"N, T, C] # Spatial Embedding 部分 # N, T,",
"query + D_S attention = self.attention(query, query, query) # (B,",
"def __init__( self, adj, embed_size, num_layers, heads, time_num, forward_expansion, ##?",
"feed forward 的 embeded size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 =",
"sys.argv[-1] if len(sys.argv) == 2 else '1' device = torch.device(\"cuda:{}\".format(GPU))",
"attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size,",
"the Encoder the query, key, value are all the same.",
"forward(self, Q, K, V): ''' Q: [batch_size, n_heads, T(Spatial) or",
"d_k] V: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal),",
"shape[ C, N, T] # C:通道数量。 N:传感器数量。 T:时间数量 # x",
"d_v], attn: [batch_size, n_heads, len_q, len_k] context = ScaledDotProductAttention()(Q, K,",
"or T(Temporal), d_k]] return context ''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制",
"C = input_Q.shape # [B, N, T, C] --> [B,",
"T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), N(Spatial) or T(Temporal)] #",
"self.Transformer(input_Transformer, self.forward_expansion) # [B, N, T, C] output_Transformer = output_Transformer.permute(0,",
"STransformer and GCN g = torch.sigmoid(self.fs(U_S)) # (7) out =",
"# [B, N, T, C] output_Transformer = output_Transformer.permute(0, 2, 1,",
"= TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward",
"或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T =",
"embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model,",
"''' Q: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal),",
"from folder workMETRLA # MODEL CODE # -*- coding: utf-8",
"input_Transformer.permute(0, 2, 3, 1) # input_Transformer shape[N, T, C] [B,",
"of ST Block T_dim = 12 # Input length, should",
"# output_Transformer = output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) # 等号左边 out",
"% self.time_num: i % self.time_num + T, :] # onehot",
"8 ,all embeded size = 512 ''' class ScaledDotProductAttention(nn.Module): def",
"self.time_num = time_num self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear =",
"= nn.Dropout(dropout) def forward(self, value, key, query, t): B, N,",
"shape[B, T, N, C] # output_Transformer = output_Transformer.unsqueeze(0) out =",
"torchsummary import summary DEVICE = 'cuda:1' class One_hot_encoder(nn.Module): def __init__(self,",
"# input_Transformer shape[N, T, C] [B, N, T, C] output_Transformer",
"super(Transformer, self).__init__() self.encoder = Encoder( embed_size, num_layers, heads, adj, time_num,",
"= onehot.repeat(N, 1, 1) onehot = onehot.expand(N, T, self.time_num) onehot",
"or N(Temporal), N(Spatial) or T(Temporal), d_k] attn_mask: [batch_size, n_heads, seq_len,",
"x1, t) + x1)) return x2 ### Encoder class Encoder(nn.Module):",
"Add skip connection,run through normalization and finally dropout x1 =",
"1, 3) # [B, N, T, C] # Spatial Transformer",
"self).__init__() self.encoder = Encoder( embed_size, num_layers, heads, adj, time_num, device,",
"= self.feed_forward(x) U_S = self.dropout(self.norm2(forward + x)) # 融合 STransformer",
"torch.sigmoid(self.fs(U_S)) # (7) out = g * U_S + (1",
"in self.layers: out = layer(out, out, out, t) return out",
"\"\"\" import torch import torch.nn as nn import math #",
"summary(model, (2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model) if __name__ ==",
"nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size, embed_size) def",
"out # [B, N, output_dim] # return out shape: [N,",
"context = context.permute(0, 3, 2, 1, 4) # [B, N,",
"self.forward_expansion = forward_expansion # feed forward 的 embeded size 8,16,32....1024",
"U_S = self.dropout(self.norm2(forward + x)) # 融合 STransformer and GCN",
"C] # D_S = D_S.expand(T, N, C) #[T, N, C]相当于在第一维复制了T份",
"or N(Temporal), N(Spatial) or T(Temporal), d_k]] return context ''' S",
"torch.matmul(attn, V) # [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or",
"[batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]] return",
"as nn import math # from GCN_models import GCN #",
"len(sys.argv) == 2 else '1' device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available()",
"# x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) # conv 要求第二维度是C,",
"nn.Linear(embed_size, embed_size) def forward(self, value, key, query): # value, key,",
"= heads self.head_dim = embed_size // heads assert ( self.head_dim",
"= D_S.permute(0, 2, 1, 3) # [B, N, T, C]",
"K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # K:",
"time_num = 288 num_layers = 2 # Number of ST",
"[B, N, T, C] # Spatial Embedding 部分 # N,",
"dropout = 0 A = pd.read_csv(ADJPATH).values A = torch.Tensor(A) ###",
"2, 3, 1) # input_Transformer shape[N, T, C] [B, N,",
"workMETRLA # MODEL CODE # -*- coding: utf-8 -*- \"\"\"",
"np.sqrt(d_k) # scores : [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial)",
"heads self.head_dim = embed_size // heads assert ( self.head_dim *",
"* embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) self.dropout =",
"是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size 32 or 64",
"# D_S = D_S.expand(T, N, C) #[T, N, C]相当于在第一维复制了T份 #",
"+ T, :] # onehot = onehot.repeat(N, 1, 1) onehot",
"context = ScaledDotProductAttention()(Q, K, V) # [B, h, N, T,",
") # 调用GCN self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout =",
"= 512 ''' class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__() def",
"N, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) #",
"# conv 要求第二维度是C, 也就是必须得B C + 其他 # input_Transformer =",
"Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2,",
"# 等号左边 out shape: [B, C, N, output_T_dim] out =",
"12 步in 12 步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N",
"= self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T = D_T.expand(B, N,",
"Network model = STTransformer( A, in_channels, embed_size, time_num, num_layers, T_dim,",
"temporal embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding",
"D_S = self.embed_liner(self.D_S) # [N, C] ---position encoding D_S =",
"T, N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0, 2, 1,",
"self.encoder = Encoder( embed_size, num_layers, heads, adj, time_num, device, forward_expansion,",
"nn.Conv2d(in_channels, embed_size, 1) # Channel = 1 给 扩维,成 embeded",
"bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.fc_out =",
"input_Transformer = input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1, 2, 0) input_Transformer",
"C] out = out.permute(0, 3, 2, 1) # 等号左边 out",
"= nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size)",
"d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1,",
"attn_mask : [batch_size, n_heads, seq_len, seq_len] seq_len = N #",
"4) # [B, N, T, h, d_k] context = context.reshape(B,",
"== embed_size ), \"Embedding size needs to be divisible by",
"3) # output_Transformer shape[B, T, N, C] # output_Transformer =",
"h, T, N, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1,",
"requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度 def forward(self,",
"are all the same. for layer in self.layers: out =",
"time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for _ in range(num_layers) ]",
"32 # Dimension of hidden embedding features time_num = 288",
"# K: [B, h, N, T, d_k] V = self.W_V(input_V).view(B,",
"self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) + x1)) return x2 ### Encoder",
"class TTransformer(nn.Module): def __init__(self, embed_size, heads, time_num, dropout, forward_expansion): super(TTransformer,",
"x = self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) U_S =",
"= 32 # Dimension of hidden embedding features time_num =",
"Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 4. 前面的版本完成后,全部升级为,C",
"return out # [B, N, output_dim] # return out shape:",
"One hot self.time_num = time_num # self.one_hot = One_hot_encoder(embed_size, time_num)",
"4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3",
"Output Expected length heads = 4 # Number of Heads",
"bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_Q =",
"output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) # [B, N, T, C] output_Transformer",
"super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads self.head_dim =",
"np from scipy.sparse.linalg import eigs from Param import * from",
"[B, N, T, C] # Spatial Transformer 部分 query =",
"of Feed Forward Network: embed_size --> embed_size * forward_expansion -->",
"(8) return out # (B, N, T, C) class TTransformer(nn.Module):",
"K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2,",
"V) # [B, h, N, T, d_k] context = context.permute(0,",
"out = self.conv3(out) # 等号左边 out shape: [B, 1, N,",
"self.time_num + T > self.time_num: o1 = self.I[i % self.time_num:,",
"output_Transformer = output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) # 等号左边 out shape:",
"1, 4) # [B, N, T, h, d_k] context =",
"N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) # Fills elements of",
"T, C] # context = context.transpose(1, 2).reshape(batch_size, -1, n_heads *",
"query = query + D_T attention = self.attention(query, query, query)",
"embedding One hot self.time_num = time_num # self.one_hot = One_hot_encoder(embed_size,",
"TIMESTEP_IN), device=device) print_params('STTransformer', model) if __name__ == '__main__': main() '''",
"scores : [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal),",
"0 for name, param in model.named_parameters(): if param.requires_grad: param_count +=",
"# Dimension of Feed Forward Network: embed_size --> embed_size *",
"__init__(self, embed_size, heads, adj, cheb_K, dropout, forward_expansion): super(STransformer, self).__init__() #",
"# 等号左边 out shape: [B, 1, N, output_T_dim] # out",
"N, T) # temporal embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE))",
"self.conv1 = nn.Conv2d(in_channels, embed_size, 1) # Channel = 1 给",
"heads): super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads self.head_dim",
"= nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads)",
"T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in 12 步",
"dropout, forward_expansion): super(TTransformer, self).__init__() # Temporal embedding One hot self.time_num",
"1) # 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels, 1) self.relu =",
"cheb_K, dropout, forward_expansion) self.TTransformer = TTransformer(embed_size, heads, time_num, dropout, forward_expansion)",
"finally dropout x = self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x)",
"V): ''' Q: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or",
"size = 512 ''' class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__()",
"Polynomials (Eq 2) forward_expansion = 32 # Dimension of Feed",
"forward_expansion, cheb_K, dropout, ): super(Encoder, self).__init__() self.embed_size = embed_size self.device",
"d_k] --> [B, h, T, N, d_k] Q = self.W_Q(input_Q).view(B,",
"self).__init__() # Spatial Embedding self.adj = adj self.D_S = adj.to(DEVICE)",
"return out # (B, N, T, C) class TTransformer(nn.Module): def",
"= nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs = nn.Linear(embed_size,",
"= self.fc_out(context) # [batch_size, len_q, d_model] return output ''' T",
"# N, T, C = query.shape # D_S = self.embed_liner(self.D_S)",
"pd.read_csv(ADJPATH).values A = torch.Tensor(A) ### Construct Network model = STTransformer(",
"12 步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1",
"input_Transformer shape[N, T, C] [B, N, T, C] output_Transformer =",
"of self tensor with value where mask is True. attn",
"def forward(self, value, key, query): # value, key, query: [N,",
"C] [B, N, T, C] # Spatial Embedding 部分 #",
"### Transformer class Transformer(nn.Module): def __init__( self, adj, embed_size, num_layers,",
"dropout, device=DEVICE ): super(Transformer, self).__init__() self.encoder = Encoder( embed_size, num_layers,",
"as prepareData.py output_T_dim = 12 # Output Expected length heads",
"S 代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def __init__(self, embed_size,",
"[B, N, T, C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) # [B,",
"context = context.permute(0, 2, 3, 1, 4) # [B, N,",
"N, T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) +",
"= time_num self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num,",
"= nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def forward(self, value, key, query,",
"embedding加到query。 原论文采用concatenated query = query + D_T attention = self.attention(query,",
"embed_size, embed_size), ) self.dropout = nn.Dropout(dropout) def forward(self, value, key,",
"pd def main(): GPU = sys.argv[-1] if len(sys.argv) == 2",
"T, self.time_num) onehot = self.onehot_Linear(onehot) return onehot ''' Attention 基础代码",
"__init__( self, adj, embed_size, num_layers, heads, time_num, forward_expansion, ##? cheb_K,",
"or 12in 12 out self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1) #",
"g = torch.sigmoid(self.fs(U_S)) # (7) out = g * U_S",
"h, N, T, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1,",
"调用GCN self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs",
"3, 2) # print('out: ',out.shape) return out # [B, N,",
"T(Temporal), d_k] attn_mask: [batch_size, n_heads, seq_len, seq_len] 可能没有 ''' B,",
"x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) + x1)) return x2",
"前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。",
"conv 要求第二维度是C, 也就是必须得B C + 其他 # input_Transformer = input_Transformer.squeeze(0)",
": [batch_size, n_heads, seq_len, seq_len] seq_len = N # context:",
"(i + T) % self.time_num, :] onehot = torch.cat((o1, o2),",
"1) # Channel = 1 给 扩维,成 embeded size self.Transformer",
"N, T, h, d_k] context = context.reshape(B, N, T, self.heads",
"temporal embedding加到query。 原论文采用concatenated query = query + D_T attention =",
"T(Temporal), N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) # Fills elements",
"embed_size, heads, adj, time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer",
"embed_size) # temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads) self.norm1 =",
"= g * U_S + (1 - g) # (8)",
"''' class TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size",
"self.fg = nn.Linear(embed_size, embed_size) def forward(self, value, key, query): #",
"from One_hot_encoder import One_hot_encoder import torch.nn.functional as F import numpy",
"T, N, C) # [B, T, N, C] 相当于在第2维复制了T份, 第一维复制B份",
"3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out",
"* U_S + (1 - g) # (8) return out",
"K, V) # [B, h, N, T, d_k] context =",
"forward_expansion=forward_expansion ) for _ in range(num_layers) ] ) self.dropout =",
"= self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4)",
"4) # K: [B, h, N, T, d_k] V =",
"n_heads, len1, len2, d_k = Q.shape scores = torch.matmul(Q, K.transpose(-1,",
"T,dk 就代表是temporal attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0,",
"adj, embed_size, num_layers, heads, time_num, forward_expansion, ##? cheb_K, dropout, device=DEVICE",
"def __init__(self, embed_size, heads, adj, time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock,",
"print_params(model_name, model): param_count = 0 for name, param in model.named_parameters():",
"scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value",
"对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size) self.fg =",
"device=DEVICE ): super(Transformer, self).__init__() self.encoder = Encoder( embed_size, num_layers, heads,",
"T, C = input_Q.shape # [B, N, T, C] -->",
"on Mon Sep 28 10:28:06 2020 @author: wb \"\"\" import",
"adj, time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size,",
"embed_size = 32 # Dimension of hidden embedding features time_num",
"x)) # 融合 STransformer and GCN g = torch.sigmoid(self.fs(U_S)) #",
"1, 2, 4) # V: [B, h, N, T, d_k]",
"from Param import * from torchsummary import summary DEVICE =",
"context = context.transpose(1, 2).reshape(batch_size, -1, n_heads * d_v) # context:",
"C] input_V: [batch_size, N, T, C] attn_mask: [batch_size, seq_len, seq_len]",
"out shape: [B, C, N, output_T_dim] out = self.conv3(out) #",
"(B, N, T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t)",
"= N # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size,",
"heads, time_num, dropout, forward_expansion): super(TTransformer, self).__init__() # Temporal embedding One",
"[B, h, T, N, d_k] Q = self.W_Q(input_Q).view(B, N, T,",
"代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__()",
"layer(out, out, out, t) return out ### Transformer class Transformer(nn.Module):",
"embed_size) def forward(self, value, key, query): # value, key, query:",
"out = g * U_S + (1 - g) #",
"for _ in range(num_layers) ] ) self.dropout = nn.Dropout(dropout) def",
"key, value are all the same. for layer in self.layers:",
"out 2. 设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in 12",
"Transformer(nn.Module): def __init__( self, adj, embed_size, num_layers, heads, time_num, forward_expansion,",
"d_k]] return context ''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class",
"[B, N, T, h, d_k] context = context.reshape(B, N, T,",
"torch.nn.functional as F import numpy as np from scipy.sparse.linalg import",
"out = out.permute(0, 3, 2, 1) # 等号左边 out shape:",
"import * from torchsummary import summary DEVICE = 'cuda:1' class",
"2, 1) # 等号左边 out shape: [B, C, N, output_T_dim]",
"output_T_dim] # out = out.squeeze(1) out = out.permute(0, 1, 3,",
"TTransformer(nn.Module): def __init__(self, embed_size, heads, time_num, dropout, forward_expansion): super(TTransformer, self).__init__()",
"= torch.cat((o1, o2), 0) else: onehot = self.I[i % self.time_num:",
"h, d_k] --> [B, h, N, T, d_k] Q =",
"return context ''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module):",
"N, T, self.heads, self.head_dim).transpose(1, 3) # V: [B, h, T,",
"= nn.Dropout(dropout) def forward(self, x, t): # x: [N, T,",
"self.head_dim * self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim * self.heads,",
"self).__init__() def forward(self, Q, K, V): ''' Q: [batch_size, n_heads,",
"= nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(),",
"self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # K: [B, h,",
"output = self.fc_out(context) # [batch_size, len_q, d_model] return output class",
"i % self.time_num + T, :] # onehot = onehot.repeat(N,",
"= device self.layers = nn.ModuleList( [ STTransformerBlock( embed_size, heads, adj,",
"self.I[i % self.time_num: i % self.time_num + T, :] #",
"out shape: [B, 1, N, output_T_dim] # out = out.squeeze(1)",
"T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN),",
"needs to be divisible by heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵???",
"T, N, d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1,",
"self.adj = adj self.D_S = adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size)",
"但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_K =",
"例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1)",
"out, out, t) return out ### Transformer class Transformer(nn.Module): def",
"d_k] K: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal),",
"Embedding self.adj = adj self.D_S = adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0],",
"= out.permute(0, 3, 2, 1) # 等号左边 out shape: [B,",
"N_NODE) # input x shape[ C, N, T] # C:通道数量。",
"x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) # conv 要求第二维度是C, 也就是必须得B",
"Feed Forward Network: embed_size --> embed_size * forward_expansion --> embed_size",
"N(Temporal), N(Spatial) or T(Temporal), d_k]] return context ''' S 代表spatial",
"= adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size, heads)",
"MODEL CODE # -*- coding: utf-8 -*- \"\"\" Created on",
"key, query, t): B, N, T, C = query.shape #",
"N(Temporal), N(Spatial) or T(Temporal), d_k] K: [batch_size, n_heads, T(Spatial) or",
",现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in 12 步 out PEMSBAY",
"seq_len] seq_len = N # context: [batch_size, n_heads, len_q, d_v],",
"Number of Heads in MultiHeadAttention cheb_K = 2 # Order",
"C) # temporal embedding加到query。 原论文采用concatenated query = query + D_T",
"self.head_dim * self.heads, bias=False) self.fc_out = nn.Linear(heads * self.head_dim, embed_size)",
"[batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k] context",
"= nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size) # 线性层改变one",
"1, 2, 4) # K: [B, h, N, T, d_k]",
"temporal embedding选用nn.Embedding D_T = D_T.expand(B, N, T, C) # temporal",
"n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] K: [batch_size,",
"Total Model class STTransformer(nn.Module): def __init__( self, adj, in_channels, embed_size,",
"T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def __init__(self, embed_size,",
"return x2 ### Encoder class Encoder(nn.Module): # 堆叠多层 ST-Transformer Block",
"class STransformer(nn.Module): def __init__(self, embed_size, heads, adj, cheb_K, dropout, forward_expansion):",
"D_S = D_S.expand(B, T, N, C) # [B, T, N,",
"[batch_size, n_heads, len_q, len_k] context = ScaledDotProductAttention()(Q, K, V) #",
"self.device = device self.layers = nn.ModuleList( [ STTransformerBlock( embed_size, heads,",
"self.head_dim, embed_size) def forward(self, input_Q, input_K, input_V): ''' input_Q: [batch_size,",
"else torch.device(\"cpu\") in_channels = 2 # Channels of input embed_size",
"self.norm2 = nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def forward(self, value, key,",
"等号左边 out shape: [B, 1, N, output_T_dim] # out =",
"self.time_num = time_num # self.one_hot = One_hot_encoder(embed_size, time_num) # temporal",
"N, output_T_dim] # out = out.squeeze(1) out = out.permute(0, 1,",
"C] output_Transformer = output_Transformer.permute(0, 2, 1, 3) # output_Transformer shape[B,",
"forward(self, x): # platform: (CHANNEL, TIMESTEP_IN, N_NODE) # input x",
"T, C] [B, N, T, C] # Spatial Embedding 部分",
"10:28:06 2020 @author: wb \"\"\" import torch import torch.nn as",
"+ D_T attention = self.attention(query, query, query) # Add skip",
"h, N, T, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads,",
"T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # Q: [B,",
"Encoder(nn.Module): # 堆叠多层 ST-Transformer Block def __init__( self, embed_size, num_layers,",
"class STTransformerBlock(nn.Module): def __init__(self, embed_size, heads, adj, time_num, cheb_K, dropout,",
"的版本,跑出PEMSBAY的结果 12 步in 12 步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B",
") self.device = device def forward(self, src, t): ## scr:",
"CODE # -*- coding: utf-8 -*- \"\"\" Created on Mon",
"self.time_num) onehot = self.onehot_Linear(onehot) return onehot ''' Attention 基础代码 ScaledDotProductAttention",
"len_q, n_heads * d_v] output = self.fc_out(context) # [batch_size, len_q,",
"x = x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x)",
"# Channels of input embed_size = 32 # Dimension of",
"Transformer( adj, embed_size, num_layers, heads, time_num, forward_expansion, cheb_K, dropout=0 )",
"= 'cuda:1' class One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__()",
"__init__( self, adj, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads,",
"T=12): if i % self.time_num + T > self.time_num: o1",
"hot self.time_num = time_num # self.one_hot = One_hot_encoder(embed_size, time_num) #",
"T] # C:通道数量。 N:传感器数量。 T:时间数量 # x = x.unsqueeze(0) #",
"self.attention = SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size)",
"T, C] # Add skip connection,run through normalization and finally",
"n_heads * d_v) # context: [batch_size, len_q, n_heads * d_v]",
"self, embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout,",
"# Spatial Embedding self.adj = adj self.D_S = adj.to(DEVICE) self.embed_liner",
"in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout=0",
"* self.heads, bias=False) self.fc_out = nn.Linear(heads * self.head_dim, embed_size) def",
"self.layers = nn.ModuleList( [ STTransformerBlock( embed_size, heads, adj, time_num, cheb_K,",
"# temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size)",
"and GCN g = torch.sigmoid(self.fs(U_S)) # (7) out = g",
"coding: utf-8 -*- \"\"\" Created on Mon Sep 28 10:28:06",
"12in 12 out self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。",
"# [batch_size, len_q, d_model] return output ''' T 代表Temporal ,MultiHeadAttention",
"#[N, T, C] B, N, T, C = query.shape D_S",
"context.transpose(1, 2).reshape(batch_size, -1, n_heads * d_v) # context: [batch_size, len_q,",
"def __init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self, Q, K, V): '''",
"T, self.heads, self.head_dim).transpose(1, 3) # Q: [B, N, T, C]",
"h, N, T, d_k] context = context.permute(0, 2, 3, 1,",
"self, adj, embed_size, num_layers, heads, time_num, forward_expansion, ##? cheb_K, dropout,",
"* self.head_dim) # [B, N, T, C] # context =",
"# context: [batch_size, len_q, n_heads * d_v] output = self.fc_out(context)",
"if __name__ == '__main__': main() ''' 布置作业: 1. 设计 only",
"32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded size = 512",
"3, 2, 1, 4) # [B, N, T, h, d_k]",
"embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num = time_num self.I = nn.Parameter(torch.eye(time_num,",
"input_Transformer = input_Transformer.permute(1, 2, 0) input_Transformer = input_Transformer.permute(0, 2, 3,",
"context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k]",
"[ STTransformerBlock( embed_size, heads, adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion )",
",MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(TMultiHeadAttention,",
"where mask is True. attn = nn.Softmax(dim=-1)(scores) context = torch.matmul(attn,",
"input_Q.shape # [B, N, T, C] --> [B, N, T,",
"GCN g = torch.sigmoid(self.fs(U_S)) # (7) out = g *",
"= 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded size =",
"= nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels,",
"(Eq 2) forward_expansion = 32 # Dimension of Feed Forward",
"T, C] [B, N, T, C] enc_src = self.encoder(src, t)",
"= context.reshape(B, N, T, self.heads * self.head_dim) # [B, N,",
"Heads in MultiHeadAttention cheb_K = 2 # Order for Chebyshev",
"# Spatial Embedding 部分 # N, T, C = query.shape",
"through normalization and finally dropout x1 = self.norm1(self.STransformer(value, key, query)",
"缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out self.conv2 = nn.Conv2d(T_dim, output_T_dim,",
"forward_expansion): super(TTransformer, self).__init__() # Temporal embedding One hot self.time_num =",
"= time_num # self.one_hot = One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式",
"In the Encoder the query, key, value are all the",
"scr: [N, T, C] [B, N, T, C] enc_src =",
"self).__init__() self.STransformer = STransformer(embed_size, heads, adj, cheb_K, dropout, forward_expansion) self.TTransformer",
"然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1,",
"[B, N, T, C] --> [B, N, T, h *",
"if torch.cuda.is_available() else torch.device(\"cpu\") in_channels = 2 # Channels of",
"out shape: [1, output_T_dim, N, C] out = out.permute(0, 3,",
"# value, key, query: [N, T, C] [B, N, T,",
"K, V): ''' Q: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial)",
"): super(Transformer, self).__init__() self.encoder = Encoder( embed_size, num_layers, heads, adj,",
"= STTransformer( A, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads,",
"T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] attn_mask: [batch_size, n_heads,",
"# Spatial Transformer 部分 query = query + D_S attention",
"self.feed_forward(x) out = self.dropout(self.norm2(forward + x)) return out ### STBlock",
"def __init__(self, embed_size, heads, time_num, dropout, forward_expansion): super(TTransformer, self).__init__() #",
"input_V): ''' input_Q: [batch_size, N, T, C] input_K: [batch_size, N,",
"D_S attention = self.attention(query, query, query) # (B, N, T,",
"Spatial Embedding self.adj = adj self.D_S = adj.to(DEVICE) self.embed_liner =",
"query.shape # D_S = self.embed_liner(self.D_S) # [N, C] # D_S",
"def forward(self, Q, K, V): ''' Q: [batch_size, n_heads, T(Spatial)",
",不能很好的表征数据高维空间的特征,C ---> embedded size 32 or 64 加入dk = 32,",
"value where mask is True. attn = nn.Softmax(dim=-1)(scores) context =",
"return out shape: [N, output_dim] def print_params(model_name, model): param_count =",
"-*- coding: utf-8 -*- \"\"\" Created on Mon Sep 28",
"(B, N, T, C) # Add skip connection, run through",
"__init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self, Q, K, V): ''' Q:",
"nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度 def forward(self, i, N=25, T=12):",
"512 ''' class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self,",
"# input_Transformer = input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1, 2, 0)",
"3, 1, 2, 4) # K: [B, h, N, T,",
"eigs from Param import * from torchsummary import summary DEVICE",
"math # from GCN_models import GCN # from One_hot_encoder import",
"n_heads, seq_len, seq_len] 可能没有 ''' B, n_heads, len1, len2, d_k",
"time_num) # temporal embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num, embed_size) #",
"scipy.sparse.linalg import eigs from Param import * from torchsummary import",
"x1)) return x2 ### Encoder class Encoder(nn.Module): # 堆叠多层 ST-Transformer",
"T, h, d_k] --> [B, h, T, N, d_k] Q",
"[B, h, N, T, d_k] T,dk 就代表是temporal attention K =",
"time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2,",
"Order for Chebyshev Polynomials (Eq 2) forward_expansion = 32 #",
"self.one_hot = One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式 或者 self.temporal_embedding =",
"adj, time_num, device, forward_expansion, cheb_K, dropout, ): super(Encoder, self).__init__() self.embed_size",
"self.head_dim) # [B, N, T, C] # context = context.transpose(1,",
"# (8) return out # (B, N, T, C) class",
"代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads):",
"等号左边 out shape: [B, C, N, output_T_dim] out = self.conv3(out)",
"那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded size = 512 '''",
"设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out",
"'cuda:1' class One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num",
"[batch_size, len_q, n_heads * d_v] output = self.fc_out(context) # [batch_size,",
"nn.Dropout(dropout) def forward(self, value, key, query, t): B, N, T,",
"加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded size",
"D_S = D_S.expand(T, N, C) #[T, N, C]相当于在第一维复制了T份 # D_S",
"d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask",
"def forward(self, value, key, query, t): # value, key, query:",
"sys import pandas as pd def main(): GPU = sys.argv[-1]",
"out self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3 =",
"__name__ == '__main__': main() ''' 布置作业: 1. 设计 only Spatial",
"self.time_num: i % self.time_num + T, :] # onehot =",
"of input embed_size = 32 # Dimension of hidden embedding",
"布置作业: 1. 设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12",
"扩维,成 embeded size self.Transformer = Transformer( adj, embed_size, num_layers, heads,",
"self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # V: [B, h,",
"d_model] return output ''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class",
"Input length, should be the same as prepareData.py output_T_dim =",
"C] [B, N, T, C] # Add skip connection,run through",
"self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # V: [B, h,",
"forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) self.dropout",
"embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout, ):",
"N, C) #[T, N, C]相当于在第一维复制了T份 # D_S = D_S.permute(1, 0,",
"---> embedded size 32 or 64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17",
"= nn.ModuleList( [ STTransformerBlock( embed_size, heads, adj, time_num, cheb_K, dropout=dropout,",
"prepareData.py output_T_dim = 12 # Output Expected length heads =",
"12 步 out 3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in",
"embed_size // heads assert ( self.head_dim * heads == embed_size",
":] # onehot = onehot.repeat(N, 1, 1) onehot = onehot.expand(N,",
"[batch_size, len_q, d_model] return output ''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制",
"T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor",
"12 out self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3",
"or 64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8 ,all",
"cheb_K, dropout, ): super(Encoder, self).__init__() self.embed_size = embed_size self.device =",
"# input_Transformer = input_Transformer.permute(1, 2, 0) input_Transformer = input_Transformer.permute(0, 2,",
"n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]] return context",
"ST-Transformer Block def __init__( self, embed_size, num_layers, heads, adj, time_num,",
"# scores : [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or",
"through normalization and finally dropout x = self.dropout(self.norm1(attention + query))",
"out.squeeze(1) out = out.permute(0, 1, 3, 2) # print('out: ',out.shape)",
"N, T, C] attn_mask: [batch_size, seq_len, seq_len] ''' B, N,",
"forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size, heads, adj, cheb_K, dropout,",
"[batch_size, n_heads, seq_len, seq_len] seq_len = N # context: [batch_size,",
"self.time_num, :] onehot = torch.cat((o1, o2), 0) else: onehot =",
"class Transformer(nn.Module): def __init__( self, adj, embed_size, num_layers, heads, time_num,",
"n_heads * d_v] output = self.fc_out(context) # [batch_size, len_q, d_model]",
"D_S = self.embed_liner(self.D_S) # [N, C] # D_S = D_S.expand(T,",
"forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model) if",
"N, T, h, d_k] --> [B, h, T, N, d_k]",
"# [B, N, T, C] --> [B, N, T, h",
"B, N, T, C = input_Q.shape # [B, N, T,",
"--> [B, h, T, N, d_k] Q = self.W_Q(input_Q).view(B, N,",
"dropout x = self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) U_S",
"t) + x1)) return x2 ### Encoder class Encoder(nn.Module): #",
"def __init__(self, embed_size, time_num=288): super(One_hot_encoder, self).__init__() self.time_num = time_num self.I",
"融合 STransformer and GCN g = torch.sigmoid(self.fs(U_S)) # (7) out",
"should be the same as prepareData.py output_T_dim = 12 #",
"= x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) #",
"[B, N, T, h, d_k] --> [B, h, N, T,",
"T, self.heads, self.head_dim).transpose(1, 3) # K: [B, h, T, N,",
"* self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False)",
"enc_src = self.encoder(src, t) return enc_src # [B, N, T,",
"super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads self.head_dim =",
"解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size 32 or 64 加入dk",
"# scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with",
"[batch_size, len_q, d_model] return output class STransformer(nn.Module): def __init__(self, embed_size,",
"output ''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def",
"pandas as pd def main(): GPU = sys.argv[-1] if len(sys.argv)",
"embed_size) self.fg = nn.Linear(embed_size, embed_size) def forward(self, value, key, query):",
"V: [B, h, T, N, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1,",
"to be divisible by heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V",
"hot编码维度 def forward(self, i, N=25, T=12): if i % self.time_num",
"embed_size, heads, adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for _",
"out ### Transformer class Transformer(nn.Module): def __init__( self, adj, embed_size,",
"= self.I[i % self.time_num: i % self.time_num + T, :]",
"N T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in 12",
"value are all the same. for layer in self.layers: out",
"设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out",
"= nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size,",
"embedding选用nn.Embedding D_T = D_T.expand(B, N, T, C) # temporal embedding加到query。",
"2020 @author: wb \"\"\" import torch import torch.nn as nn",
"heads, cheb_K, forward_expansion, dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion = forward_expansion",
"Encoder( embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout",
"class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self, Q, K,",
"__init__(self, embed_size, heads, adj, time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__()",
"# Q: [B, N, T, C] --[B, N, T, self.heads,",
"T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # K: [B,",
"d_model] return output class STransformer(nn.Module): def __init__(self, embed_size, heads, adj,",
"T, C) # Add skip connection, run through normalization and",
"__init__( self, embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K,",
"[B, N, T, h * d_k] --> [B, N, T,",
"C] # Spatial Transformer 部分 query = query + D_S",
"embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout )",
"n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] attn_mask: [batch_size,",
"self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size,",
"N, T, C] # context = context.transpose(1, 2).reshape(batch_size, -1, n_heads",
"N(Spatial) or T(Temporal), N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) #",
"self.fc_out(context) # [batch_size, len_q, d_model] return output class STransformer(nn.Module): def",
"attn: [batch_size, n_heads, len_q, len_k] context = ScaledDotProductAttention()(Q, K, V)",
"[batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] V:",
"# temporal embedding加到query。 原论文采用concatenated query = query + D_T attention",
"value, key, query, t): # value, key, query: [N, T,",
"): super(STTransformer, self).__init__() self.forward_expansion = forward_expansion # feed forward 的",
"Forward Network: embed_size --> embed_size * forward_expansion --> embed_size dropout",
"torch.Tensor(A) ### Construct Network model = STTransformer( A, in_channels, embed_size,",
"D_T.expand(B, N, T, C) # temporal embedding加到query。 原论文采用concatenated query =",
"N, T, C = query.shape # D_S = self.embed_liner(self.D_S) #",
"self.heads, bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_Q",
"N(Spatial) or T(Temporal), d_k] attn_mask: [batch_size, n_heads, seq_len, seq_len] 可能没有",
"heads): super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads self.head_dim",
"(7) out = g * U_S + (1 - g)",
"heads, time_num, dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size)",
"embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding self.attention",
"dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out self.conv2",
"V) # [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal),",
"ScaledDotProductAttention()(Q, K, V) # [B, h, T, N, d_k] context",
"self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) #",
"self.embed_size = embed_size self.device = device self.layers = nn.ModuleList( [",
"D_S.permute(0, 2, 1, 3) # [B, N, T, C] #",
"g) # (8) return out # (B, N, T, C)",
"model) if __name__ == '__main__': main() ''' 布置作业: 1. 设计",
"def forward(self, x, t): # x: [N, T, C] [B,",
"D_S = D_S.permute(1, 0, 2) #[N, T, C] B, N,",
"d_k] context = context.permute(0, 2, 3, 1, 4) # [B,",
"self.head_dim).transpose(1, 3) # K: [B, h, T, N, d_k] V",
"device, forward_expansion, cheb_K, dropout ) self.device = device def forward(self,",
"= 288 num_layers = 2 # Number of ST Block",
"# 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size, 1) # Channel =",
"Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 2. 设计",
"onehot = onehot.expand(N, T, self.time_num) onehot = self.onehot_Linear(onehot) return onehot",
"堆叠多层 ST-Transformer Block def __init__( self, embed_size, num_layers, heads, adj,",
"1) onehot = onehot.expand(N, T, self.time_num) onehot = self.onehot_Linear(onehot) return",
"forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout)",
"Dimension of hidden embedding features time_num = 288 num_layers =",
"1. 设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步",
"步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1 ,现在要求改成",
"h, T, N, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads,",
"N, T, self.heads, self.head_dim).transpose(1, 3) # Q: [B, N, T,",
"C] input_K: [batch_size, N, T, C] input_V: [batch_size, N, T,",
"heads, adj, cheb_K, dropout, forward_expansion) self.TTransformer = TTransformer(embed_size, heads, time_num,",
"torch import torch.nn as nn import math # from GCN_models",
"self.heads, self.head_dim).transpose(1, 3) # Q: [B, N, T, C] --[B,",
"seq_len] # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads,",
"SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward =",
"1 给 扩维,成 embeded size self.Transformer = Transformer( adj, embed_size,",
"12 步 out 2. 设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果 12",
"ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size 32 or",
"super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size, heads, adj, cheb_K, dropout, forward_expansion)",
"C) # [B, T, N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S =",
"out shape: [N, output_dim] def print_params(model_name, model): param_count = 0",
"self.norm1(self.STransformer(value, key, query) + query) # (B, N, T, C)",
"* embed_size, embed_size), ) self.dropout = nn.Dropout(dropout) def forward(self, value,",
"query.shape # D_T = self.one_hot(t, N, T) # temporal embedding选用one-hot方式",
"size self.Transformer = Transformer( adj, embed_size, num_layers, heads, time_num, forward_expansion,",
"Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # Q:",
"out ### STBlock class STTransformerBlock(nn.Module): def __init__(self, embed_size, heads, adj,",
"n_heads, len_q, len_k] context = ScaledDotProductAttention()(Q, K, V) # [B,",
"K: [B, h, T, N, d_k] V = self.W_V(input_V).view(B, N,",
"# V: [B, h, T, N, d_k] # attn_mask =",
"步in 12 步 out 2. 设计 only Temporal Transformer 的版本,跑出PEMSBAY的结果",
"embed_size) # 线性层改变one hot编码维度 def forward(self, i, N=25, T=12): if",
"2 else '1' device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\")",
"# [B, h, N, T, d_k] context = context.permute(0, 2,",
"3) # K: [B, h, T, N, d_k] V =",
"out, t) return out ### Transformer class Transformer(nn.Module): def __init__(",
"4 # Number of Heads in MultiHeadAttention cheb_K = 2",
"forward = self.feed_forward(x) U_S = self.dropout(self.norm2(forward + x)) # 融合",
"nn.ModuleList( [ STTransformerBlock( embed_size, heads, adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion",
"N(Spatial) or T(Temporal), d_k] K: [batch_size, n_heads, T(Spatial) or N(Temporal),",
"self.W_V = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_K = nn.Linear(self.embed_size,",
"as np from scipy.sparse.linalg import eigs from Param import *",
"V) # [B, h, T, N, d_k] context = context.permute(0,",
"N, T, C] ### ST Transformer: Total Model class STTransformer(nn.Module):",
"adj, cheb_K, dropout, forward_expansion) self.TTransformer = TTransformer(embed_size, heads, time_num, dropout,",
"= self.onehot_Linear(onehot) return onehot ''' Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk:",
"3) # Q: [B, N, T, C] --[B, N, T,",
"context.permute(0, 2, 3, 1, 4) # [B, N, T, h,",
"for Chebyshev Polynomials (Eq 2) forward_expansion = 32 # Dimension",
"dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size, heads, adj, cheb_K,",
"设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 4.",
"D_S.expand(B, T, N, C) # [B, T, N, C] 相当于在第2维复制了T份,",
"onehot = self.I[i % self.time_num: i % self.time_num + T,",
"self.heads = heads self.head_dim = embed_size // heads assert (",
"embed_size, embed_size), ) # 调用GCN self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化",
"forward(self, value, key, query, t): B, N, T, C =",
"N:传感器数量。 T:时间数量 # x = x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE)",
"Q: [B, N, T, C] --[B, N, T, self.heads, self.head_dim]",
"tranformer论文完全对应上,那么dk=64,head = 8 ,all embeded size = 512 ''' class",
"hidden embedding features time_num = 288 num_layers = 2 #",
"self.head_dim * heads == embed_size ), \"Embedding size needs to",
"import torch.nn as nn import math # from GCN_models import",
"* from torchsummary import summary DEVICE = 'cuda:1' class One_hot_encoder(nn.Module):",
"# Channel = 1 给 扩维,成 embeded size self.Transformer =",
"N, T, h, d_k] --> [B, h, N, T, d_k]",
"= self.dropout(self.norm2(forward + x)) return out ### STBlock class STTransformerBlock(nn.Module):",
"self.attention(query, query, query) # (B, N, T, C) # Add",
"N(Spatial) or T(Temporal), d_k]] return context ''' S 代表spatial ,MultiHeadAttention",
"class TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size =",
"A = pd.read_csv(ADJPATH).values A = torch.Tensor(A) ### Construct Network model",
"only Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 3.",
"nn.Linear(heads * self.head_dim, embed_size) def forward(self, input_Q, input_K, input_V): '''",
"* self.head_dim, embed_size) def forward(self, input_Q, input_K, input_V): ''' input_Q:",
"out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1 ,现在要求改成 B,N,T,C=2,",
"context = context.reshape(B, N, T, self.heads * self.head_dim) # [B,",
"+ (1 - g) # (8) return out # (B,",
"as pd def main(): GPU = sys.argv[-1] if len(sys.argv) ==",
"embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 =",
"'__main__': main() ''' 布置作业: 1. 设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果",
"torch.device(\"cpu\") in_channels = 2 # Channels of input embed_size =",
"heads, adj, time_num, cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer =",
"self.temporal_embedding = nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size,",
"1, 1) # attn_mask : [batch_size, n_heads, seq_len, seq_len] seq_len",
"N, T, C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) # [B, N,",
") self.dropout = nn.Dropout(dropout) def forward(self, value, key, query, t):",
"super(STTransformer, self).__init__() self.forward_expansion = forward_expansion # feed forward 的 embeded",
"d_k] attn_mask: [batch_size, n_heads, seq_len, seq_len] 可能没有 ''' B, n_heads,",
"self.head_dim).permute(0, 3, 1, 2, 4) # Q: [B, h, N,",
"--> embed_size * forward_expansion --> embed_size dropout = 0 A",
"def forward(self, i, N=25, T=12): if i % self.time_num +",
"= embed_size self.device = device self.layers = nn.ModuleList( [ STTransformerBlock(",
"time_num=288): super(One_hot_encoder, self).__init__() self.time_num = time_num self.I = nn.Parameter(torch.eye(time_num, time_num,",
"forward(self, i, N=25, T=12): if i % self.time_num + T",
"Chebyshev Polynomials (Eq 2) forward_expansion = 32 # Dimension of",
"= torch.Tensor(A) ### Construct Network model = STTransformer( A, in_channels,",
"2).reshape(batch_size, -1, n_heads * d_v) # context: [batch_size, len_q, n_heads",
"2 # Order for Chebyshev Polynomials (Eq 2) forward_expansion =",
"步in 12 步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T",
"self.time_num: o1 = self.I[i % self.time_num:, :] o2 = self.I[0:",
"self.heads * self.head_dim) # [B, N, T, C] # context",
"embed_size), ) self.dropout = nn.Dropout(dropout) def forward(self, value, key, query,",
"d_v] output = self.fc_out(context) # [batch_size, len_q, d_model] return output",
"def forward(self, input_Q, input_K, input_V): ''' input_Q: [batch_size, N, T,",
"i % self.time_num + T > self.time_num: o1 = self.I[i",
"[B, h, N, T, d_k] context = context.permute(0, 2, 3,",
"N, C) # [B, T, N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S",
"self.conv2 = nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size,",
"in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout).to(DEVICE)",
"4) # V: [B, h, N, T, d_k] # attn_mask",
"self.TTransformer = TTransformer(embed_size, heads, time_num, dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size)",
"d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) #",
"V: [B, h, N, T, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1,",
"= self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # K: [B,",
"''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def __init__(self,",
"= nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def forward(self,",
"query = query + D_S attention = self.attention(query, query, query)",
"heads, time_num, forward_expansion, cheb_K, dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or",
": [batch_size, n_heads, seq_len, seq_len] # context: [batch_size, n_heads, len_q,",
"Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size",
"import sys import pandas as pd def main(): GPU =",
"# input x shape[ C, N, T] # C:通道数量。 N:传感器数量。",
"super(TTransformer, self).__init__() # Temporal embedding One hot self.time_num = time_num",
"--> embed_size dropout = 0 A = pd.read_csv(ADJPATH).values A =",
"[B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K = self.W_K(input_K).view(B, N, T, self.heads,",
"nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def forward(self, value, key, query, t):",
"V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2,",
"= D_S.expand(T, N, C) #[T, N, C]相当于在第一维复制了T份 # D_S =",
"* self.heads, bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False)",
"= self.conv1(x) # conv 要求第二维度是C, 也就是必须得B C + 其他 #",
"A = torch.Tensor(A) ### Construct Network model = STTransformer( A,",
"C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in 12 步 out",
"T, h, d_k] context = context.reshape(B, N, T, self.heads *",
"N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model) if __name__ == '__main__': main()",
"V: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]",
"# temporal embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal",
"N(Temporal), N(Spatial) or T(Temporal), d_k] attn_mask: [batch_size, n_heads, seq_len, seq_len]",
"embed_size, heads, adj, cheb_K, dropout, forward_expansion): super(STransformer, self).__init__() # Spatial",
"self.heads, bias=False) self.fc_out = nn.Linear(heads * self.head_dim, embed_size) def forward(self,",
"attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size, n_heads, seq_len,",
"N, T, C] enc_src = self.encoder(src, t) return enc_src #",
"T, C] B, N, T, C = query.shape D_S =",
"T, C] # Spatial Transformer 部分 query = query +",
"output_T_dim, N, C] out = out.permute(0, 3, 2, 1) #",
"embeded size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size, 1)",
"= 1 给 扩维,成 embeded size self.Transformer = Transformer( adj,",
"encoding D_S = D_S.expand(B, T, N, C) # [B, T,",
"self.layers: out = layer(out, out, out, t) return out ###",
"1, N, output_T_dim] # out = out.squeeze(1) out = out.permute(0,",
"Number of ST Block T_dim = 12 # Input length,",
"embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T",
"time_num, device, forward_expansion, cheb_K, dropout, ): super(Encoder, self).__init__() self.embed_size =",
"Q.shape scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores",
"-*- \"\"\" Created on Mon Sep 28 10:28:06 2020 @author:",
"), \"Embedding size needs to be divisible by heads\" #",
"h, T, N, d_k] context = context.permute(0, 3, 2, 1,",
"+ D_S attention = self.attention(query, query, query) # (B, N,",
"x shape[ C, N, T] # C:通道数量。 N:传感器数量。 T:时间数量 #",
"''' Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded",
"nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size)",
"Dimension of Feed Forward Network: embed_size --> embed_size * forward_expansion",
"len_k] context = ScaledDotProductAttention()(Q, K, V) # [B, h, N,",
"K: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]",
"self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion *",
"all the same. for layer in self.layers: out = layer(out,",
"= context.transpose(1, 2).reshape(batch_size, -1, n_heads * d_v) # context: [batch_size,",
"heads, time_num, forward_expansion, ##? cheb_K, dropout, device=DEVICE ): super(Transformer, self).__init__()",
"nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) # 调用GCN self.norm_adj =",
"Block def __init__( self, embed_size, num_layers, heads, adj, time_num, device,",
"# [B, T, N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0,",
"t) return enc_src # [B, N, T, C] ### ST",
"# K: [B, h, T, N, d_k] V = self.W_V(input_V).view(B,",
"T, N, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)",
"out = out.squeeze(1) out = out.permute(0, 1, 3, 2) #",
"self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # Q: [B, N,",
"in total.') return import sys import pandas as pd def",
"embed_size dropout = 0 A = pd.read_csv(ADJPATH).values A = torch.Tensor(A)",
"out = layer(out, out, out, t) return out ### Transformer",
"= nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): # platform: (CHANNEL,",
"src, t): ## scr: [N, T, C] [B, N, T,",
"相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0, 2, 1, 3) # [B,",
"代表spatial ,MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads):",
"of hidden embedding features time_num = 288 num_layers = 2",
"= self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4)",
"return import sys import pandas as pd def main(): GPU",
"= self.norm1(self.STransformer(value, key, query) + query) # (B, N, T,",
"N, T, C) class TTransformer(nn.Module): def __init__(self, embed_size, heads, time_num,",
"attn_mask : [batch_size, n_heads, seq_len, seq_len] # context: [batch_size, n_heads,",
"adj, time_num, device, forward_expansion, cheb_K, dropout ) self.device = device",
"def forward(self, x): # platform: (CHANNEL, TIMESTEP_IN, N_NODE) # input",
"dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model) if __name__",
"platform: (CHANNEL, TIMESTEP_IN, N_NODE) # input x shape[ C, N,",
"# 线性层改变one hot编码维度 def forward(self, i, N=25, T=12): if i",
"self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size, heads) self.norm1 =",
"dropout, forward_expansion) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout =",
"n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] V: [batch_size,",
"super(ScaledDotProductAttention, self).__init__() def forward(self, Q, K, V): ''' Q: [batch_size,",
"output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels, 1) self.relu",
"torch.cuda.is_available() else torch.device(\"cpu\") in_channels = 2 # Channels of input",
"if i % self.time_num + T > self.time_num: o1 =",
"D_S = D_S.permute(0, 2, 1, 3) # [B, N, T,",
"# Add skip connection, run through normalization and finally dropout",
"= self.dropout(self.norm2(forward + x)) # 融合 STransformer and GCN g",
"self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs =",
"value, key, query: [N, T, C] [B, N, T, C]",
"shape: [B, C, N, output_T_dim] out = self.conv3(out) # 等号左边",
"= D_S.expand(B, T, N, C) # [B, T, N, C]",
"T, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0, 3,",
"nn.Linear(forward_expansion * embed_size, embed_size), ) # 调用GCN self.norm_adj = nn.InstanceNorm2d(1)",
"# [B, N, T, h, d_k] context = context.reshape(B, N,",
"TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size",
"# 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_K",
"N, T, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).permute(0,",
"% self.time_num + T, :] # onehot = onehot.repeat(N, 1,",
"dropout ) self.device = device def forward(self, src, t): ##",
"# -*- coding: utf-8 -*- \"\"\" Created on Mon Sep",
"heads, adj, time_num, device, forward_expansion, cheb_K, dropout ) self.device =",
"for layer in self.layers: out = layer(out, out, out, t)",
"dropout=dropout, forward_expansion=forward_expansion ) for _ in range(num_layers) ] ) self.dropout",
"def __init__(self, embed_size, heads, adj, cheb_K, dropout, forward_expansion): super(STransformer, self).__init__()",
"forward 的 embeded size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels,",
"其他 # input_Transformer = input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1, 2,",
"32 or 64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head = 8",
"import One_hot_encoder import torch.nn.functional as F import numpy as np",
"= self.feed_forward(x) out = self.dropout(self.norm2(forward + x)) return out ###",
"-1e9) # Fills elements of self tensor with value where",
"as F import numpy as np from scipy.sparse.linalg import eigs",
"# [N, C] ---position encoding D_S = D_S.expand(B, T, N,",
"embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) # 调用GCN self.norm_adj",
"D_T = D_T.expand(B, N, T, C) # temporal embedding加到query。 原论文采用concatenated",
"T, C] input_V: [batch_size, N, T, C] attn_mask: [batch_size, seq_len,",
"cheb_K, dropout, forward_expansion): super(STTransformerBlock, self).__init__() self.STransformer = STransformer(embed_size, heads, adj,",
"tensor with value where mask is True. attn = nn.Softmax(dim=-1)(scores)",
"= torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size,",
"B, n_heads, len1, len2, d_k = Q.shape scores = torch.matmul(Q,",
"[B, h, N, T, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads,",
"2, 4) # K: [B, h, N, T, d_k] V",
"# (B, N, T, C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1,",
"or N(Temporal), N(Spatial) or T(Temporal), d_k] K: [batch_size, n_heads, T(Spatial)",
"= embed_size self.heads = heads self.head_dim = embed_size // heads",
"param in model.named_parameters(): if param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count}",
"torch.nn as nn import math # from GCN_models import GCN",
"folder workMETRLA # MODEL CODE # -*- coding: utf-8 -*-",
"[N, C] # D_S = D_S.expand(T, N, C) #[T, N,",
"C = query.shape D_S = self.embed_liner(self.D_S) # [N, C] ---position",
"然后跑出1,2,3 升级版结果。 12 步in 12 步 out PEMSBAY 数据集 '''",
"adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size, heads) self.norm1",
"2 # Number of ST Block T_dim = 12 #",
"nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): # platform: (CHANNEL, TIMESTEP_IN,",
"要求第二维度是C, 也就是必须得B C + 其他 # input_Transformer = input_Transformer.squeeze(0) #",
"forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) #",
"range(num_layers) ] ) self.dropout = nn.Dropout(dropout) def forward(self, x, t):",
"> self.time_num: o1 = self.I[i % self.time_num:, :] o2 =",
"attention = self.attention(query, query, query) # (B, N, T, C)",
"heads == embed_size ), \"Embedding size needs to be divisible",
"N, C] # output_Transformer = output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) #",
"2) # print('out: ',out.shape) return out # [B, N, output_dim]",
"C] ---position encoding D_S = D_S.expand(B, T, N, C) #",
"N, T, C] output_Transformer = output_Transformer.permute(0, 2, 1, 3) #",
"self.heads, self.head_dim).transpose(1, 3) # V: [B, h, T, N, d_k]",
"dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion = forward_expansion # feed forward",
"# D_S = D_S.permute(1, 0, 2) #[N, T, C] B,",
"<filename>metr-la/model/Double_C_STTN.py<gh_stars>1-10 # from folder workMETRLA # MODEL CODE # -*-",
"数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size 32 or 64 加入dk =",
"T, self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K =",
"T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # V: [B,",
"可能没有 ''' B, n_heads, len1, len2, d_k = Q.shape scores",
"forward(self, input_Q, input_K, input_V): ''' input_Q: [batch_size, N, T, C]",
"t): # x: [N, T, C] [B, N, T, C]",
"key, query: [N, T, C] [B, N, T, C] #",
"seq_len, seq_len] ''' B, N, T, C = input_Q.shape #",
"### Encoder class Encoder(nn.Module): # 堆叠多层 ST-Transformer Block def __init__(",
"= input_Transformer.permute(1, 2, 0) input_Transformer = input_Transformer.permute(0, 2, 3, 1)",
"[B, h, T, N, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads,",
"or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9) # Fills elements of self",
"nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion",
"# D_S = self.embed_liner(self.D_S) # [N, C] # D_S =",
"28 10:28:06 2020 @author: wb \"\"\" import torch import torch.nn",
"Channel = 1 给 扩维,成 embeded size self.Transformer = Transformer(",
"Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 3. 设计 Temporal-Spatial",
"query, t): B, N, T, C = query.shape # D_T",
"T, N, d_k] context = context.permute(0, 3, 2, 1, 4)",
"T:时间数量 # x = x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer",
"# (7) out = g * U_S + (1 -",
"input_Transformer = self.conv1(x) # conv 要求第二维度是C, 也就是必须得B C + 其他",
"= self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # V: [B,",
"''' class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention, self).__init__() def forward(self, Q,",
"# temporal embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num, embed_size) # temporal",
"def forward(self, src, t): ## scr: [N, T, C] [B,",
"= 4 # Number of Heads in MultiHeadAttention cheb_K =",
"Q, K, V): ''' Q: [batch_size, n_heads, T(Spatial) or N(Temporal),",
"or T(Temporal), d_k] K: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial)",
"= SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward",
"= torch.matmul(attn, V) # [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial)",
"input_K: [batch_size, N, T, C] input_V: [batch_size, N, T, C]",
"STTransformerBlock(nn.Module): def __init__(self, embed_size, heads, adj, time_num, cheb_K, dropout, forward_expansion):",
"2, 4) # Q: [B, h, N, T, d_k] T,dk",
"query: [N, T, C] [B, N, T, C] # Spatial",
"+ T) % self.time_num, :] onehot = torch.cat((o1, o2), 0)",
"embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout=0 ):",
"num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout ) self.device",
"or T(Temporal), d_k] V: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial)",
"output class STransformer(nn.Module): def __init__(self, embed_size, heads, adj, cheb_K, dropout,",
"input x shape[ C, N, T] # C:通道数量。 N:传感器数量。 T:时间数量",
"# C:通道数量。 N:传感器数量。 T:时间数量 # x = x.unsqueeze(0) # x",
"self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.fc_out",
"= query.shape # D_S = self.embed_liner(self.D_S) # [N, C] #",
"h, d_k] context = context.reshape(B, N, T, self.heads * self.head_dim)",
"N, T, C = query.shape # D_T = self.one_hot(t, N,",
"import pandas as pd def main(): GPU = sys.argv[-1] if",
"time_num, dropout, forward_expansion): super(TTransformer, self).__init__() # Temporal embedding One hot",
"query) # (B, N, T, C) # Add skip connection,",
"= nn.Dropout(dropout) def forward(self, value, key, query, t): # value,",
"0, 2) #[N, T, C] B, N, T, C =",
"[B, N, T, C] # Add skip connection,run through normalization",
"self, adj, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K,",
"= self.embed_liner(self.D_S) # [N, C] ---position encoding D_S = D_S.expand(B,",
"(2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model) if __name__ == '__main__':",
"+ 其他 # input_Transformer = input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1,",
"# feed forward 的 embeded size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1",
"Spatial Embedding 部分 # N, T, C = query.shape #",
"self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) #",
"Channels of input embed_size = 32 # Dimension of hidden",
"self.forward_expansion) # [B, N, T, C] output_Transformer = output_Transformer.permute(0, 2,",
"STransformer(nn.Module): def __init__(self, embed_size, heads, adj, cheb_K, dropout, forward_expansion): super(STransformer,",
"# output_Transformer shape[B, T, N, C] # output_Transformer = output_Transformer.unsqueeze(0)",
"ScaledDotProductAttention()(Q, K, V) # [B, h, N, T, d_k] context",
"T, d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0, 3,",
"= device def forward(self, src, t): ## scr: [N, T,",
"N, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1, 3)",
"self.onehot_Linear(onehot) return onehot ''' Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1",
"output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer)) # 等号左边 out shape: [1, output_T_dim,",
"- g) # (8) return out # (B, N, T,",
"forward(self, src, t): ## scr: [N, T, C] [B, N,",
"[batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), N(Spatial) or",
"self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # K: [B, h,",
"num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout=0 ): super(STTransformer, self).__init__()",
"T, C] input_K: [batch_size, N, T, C] input_V: [batch_size, N,",
"[N, T, C] [B, N, T, C] # Spatial Embedding",
"K, V) # [B, h, T, N, d_k] context =",
"3, 1, 4) # [B, N, T, h, d_k] context",
"nn import math # from GCN_models import GCN # from",
"self).__init__() self.time_num = time_num self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear",
"F import numpy as np from scipy.sparse.linalg import eigs from",
"# from GCN_models import GCN # from One_hot_encoder import One_hot_encoder",
"class Encoder(nn.Module): # 堆叠多层 ST-Transformer Block def __init__( self, embed_size,",
"* d_v] output = self.fc_out(context) # [batch_size, len_q, d_model] return",
"self.fs = nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size, embed_size) def forward(self,",
"或者 self.temporal_embedding = nn.Embedding(time_num, embed_size) # temporal embedding选用nn.Embedding self.attention =",
"[B, T, N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0, 2,",
"x2 ### Encoder class Encoder(nn.Module): # 堆叠多层 ST-Transformer Block def",
"self.conv1(x) # conv 要求第二维度是C, 也就是必须得B C + 其他 # input_Transformer",
"query)) forward = self.feed_forward(x) U_S = self.dropout(self.norm2(forward + x)) #",
"[B, N, T, C] # context = context.transpose(1, 2).reshape(batch_size, -1,",
"self.conv3 = nn.Conv2d(embed_size, in_channels, 1) self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。",
"T, C = query.shape D_S = self.embed_liner(self.D_S) # [N, C]",
"embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads = heads",
"nn.Dropout(dropout) def forward(self, value, key, query, t): # value, key,",
"heads assert ( self.head_dim * heads == embed_size ), \"Embedding",
"size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size, 1) #",
"[B, N, T, C] out = self.dropout(x) # In the",
"% self.time_num:, :] o2 = self.I[0: (i + T) %",
"import eigs from Param import * from torchsummary import summary",
"B, N, T, C = query.shape D_S = self.embed_liner(self.D_S) #",
"T, N, d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1,",
"self.dropout(self.norm2(forward + x)) # 融合 STransformer and GCN g =",
"# Fills elements of self tensor with value where mask",
"One_hot_encoder import One_hot_encoder import torch.nn.functional as F import numpy as",
"# context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q,",
"One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num, embed_size)",
"= self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) out = self.dropout(self.norm2(forward",
"= nn.Conv2d(in_channels, embed_size, 1) # Channel = 1 给 扩维,成",
"GCN # from One_hot_encoder import One_hot_encoder import torch.nn.functional as F",
"main() ''' 布置作业: 1. 设计 only Spatial Transformer 的版本,跑出PEMSBAY的结果 12",
"= self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) # Q: [B,",
"288 num_layers = 2 # Number of ST Block T_dim",
"# 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size) self.fg",
"key, query, t): # value, key, query: [N, T, C]",
"onehot = torch.cat((o1, o2), 0) else: onehot = self.I[i %",
"# (B, N, T, C) class TTransformer(nn.Module): def __init__(self, embed_size,",
"= out.permute(0, 1, 3, 2) # print('out: ',out.shape) return out",
"seq_len = N # context: [batch_size, n_heads, len_q, d_v], attn:",
"nn.Conv2d(T_dim, output_T_dim, 1) # 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels, 1)",
"torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads,",
"Param import * from torchsummary import summary DEVICE = 'cuda:1'",
"embed_size, 1) # Channel = 1 给 扩维,成 embeded size",
"self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K = self.W_K(input_K).view(B, N,",
"length heads = 4 # Number of Heads in MultiHeadAttention",
"ST Transformer: Total Model class STTransformer(nn.Module): def __init__( self, adj,",
"else '1' device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\") in_channels",
"query) + query) # (B, N, T, C) x2 =",
"D_T = self.one_hot(t, N, T) # temporal embedding选用one-hot方式 或者 D_T",
"= D_S.permute(1, 0, 2) #[N, T, C] B, N, T,",
"# context = context.transpose(1, 2).reshape(batch_size, -1, n_heads * d_v) #",
"query, query) # (B, N, T, C) # Add skip",
"[batch_size, seq_len, seq_len] ''' B, N, T, C = input_Q.shape",
"onehot = onehot.repeat(N, 1, 1) onehot = onehot.expand(N, T, self.time_num)",
"T_dim = 12 # Input length, should be the same",
"time_num self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size)",
"d_k] --> [B, h, N, T, d_k] Q = self.W_Q(input_Q).view(B,",
"T, d_k] context = context.permute(0, 2, 3, 1, 4) #",
"seq_len] 可能没有 ''' B, n_heads, len1, len2, d_k = Q.shape",
"self.embed_size = embed_size self.heads = heads self.head_dim = embed_size //",
"= self.embed_liner(self.D_S) # [N, C] # D_S = D_S.expand(T, N,",
"total.') return import sys import pandas as pd def main():",
"[B, h, T, N, d_k] context = context.permute(0, 3, 2,",
"Transformer class Transformer(nn.Module): def __init__( self, adj, embed_size, num_layers, heads,",
"onehot.repeat(N, 1, 1) onehot = onehot.expand(N, T, self.time_num) onehot =",
"Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 4. 前面的版本完成后,全部升级为,C 维度由1变成2,多的一个C是时间戳,时间戳的写法,参考",
"forward_expansion) self.TTransformer = TTransformer(embed_size, heads, time_num, dropout, forward_expansion) self.norm1 =",
"time_num, device, forward_expansion, cheb_K, dropout ) self.device = device def",
"= nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim",
"Encoder the query, key, value are all the same. for",
"(B, N, T, C) class TTransformer(nn.Module): def __init__(self, embed_size, heads,",
"output_T_dim, heads, cheb_K, forward_expansion, dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion =",
"= torch.sigmoid(self.fs(U_S)) # (7) out = g * U_S +",
"embed_size self.device = device self.layers = nn.ModuleList( [ STTransformerBlock( embed_size,",
"param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count} trainable parameters in total.')",
"= attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size, n_heads,",
"def print_params(model_name, model): param_count = 0 for name, param in",
"T(Temporal), d_k]] return context ''' S 代表spatial ,MultiHeadAttention 代表多头注意力机制 '''",
"query): # value, key, query: [N, T, C] [B, N,",
"nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim *",
"the same. for layer in self.layers: out = layer(out, out,",
"self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) U_S = self.dropout(self.norm2(forward +",
"x: [N, T, C] [B, N, T, C] out =",
"adj, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion,",
"forward_expansion, cheb_K, dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12",
"h, N, T, d_k] V = self.W_V(input_V).view(B, N, T, self.heads,",
"T, C) # temporal embedding加到query。 原论文采用concatenated query = query +",
"n_heads, 1, 1) # attn_mask : [batch_size, n_heads, seq_len, seq_len]",
"x1, x1, t) + x1)) return x2 ### Encoder class",
"= onehot.expand(N, T, self.time_num) onehot = self.onehot_Linear(onehot) return onehot '''",
"--> [B, h, N, T, d_k] Q = self.W_Q(input_Q).view(B, N,",
"seq_len] ''' B, N, T, C = input_Q.shape # [B,",
"num_layers, heads, adj, time_num, device, forward_expansion, cheb_K, dropout, ): super(Encoder,",
"= nn.Conv2d(embed_size, in_channels, 1) self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def",
"T, C] attn_mask: [batch_size, seq_len, seq_len] ''' B, N, T,",
"connection, run through normalization and finally dropout x = self.dropout(self.norm1(attention",
"query, key, value are all the same. for layer in",
"from torchsummary import summary DEVICE = 'cuda:1' class One_hot_encoder(nn.Module): def",
"Temporal Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 3. 设计",
"= nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度 def forward(self, i, N=25,",
"T, h * d_k] --> [B, N, T, h, d_k]",
"+ x)) return out ### STBlock class STTransformerBlock(nn.Module): def __init__(self,",
"in range(num_layers) ] ) self.dropout = nn.Dropout(dropout) def forward(self, x,",
"n_heads, len_q, d_v], attn: [batch_size, n_heads, len_q, len_k] context =",
"seq_len, seq_len] seq_len = N # context: [batch_size, n_heads, len_q,",
"@author: wb \"\"\" import torch import torch.nn as nn import",
"[1, output_T_dim, N, C] out = out.permute(0, 3, 2, 1)",
"self).__init__() self.forward_expansion = forward_expansion # feed forward 的 embeded size",
"= input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1, 2, 0) input_Transformer =",
"embed_size) def forward(self, input_Q, input_K, input_V): ''' input_Q: [batch_size, N,",
"# Temporal embedding One hot self.time_num = time_num # self.one_hot",
"in model.named_parameters(): if param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count} trainable",
"embed_size --> embed_size * forward_expansion --> embed_size dropout = 0",
"time_num, forward_expansion, ##? cheb_K, dropout, device=DEVICE ): super(Transformer, self).__init__() self.encoder",
"--[B, N, T, self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention",
"N, T, d_k] # attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1)",
"= input_Transformer.permute(0, 2, 3, 1) # input_Transformer shape[N, T, C]",
"N, C]相当于在第一维复制了T份 # D_S = D_S.permute(1, 0, 2) #[N, T,",
"output_Transformer shape[B, T, N, C] # output_Transformer = output_Transformer.unsqueeze(0) out",
"layer in self.layers: out = layer(out, out, out, t) return",
"attn_mask: [batch_size, seq_len, seq_len] ''' B, N, T, C =",
"-1, n_heads * d_v) # context: [batch_size, len_q, n_heads *",
"embedded size 32 or 64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head",
"return onehot ''' Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C",
"32 # Dimension of Feed Forward Network: embed_size --> embed_size",
"nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size),",
"### STBlock class STTransformerBlock(nn.Module): def __init__(self, embed_size, heads, adj, time_num,",
"N(Temporal), N(Spatial) or T(Temporal), N(Spatial) or T(Temporal)] # scores.masked_fill_(attn_mask, -1e9)",
"的 embeded size 8,16,32....1024 # 第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size,",
"N, T, C] --> [B, N, T, h * d_k]",
"[batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] attn_mask:",
"= nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size, embed_size) def forward(self, value,",
"self.conv3(out) # 等号左边 out shape: [B, 1, N, output_T_dim] #",
"Construct Network model = STTransformer( A, in_channels, embed_size, time_num, num_layers,",
"C) # Add skip connection, run through normalization and finally",
"# [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k]]",
"self.head_dim).transpose(1, 3) # Q: [B, N, T, C] --[B, N,",
"dropout, ): super(Encoder, self).__init__() self.embed_size = embed_size self.device = device",
"D_S.permute(1, 0, 2) #[N, T, C] B, N, T, C",
"C] attn_mask: [batch_size, seq_len, seq_len] ''' B, N, T, C",
"output_dim] def print_params(model_name, model): param_count = 0 for name, param",
"T, self.heads * self.head_dim) # [B, N, T, C] #",
"1, 3) # output_Transformer shape[B, T, N, C] # output_Transformer",
"class STTransformer(nn.Module): def __init__( self, adj, in_channels, embed_size, time_num, num_layers,",
"query) # Add skip connection, run through normalization and finally",
"T, C = query.shape # D_T = self.one_hot(t, N, T)",
"1, 3, 2) # print('out: ',out.shape) return out # [B,",
"N, C] out = out.permute(0, 3, 2, 1) # 等号左边",
"= nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.fc_out = nn.Linear(heads *",
"t): # value, key, query: [N, T, C] [B, N,",
"= input_Q.shape # [B, N, T, C] --> [B, N,",
"Network: embed_size --> embed_size * forward_expansion --> embed_size dropout =",
"= nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion",
"else: onehot = self.I[i % self.time_num: i % self.time_num +",
"forward_expansion --> embed_size dropout = 0 A = pd.read_csv(ADJPATH).values A",
") for _ in range(num_layers) ] ) self.dropout = nn.Dropout(dropout)",
"N, T, d_k] T,dk 就代表是temporal attention K = self.W_K(input_K).view(B, N,",
"---position encoding D_S = D_S.expand(B, T, N, C) # [B,",
"self.I[i % self.time_num:, :] o2 = self.I[0: (i + T)",
"return enc_src # [B, N, T, C] ### ST Transformer:",
"self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # Q: [B, h,",
"dropout, forward_expansion): super(STransformer, self).__init__() # Spatial Embedding self.adj = adj",
"= 32 # Dimension of Feed Forward Network: embed_size -->",
"# temporal embedding选用nn.Embedding D_T = D_T.expand(B, N, T, C) #",
"super(STransformer, self).__init__() # Spatial Embedding self.adj = adj self.D_S =",
"self.Transformer = Transformer( adj, embed_size, num_layers, heads, time_num, forward_expansion, cheb_K,",
"* forward_expansion --> embed_size dropout = 0 A = pd.read_csv(ADJPATH).values",
"context: [batch_size, len_q, n_heads * d_v] output = self.fc_out(context) #",
"length, should be the same as prepareData.py output_T_dim = 12",
"from GCN_models import GCN # from One_hot_encoder import One_hot_encoder import",
"[B, C, N, output_T_dim] out = self.conv3(out) # 等号左边 out",
"import numpy as np from scipy.sparse.linalg import eigs from Param",
"2, 1, 4) # [B, N, T, h, d_k] context",
"-2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, T(Spatial) or",
"2, 4) # V: [B, h, N, T, d_k] #",
"T, C] [B, N, T, C] out = self.dropout(x) #",
"# 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): # platform: (CHANNEL, TIMESTEP_IN, N_NODE)",
"self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): # platform:",
"1, 1) onehot = onehot.expand(N, T, self.time_num) onehot = self.onehot_Linear(onehot)",
"C] out = self.dropout(x) # In the Encoder the query,",
"bias=False) self.fc_out = nn.Linear(heads * self.head_dim, embed_size) def forward(self, input_Q,",
"{param_count} trainable parameters in total.') return import sys import pandas",
"TIMESTEP_IN, N_NODE) # input x shape[ C, N, T] #",
"维度由1变成2,多的一个C是时间戳,时间戳的写法,参考 也就是说原来是B N T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12",
"T, C] output_Transformer = output_Transformer.permute(0, 2, 1, 3) # output_Transformer",
"# attn_mask : [batch_size, n_heads, seq_len, seq_len] # context: [batch_size,",
"super(One_hot_encoder, self).__init__() self.time_num = time_num self.I = nn.Parameter(torch.eye(time_num, time_num, requires_grad=True))",
"be the same as prepareData.py output_T_dim = 12 # Output",
"B, N, T, C = query.shape # D_T = self.one_hot(t,",
"# [B, N, output_dim] # return out shape: [N, output_dim]",
"[B, N, T, C] ### ST Transformer: Total Model class",
"in_channels, 1) self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x):",
"d_k] T,dk 就代表是temporal attention K = self.W_K(input_K).view(B, N, T, self.heads,",
"= context.permute(0, 2, 3, 1, 4) # [B, N, T,",
"import torch.nn.functional as F import numpy as np from scipy.sparse.linalg",
"context.permute(0, 3, 2, 1, 4) # [B, N, T, h,",
"N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4) # K:",
"self.encoder(src, t) return enc_src # [B, N, T, C] ###",
"# from One_hot_encoder import One_hot_encoder import torch.nn.functional as F import",
"return out ### STBlock class STTransformerBlock(nn.Module): def __init__(self, embed_size, heads,",
"# onehot = onehot.repeat(N, 1, 1) onehot = onehot.expand(N, T,",
"len1, len2, d_k = Q.shape scores = torch.matmul(Q, K.transpose(-1, -2))",
",MultiHeadAttention 代表多头注意力机制 ''' class SMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(SMultiHeadAttention,",
"= self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0, 3, 1, 2, 4)",
"torch.cat((o1, o2), 0) else: onehot = self.I[i % self.time_num: i",
"也就是说原来是B N T C=1 ,现在要求改成 B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in",
"T, N, C] # output_Transformer = output_Transformer.unsqueeze(0) out = self.relu(self.conv2(output_Transformer))",
"N, output_dim] # return out shape: [N, output_dim] def print_params(model_name,",
"elements of self tensor with value where mask is True.",
"STBlock class STTransformerBlock(nn.Module): def __init__(self, embed_size, heads, adj, time_num, cheb_K,",
"shape: [B, 1, N, output_T_dim] # out = out.squeeze(1) out",
"和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): # platform: (CHANNEL, TIMESTEP_IN, N_NODE) #",
"# 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out self.conv2 = nn.Conv2d(T_dim,",
"C, N, T] # C:通道数量。 N:传感器数量。 T:时间数量 # x =",
"D_T attention = self.attention(query, query, query) # Add skip connection,",
"缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels, 1) self.relu = nn.ReLU() #",
"input_Transformer.permute(1, 2, 0) input_Transformer = input_Transformer.permute(0, 2, 3, 1) #",
"self.attention(query, query, query) # Add skip connection, run through normalization",
"num_layers = 2 # Number of ST Block T_dim =",
"1) self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self, x): #",
"[B, N, T, C] output_Transformer = output_Transformer.permute(0, 2, 1, 3)",
":] onehot = torch.cat((o1, o2), 0) else: onehot = self.I[i",
"Encoder class Encoder(nn.Module): # 堆叠多层 ST-Transformer Block def __init__( self,",
"N, T, self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K",
"C] # Add skip connection,run through normalization and finally dropout",
"torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\") in_channels = 2 # Channels",
"T, d_k] T,dk 就代表是temporal attention K = self.W_K(input_K).view(B, N, T,",
"self.head_dim).permute(0, 3, 1, 2, 4) # K: [B, h, N,",
"nn.Parameter(torch.eye(time_num, time_num, requires_grad=True)) self.onehot_Linear = nn.Linear(time_num, embed_size) # 线性层改变one hot编码维度",
"= query + D_T attention = self.attention(query, query, query) #",
"): super(Encoder, self).__init__() self.embed_size = embed_size self.device = device self.layers",
"12 # Input length, should be the same as prepareData.py",
"nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) self.dropout = nn.Dropout(dropout) def",
"forward = self.feed_forward(x) out = self.dropout(self.norm2(forward + x)) return out",
"N, T, C = input_Q.shape # [B, N, T, C]",
"= context.permute(0, 3, 2, 1, 4) # [B, N, T,",
"trainable parameters in total.') return import sys import pandas as",
"N=25, T=12): if i % self.time_num + T > self.time_num:",
"Model class STTransformer(nn.Module): def __init__( self, adj, in_channels, embed_size, time_num,",
"= nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V) # [batch_size, n_heads, T(Spatial)",
"Block T_dim = 12 # Input length, should be the",
"= adj self.D_S = adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention",
"步 out 3. 设计 Temporal-Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12",
"STTransformer( A, in_channels, embed_size, time_num, num_layers, T_dim, output_T_dim, heads, cheb_K,",
"d_k] Q = self.W_Q(input_Q).view(B, N, T, self.heads, self.head_dim).transpose(1, 3) #",
"# D_T = self.one_hot(t, N, T) # temporal embedding选用one-hot方式 或者",
"# Dimension of hidden embedding features time_num = 288 num_layers",
"+ T > self.time_num: o1 = self.I[i % self.time_num:, :]",
"T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion",
"onehot = self.onehot_Linear(onehot) return onehot ''' Attention 基础代码 ScaledDotProductAttention 是通用的",
"self.dropout = nn.Dropout(dropout) def forward(self, value, key, query, t): #",
"% self.time_num, :] onehot = torch.cat((o1, o2), 0) else: onehot",
"C:通道数量。 N:传感器数量。 T:时间数量 # x = x.unsqueeze(0) # x =",
"time_num, num_layers, T_dim, output_T_dim, heads, cheb_K, forward_expansion, dropout=0 ): super(STTransformer,",
"== '__main__': main() ''' 布置作业: 1. 设计 only Spatial Transformer",
"self.norm2 = nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion * embed_size),",
"and finally dropout x = self.dropout(self.norm1(attention + query)) forward =",
"T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), d_k] K: [batch_size, n_heads,",
"__init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads =",
"self.embed_liner(self.D_S) # [N, C] # D_S = D_S.expand(T, N, C)",
"embed_size, num_layers, heads, time_num, forward_expansion, cheb_K, dropout=0 ) # 缩小时间维度。",
"True. attn = nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V) # [batch_size,",
"就代表是temporal attention K = self.W_K(input_K).view(B, N, T, self.heads, self.head_dim).permute(0, 3,",
"self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) out = self.dropout(self.norm2(forward +",
"for name, param in model.named_parameters(): if param.requires_grad: param_count += param.numel()",
"__init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads =",
"return output ''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module):",
"nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2",
"dropout x = self.dropout(self.norm1(attention + query)) forward = self.feed_forward(x) out",
"T(Temporal), d_k] K: [batch_size, n_heads, T(Spatial) or N(Temporal), N(Spatial) or",
"onehot ''' Attention 基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C --->",
"Embedding 部分 # N, T, C = query.shape # D_S",
"t): ## scr: [N, T, C] [B, N, T, C]",
"def __init__( self, embed_size, num_layers, heads, adj, time_num, device, forward_expansion,",
"nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), )",
"代表多头注意力机制 ''' class TMultiHeadAttention(nn.Module): def __init__(self, embed_size, heads): super(TMultiHeadAttention, self).__init__()",
"shape[N, T, C] [B, N, T, C] output_Transformer = self.Transformer(input_Transformer,",
"output_dim] # return out shape: [N, output_dim] def print_params(model_name, model):",
"embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size), ) self.dropout = nn.Dropout(dropout)",
"N, output_T_dim] out = self.conv3(out) # 等号左边 out shape: [B,",
"0 A = pd.read_csv(ADJPATH).values A = torch.Tensor(A) ### Construct Network",
"C] [B, N, T, C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) #",
"的版本,跑出PEMSBAY的结果 12 步in 12 步 out 3. 设计 Temporal-Spatial Transformer",
"self.head_dim * self.heads, bias=False) self.W_K = nn.Linear(self.embed_size, self.head_dim * self.heads,",
"2, 1, 3) # [B, N, T, C] # Spatial",
"第一维复制B份 D_S = D_S.permute(0, 2, 1, 3) # [B, N,",
"d_k = Q.shape scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k)",
"and finally dropout x1 = self.norm1(self.STransformer(value, key, query) + query)",
"enc_src # [B, N, T, C] ### ST Transformer: Total",
"input_Transformer.squeeze(0) # input_Transformer = input_Transformer.permute(1, 2, 0) input_Transformer = input_Transformer.permute(0,",
"T, C] enc_src = self.encoder(src, t) return enc_src # [B,",
"= output_Transformer.permute(0, 2, 1, 3) # output_Transformer shape[B, T, N,",
"only Spatial Transformer 的版本,跑出PEMSBAY的结果 12 步in 12 步 out 2.",
"[B, h, N, T, d_k] V = self.W_V(input_V).view(B, N, T,",
"GCN_models import GCN # from One_hot_encoder import One_hot_encoder import torch.nn.functional",
"from scipy.sparse.linalg import eigs from Param import * from torchsummary",
"= One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式 或者 self.temporal_embedding = nn.Embedding(time_num,",
"GPU = sys.argv[-1] if len(sys.argv) == 2 else '1' device",
"self.dropout = nn.Dropout(dropout) self.fs = nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size,",
"print_params('STTransformer', model) if __name__ == '__main__': main() ''' 布置作业: 1.",
"C) x2 = self.dropout(self.norm2(self.TTransformer(x1, x1, x1, t) + x1)) return",
"# [B, N, T, C] # context = context.transpose(1, 2).reshape(batch_size,",
"in_channels = 2 # Channels of input embed_size = 32",
"self.D_S = adj.to(DEVICE) self.embed_liner = nn.Linear(adj.shape[0], embed_size) self.attention = SMultiHeadAttention(embed_size,",
"query.shape D_S = self.embed_liner(self.D_S) # [N, C] ---position encoding D_S",
"T, C] [B, N, T, C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion)",
"= nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim",
"= 2 # Order for Chebyshev Polynomials (Eq 2) forward_expansion",
"cheb_K = 2 # Order for Chebyshev Polynomials (Eq 2)",
"self.relu(self.conv2(output_Transformer)) # 等号左边 out shape: [1, output_T_dim, N, C] out",
"N, T, C] input_V: [batch_size, N, T, C] attn_mask: [batch_size,",
"i, N=25, T=12): if i % self.time_num + T >",
"embeded size = 512 ''' class ScaledDotProductAttention(nn.Module): def __init__(self): super(ScaledDotProductAttention,",
"[batch_size, n_heads, seq_len, seq_len] 可能没有 ''' B, n_heads, len1, len2,",
"3, 1, 2, 4) # Q: [B, h, N, T,",
"return out ### Transformer class Transformer(nn.Module): def __init__( self, adj,",
"= 2 # Number of ST Block T_dim = 12",
"finally dropout x1 = self.norm1(self.STransformer(value, key, query) + query) #",
"def __init__(self, embed_size, heads): super(SMultiHeadAttention, self).__init__() self.embed_size = embed_size self.heads",
"C] 相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0, 2, 1, 3) #",
"3) # [B, N, T, C] # Spatial Transformer 部分",
"if param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count} trainable parameters in",
"N, T, C = query.shape D_S = self.embed_liner(self.D_S) # [N,",
"N(Temporal), N(Spatial) or T(Temporal), d_k] V: [batch_size, n_heads, T(Spatial) or",
"self.time_num + T, :] # onehot = onehot.repeat(N, 1, 1)",
"N, T, C] input_K: [batch_size, N, T, C] input_V: [batch_size,",
"time_num # self.one_hot = One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式 或者",
"nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size, self.head_dim *",
"dropout x1 = self.norm1(self.STransformer(value, key, query) + query) # (B,",
"= self.one_hot(t, N, T) # temporal embedding选用one-hot方式 或者 D_T =",
"device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\") in_channels = 2",
"output_Transformer.permute(0, 2, 1, 3) # output_Transformer shape[B, T, N, C]",
"# [B, N, T, C] # Spatial Transformer 部分 query",
",all embeded size = 512 ''' class ScaledDotProductAttention(nn.Module): def __init__(self):",
"self.one_hot(t, N, T) # temporal embedding选用one-hot方式 或者 D_T = self.temporal_embedding(torch.arange(0,",
"= 0 for name, param in model.named_parameters(): if param.requires_grad: param_count",
"[batch_size, N, T, C] input_V: [batch_size, N, T, C] attn_mask:",
"+= param.numel() print(f'{model_name}, {param_count} trainable parameters in total.') return import",
"T > self.time_num: o1 = self.I[i % self.time_num:, :] o2",
"temporal embedding选用nn.Embedding self.attention = TMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2",
"D_T = self.temporal_embedding(torch.arange(0, T).to(DEVICE)) # temporal embedding选用nn.Embedding D_T = D_T.expand(B,",
"[B, N, output_dim] # return out shape: [N, output_dim] def",
"self.STransformer = STransformer(embed_size, heads, adj, cheb_K, dropout, forward_expansion) self.TTransformer =",
"d_v) # context: [batch_size, len_q, n_heads * d_v] output =",
"''' B, N, T, C = input_Q.shape # [B, N,",
"nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.dropout = nn.Dropout(dropout) def forward(self, value,",
"cheb_K, forward_expansion, dropout).to(DEVICE) summary(model, (2, N_NODE, TIMESTEP_IN), device=device) print_params('STTransformer', model)",
"n_heads, seq_len, seq_len] # context: [batch_size, n_heads, len_q, d_v], attn:",
"N, T, d_k] V = self.W_V(input_V).view(B, N, T, self.heads, self.head_dim).permute(0,",
"output_Transformer = output_Transformer.permute(0, 2, 1, 3) # output_Transformer shape[B, T,",
"C] enc_src = self.encoder(src, t) return enc_src # [B, N,",
"= Encoder( embed_size, num_layers, heads, adj, time_num, device, forward_expansion, cheb_K,",
"context = ScaledDotProductAttention()(Q, K, V) # [B, h, T, N,",
"print('out: ',out.shape) return out # [B, N, output_dim] # return",
"C) class TTransformer(nn.Module): def __init__(self, embed_size, heads, time_num, dropout, forward_expansion):",
"[B, N, T, C] --[B, N, T, self.heads, self.head_dim] ->",
"# Input length, should be the same as prepareData.py output_T_dim",
"C = query.shape # D_S = self.embed_liner(self.D_S) # [N, C]",
"(1 - g) # (8) return out # (B, N,",
"num_layers, heads, time_num, forward_expansion, cheb_K, dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维",
"context.reshape(B, N, T, self.heads * self.head_dim) # [B, N, T,",
"print(f'{model_name}, {param_count} trainable parameters in total.') return import sys import",
"n_heads, T(Spatial) or N(Temporal), N(Spatial) or T(Temporal), N(Spatial) or T(Temporal)]",
"nn.LayerNorm(embed_size) self.norm2 = nn.LayerNorm(embed_size) self.feed_forward = nn.Sequential( nn.Linear(embed_size, forward_expansion *",
"be divisible by heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V =",
"h, T, N, d_k] V = self.W_V(input_V).view(B, N, T, self.heads,",
"C] --> [B, N, T, h * d_k] --> [B,",
"T, C) class TTransformer(nn.Module): def __init__(self, embed_size, heads, time_num, dropout,",
"= nn.Linear(embed_size, embed_size) def forward(self, value, key, query): # value,",
"* embed_size, embed_size), ) # 调用GCN self.norm_adj = nn.InstanceNorm2d(1) #",
"attn = nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V) # [batch_size, n_heads,",
"第一次卷积扩充通道数 self.conv1 = nn.Conv2d(in_channels, embed_size, 1) # Channel = 1",
"(CHANNEL, TIMESTEP_IN, N_NODE) # input x shape[ C, N, T]",
"N, T, d_k] context = context.permute(0, 2, 3, 1, 4)",
"cheb_K, dropout=0 ) # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out",
"',out.shape) return out # [B, N, output_dim] # return out",
"C] [B, N, T, C] out = self.dropout(x) # In",
"T, C] ### ST Transformer: Total Model class STTransformer(nn.Module): def",
"// heads assert ( self.head_dim * heads == embed_size ),",
"= pd.read_csv(ADJPATH).values A = torch.Tensor(A) ### Construct Network model =",
"U_S + (1 - g) # (8) return out #",
"num_layers, heads, time_num, forward_expansion, ##? cheb_K, dropout, device=DEVICE ): super(Transformer,",
"nn.Linear(embed_size, embed_size) self.fg = nn.Linear(embed_size, embed_size) def forward(self, value, key,",
"Fills elements of self tensor with value where mask is",
"[batch_size, N, T, C] attn_mask: [batch_size, seq_len, seq_len] ''' B,",
"# Order for Chebyshev Polynomials (Eq 2) forward_expansion = 32",
"# platform: (CHANNEL, TIMESTEP_IN, N_NODE) # input x shape[ C,",
"''' B, n_heads, len1, len2, d_k = Q.shape scores =",
"Spatial Transformer 部分 query = query + D_S attention =",
"N, d_k] context = context.permute(0, 3, 2, 1, 4) #",
"summary DEVICE = 'cuda:1' class One_hot_encoder(nn.Module): def __init__(self, embed_size, time_num=288):",
"T, self.heads, self.head_dim).transpose(1, 3) # V: [B, h, T, N,",
"D_S.expand(T, N, C) #[T, N, C]相当于在第一维复制了T份 # D_S = D_S.permute(1,",
"mask is True. attn = nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V)",
"# 调用GCN self.norm_adj = nn.InstanceNorm2d(1) # 对邻接矩阵归一化 self.dropout = nn.Dropout(dropout)",
"nn.Conv2d(embed_size, in_channels, 1) self.relu = nn.ReLU() # 和归一化搭配好,防止梯度爆炸,消失。 def forward(self,",
"attn_mask: [batch_size, n_heads, seq_len, seq_len] 可能没有 ''' B, n_heads, len1,",
"# x: [N, T, C] [B, N, T, C] out",
"= STransformer(embed_size, heads, adj, cheb_K, dropout, forward_expansion) self.TTransformer = TTransformer(embed_size,",
"embed_size self.heads = heads self.head_dim = embed_size // heads assert",
"STTransformerBlock( embed_size, heads, adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for",
"self.head_dim = embed_size // heads assert ( self.head_dim * heads",
"o2), 0) else: onehot = self.I[i % self.time_num: i %",
"= self.Transformer(input_Transformer, self.forward_expansion) # [B, N, T, C] output_Transformer =",
"same as prepareData.py output_T_dim = 12 # Output Expected length",
"n_heads, seq_len, seq_len] seq_len = N # context: [batch_size, n_heads,",
"C]相当于在第一维复制了T份 # D_S = D_S.permute(1, 0, 2) #[N, T, C]",
"# 缩小通道数,降到1维。 self.conv3 = nn.Conv2d(embed_size, in_channels, 1) self.relu = nn.ReLU()",
"self.heads, self.head_dim).transpose(1, 3) # K: [B, h, T, N, d_k]",
"# x = x.unsqueeze(0) # x = np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer =",
"# Add skip connection,run through normalization and finally dropout x1",
"N, T, C] # Spatial Transformer 部分 query = query",
"# V: [B, h, N, T, d_k] # attn_mask =",
"= np.transpose(x,(0,2,1)).to(DEVICE) input_Transformer = self.conv1(x) # conv 要求第二维度是C, 也就是必须得B C",
"-> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K = self.W_K(input_K).view(B, N, T,",
"input_Q, input_K, input_V): ''' input_Q: [batch_size, N, T, C] input_K:",
"12 # Output Expected length heads = 4 # Number",
"等号左边 out shape: [1, output_T_dim, N, C] out = out.permute(0,",
"d_k] --> [B, N, T, h, d_k] --> [B, h,",
"用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False)",
"# MODEL CODE # -*- coding: utf-8 -*- \"\"\" Created",
"_ in range(num_layers) ] ) self.dropout = nn.Dropout(dropout) def forward(self,",
"embed_size * forward_expansion --> embed_size dropout = 0 A =",
"self).__init__() self.embed_size = embed_size self.device = device self.layers = nn.ModuleList(",
"= self.encoder(src, t) return enc_src # [B, N, T, C]",
"# Number of ST Block T_dim = 12 # Input",
"= out.squeeze(1) out = out.permute(0, 1, 3, 2) # print('out:",
"3, 2, 1) # 等号左边 out shape: [B, C, N,",
"N, C] 相当于在第2维复制了T份, 第一维复制B份 D_S = D_S.permute(0, 2, 1, 3)",
"[N, T, C] [B, N, T, C] enc_src = self.encoder(src,",
"is True. attn = nn.Softmax(dim=-1)(scores) context = torch.matmul(attn, V) #",
"# Q: [B, h, N, T, d_k] T,dk 就代表是temporal attention",
"2) forward_expansion = 32 # Dimension of Feed Forward Network:",
"T, C] --[B, N, T, self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention",
"Q: [B, h, N, T, d_k] T,dk 就代表是temporal attention K",
"# 堆叠多层 ST-Transformer Block def __init__( self, embed_size, num_layers, heads,",
"utf-8 -*- \"\"\" Created on Mon Sep 28 10:28:06 2020",
"= self.dropout(x) # In the Encoder the query, key, value",
"也就是必须得B C + 其他 # input_Transformer = input_Transformer.squeeze(0) # input_Transformer",
"2, 1, 3) # output_Transformer shape[B, T, N, C] #",
"heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim *",
"( self.head_dim * heads == embed_size ), \"Embedding size needs",
"or T(Temporal), d_k] attn_mask: [batch_size, n_heads, seq_len, seq_len] 可能没有 '''",
"N, T, self.heads, self.head_dim).transpose(1, 3) # K: [B, h, T,",
"N # context: [batch_size, n_heads, len_q, d_v], attn: [batch_size, n_heads,",
"# [B, N, T, C] ### ST Transformer: Total Model",
"self.I[0: (i + T) % self.time_num, :] onehot = torch.cat((o1,",
"len_q, d_model] return output ''' T 代表Temporal ,MultiHeadAttention 代表多头注意力机制 '''",
"N, T, self.heads * self.head_dim) # [B, N, T, C]",
"g * U_S + (1 - g) # (8) return",
"h * d_k] --> [B, N, T, h, d_k] -->",
"= self.conv3(out) # 等号左边 out shape: [B, 1, N, output_T_dim]",
"value, key, query): # value, key, query: [N, T, C]",
"= layer(out, out, out, t) return out ### Transformer class",
"assert ( self.head_dim * heads == embed_size ), \"Embedding size",
"C] # context = context.transpose(1, 2).reshape(batch_size, -1, n_heads * d_v)",
"= 8 ,all embeded size = 512 ''' class ScaledDotProductAttention(nn.Module):",
"T, C] out = self.dropout(x) # In the Encoder the",
"C] ### ST Transformer: Total Model class STTransformer(nn.Module): def __init__(",
"self.W_K = nn.Linear(self.embed_size, self.head_dim * self.heads, bias=False) self.W_Q = nn.Linear(self.embed_size,",
"forward_expansion, ##? cheb_K, dropout, device=DEVICE ): super(Transformer, self).__init__() self.encoder =",
"= nn.Linear(heads * self.head_dim, embed_size) def forward(self, input_Q, input_K, input_V):",
"3) # V: [B, h, T, N, d_k] # attn_mask",
"B,N,T,C=2, 然后跑出1,2,3 升级版结果。 12 步in 12 步 out PEMSBAY 数据集",
"[batch_size, n_heads, seq_len, seq_len] # context: [batch_size, n_heads, len_q, d_v],",
"T, C] output_Transformer = self.Transformer(input_Transformer, self.forward_expansion) # [B, N, T,",
") # 缩小时间维度。 例:T_dim=12到output_T_dim=3,输入12维降到输出3维 or 12in 12 out self.conv2 =",
"Expected length heads = 4 # Number of Heads in",
"# self.one_hot = One_hot_encoder(embed_size, time_num) # temporal embedding选用one-hot方式 或者 self.temporal_embedding",
"== 2 else '1' device = torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else",
"MultiHeadAttention cheb_K = 2 # Order for Chebyshev Polynomials (Eq",
"1) # attn_mask : [batch_size, n_heads, seq_len, seq_len] seq_len =",
"self.device = device def forward(self, src, t): ## scr: [N,",
"= Transformer( adj, embed_size, num_layers, heads, time_num, forward_expansion, cheb_K, dropout=0",
"forward_expansion = 32 # Dimension of Feed Forward Network: embed_size",
"d_k] context = context.reshape(B, N, T, self.heads * self.head_dim) #",
"self.heads, self.head_dim] -> [B,h,T,N,dk] 然后是为了把N,dk这两维度考虑去做ScaledDotProductAttention ,代表着是spatial attention K = self.W_K(input_K).view(B,",
"__init__(self, embed_size, heads, time_num, dropout, forward_expansion): super(TTransformer, self).__init__() # Temporal",
"cheb_K, dropout ) self.device = device def forward(self, src, t):",
"self.time_num:, :] o2 = self.I[0: (i + T) % self.time_num,",
"value, key, query, t): B, N, T, C = query.shape",
"= forward_expansion # feed forward 的 embeded size 8,16,32....1024 #",
"# out = out.squeeze(1) out = out.permute(0, 1, 3, 2)",
"Mon Sep 28 10:28:06 2020 @author: wb \"\"\" import torch",
"size 32 or 64 加入dk = 32, 那么一个头就是32,然后加上多头注意力机制的话,比如8个head,8个头,那就是32*8=256,如果要跟NIPS17 tranformer论文完全对应上,那么dk=64,head =",
"features time_num = 288 num_layers = 2 # Number of",
"2 # Channels of input embed_size = 32 # Dimension",
"* d_k] --> [B, N, T, h, d_k] --> [B,",
"= torch.device(\"cuda:{}\".format(GPU)) if torch.cuda.is_available() else torch.device(\"cpu\") in_channels = 2 #",
"param_count = 0 for name, param in model.named_parameters(): if param.requires_grad:",
"shape: [N, output_dim] def print_params(model_name, model): param_count = 0 for",
"embed_size) self.attention = SMultiHeadAttention(embed_size, heads) self.norm1 = nn.LayerNorm(embed_size) self.norm2 =",
"return output class STransformer(nn.Module): def __init__(self, embed_size, heads, adj, cheb_K,",
"heads, adj, time_num, cheb_K, dropout=dropout, forward_expansion=forward_expansion ) for _ in",
"% self.time_num + T > self.time_num: o1 = self.I[i %",
"Sep 28 10:28:06 2020 @author: wb \"\"\" import torch import",
"K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size, n_heads, T(Spatial)",
"output_T_dim] out = self.conv3(out) # 等号左边 out shape: [B, 1,",
"cheb_K, forward_expansion, dropout=0 ): super(STTransformer, self).__init__() self.forward_expansion = forward_expansion #",
"embedding features time_num = 288 num_layers = 2 # Number",
"out = out.permute(0, 1, 3, 2) # print('out: ',out.shape) return",
"= self.attention(query, query, query) # Add skip connection, run through",
"N, T, C) # Add skip connection, run through normalization",
"or N(Temporal), N(Spatial) or T(Temporal), d_k] V: [batch_size, n_heads, T(Spatial)",
"x)) return out ### STBlock class STTransformerBlock(nn.Module): def __init__(self, embed_size,",
"query, t): # value, key, query: [N, T, C] [B,",
"cheb_K, dropout, forward_expansion): super(STransformer, self).__init__() # Spatial Embedding self.adj =",
"基础代码 ScaledDotProductAttention 是通用的 解释dk: 数据进来的时候是B,N,T,C,做attention的时候,C=1 ,不能很好的表征数据高维空间的特征,C ---> embedded size 32",
"by heads\" # 用Linear来做投影矩阵 # 但这里如果是多头的话,是不是需要声明多个矩阵??? self.W_V = nn.Linear(self.embed_size, self.head_dim",
"One_hot_encoder import torch.nn.functional as F import numpy as np from"
] |
[
"[0, 0, 0, 0, 2, 2, 2, 0, 0, 0],",
"end=\" \", flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"), end=\"",
"lst.add(row) if (i == 20 or i > row) and",
"range(21): for z in range(10): for row in range(len(matrix)): if",
"0, 1, 0, 0, 0, 0, 1, 0, 1], [1,",
"takes a screenshot pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command', 'shift',",
"import time import imageio import pyautogui pyautogui.FAILSAFE = True matrix",
"1, 1, 1, 1, 1, 1, 0], [1, 0, 1,",
"0], [0, 0, 0, 0, 0, 2, 0, 0, 0,",
"pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000,",
"matrix = [[0, 0, 0, 0, 0, 0, 0, 0,",
"range(len(matrix[row])): if i == row and z == element: print(colored(matrix[row][element],",
"imageio import pyautogui pyautogui.FAILSAFE = True matrix = [[0, 0,",
"0, 1, 0, 0, 1, 1], [1, 1, 1, 1,",
"0, 0, 0, 0], [0, 0, 0, 0, 0, 0,",
"0, 0, 0, 0, 0, 0], [0, 0, 0, 0,",
"0, 0, 0, 0, 0], [1, 0, 1, 1, 1,",
"pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration = 0, button =",
"flush=False) print(\"\") print(\"\") # takes a screenshot pyautogui.moveTo(338, 580, duration",
"0, 1, 0, 1], [1, 1, 1, 1, 1, 1,",
"row and z == element: print(colored(matrix[row][element], \"green\"), end=\" \", flush=False)",
"1], [1, 1, 1, 1, 1, 1, 1, 1, 1,",
"0 not in matrix[row]: lst.add(row) if (i == 20 or",
"\", flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"), end=\" \",",
"animation for medium article from termcolor import colored import time",
"0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration = 0, button",
"0, 0, 0, 0, 0, 0, 0, 0, 0], [0,",
"element in range(len(matrix[row])): if i == row and z ==",
"matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"), end=\" \", flush=False) elif matrix[row][element]",
"and z == element: print(colored(matrix[row][element], \"green\"), end=\" \", flush=False) elif",
"a screenshot pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command', 'shift', '4')",
"1, 0, 0, 1, 1], [1, 1, 1, 1, 1,",
"True matrix = [[0, 0, 0, 0, 0, 0, 0,",
"0, 0, 0, 0, 0, 0], [1, 0, 1, 1,",
"matrix[row]: lst.add(row) if (i == 20 or i > row)",
"import imageio import pyautogui pyautogui.FAILSAFE = True matrix = [[0,",
"i == row and z == element: print(colored(matrix[row][element], \"green\"), end=\"",
"\"red\"), end=\" \", flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"),",
"[1, 0, 1, 0, 0, 0, 0, 1, 0, 1],",
"0, 0, 0, 2, 2, 2, 0, 0, 0], [0,",
"row in lst: print(colored(\"1 \" * 10, \"green\")) else: for",
"\"green\"), end=\" \", flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"),",
"\", flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"), end=\" \",",
"0, 0, 0, 0, 1, 0, 1], [1, 1, 1,",
"1, 1, 1], [0, 1, 0, 1, 0, 1, 0,",
"if 0 not in matrix[row]: lst.add(row) if (i == 20",
"not in matrix[row]: lst.add(row) if (i == 20 or i",
"0], [1, 0, 1, 0, 0, 0, 0, 1, 0,",
"0, 0, 0, 0], [0, 0, 0, 0, 2, 2,",
"print(colored(\"1 \" * 10, \"green\")) else: for element in range(len(matrix[row])):",
"2, 0, 0, 0], [0, 0, 0, 0, 0, 2,",
"in range(21): for z in range(10): for row in range(len(matrix)):",
"time import imageio import pyautogui pyautogui.FAILSAFE = True matrix =",
"0, 0, 2, 2, 2, 0, 0, 0], [0, 0,",
"2, 2, 0, 0, 0], [0, 0, 0, 0, 0,",
"1, 1, 1, 1], [0, 1, 0, 1, 0, 1,",
"or i > row) and row in lst: print(colored(\"1 \"",
"0, 0], [1, 0, 1, 1, 1, 1, 1, 1,",
"print(colored(matrix[row][element], \"red\"), end=\" \", flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element],",
"from termcolor import colored import time import imageio import pyautogui",
"1, 1, 1, 1, 1, 1, 1], [0, 1, 0,",
"[0, 1, 0, 1, 0, 1, 0, 0, 1, 1],",
"1, 1, 1, 0], [1, 0, 1, 0, 0, 0,",
"if i == row and z == element: print(colored(matrix[row][element], \"green\"),",
"0, 0, 0], [0, 0, 0, 0, 0, 2, 0,",
"1, 1, 1, 1, 0], [1, 0, 1, 0, 0,",
"1, 0, 1, 0, 1, 0, 0, 1, 1], [1,",
"1, 1, 1, 1, 1, 1, 1, 1], [0, 1,",
"row) and row in lst: print(colored(\"1 \" * 10, \"green\"))",
"1, 0, 1, 0, 0, 1, 1], [1, 1, 1,",
"'shift', '4') pyautogui.dragTo(547, 1000, duration = 0, button = 'left')",
"10, \"green\")) else: for element in range(len(matrix[row])): if i ==",
"print(colored(matrix[row][element], \"green\"), end=\" \", flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element],",
"else: for element in range(len(matrix[row])): if i == row and",
"in lst: print(colored(\"1 \" * 10, \"green\")) else: for element",
"1, 1, 1, 1, 1]] lst = set() for i",
"1, 1, 1, 1, 1, 1, 1, 1, 1]] lst",
"and row in lst: print(colored(\"1 \" * 10, \"green\")) else:",
"1, 1, 1, 1, 1, 1], [0, 1, 0, 1,",
"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],",
"1, 0, 1], [1, 1, 1, 1, 1, 1, 1,",
"1, 1, 1, 1, 1, 1, 1, 1, 1], [0,",
"end=\" \", flush=False) print(\"\") print(\"\") # takes a screenshot pyautogui.moveTo(338,",
"1, 1, 1]] lst = set() for i in range(21):",
"[1, 0, 1, 1, 1, 1, 1, 1, 1, 0],",
"termcolor import colored import time import imageio import pyautogui pyautogui.FAILSAFE",
"1, 1]] lst = set() for i in range(21): for",
"\", flush=False) print(\"\") print(\"\") # takes a screenshot pyautogui.moveTo(338, 580,",
"[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],",
"for z in range(10): for row in range(len(matrix)): if 0",
"\"blue\"), end=\" \", flush=False) else: print(matrix[row][element], end=\" \", flush=False) print(\"\")",
"0, 2, 0, 0, 0, 0], [0, 0, 0, 0,",
"medium article from termcolor import colored import time import imageio",
"\"green\")) else: for element in range(len(matrix[row])): if i == row",
"i > row) and row in lst: print(colored(\"1 \" *",
"0, 0, 0, 1, 0, 1], [1, 1, 1, 1,",
"print(\"\") print(\"\") # takes a screenshot pyautogui.moveTo(338, 580, duration =",
"for element in range(len(matrix[row])): if i == row and z",
"0, 1, 1, 1, 1, 1, 1, 1, 0], [1,",
"z == element: print(colored(matrix[row][element], \"green\"), end=\" \", flush=False) elif matrix[row][element]",
"= set() for i in range(21): for z in range(10):",
"i in range(21): for z in range(10): for row in",
"# animation for medium article from termcolor import colored import",
"range(len(matrix)): if 0 not in matrix[row]: lst.add(row) if (i ==",
"0, 0, 1, 1], [1, 1, 1, 1, 1, 1,",
"lst: print(colored(\"1 \" * 10, \"green\")) else: for element in",
"0, 0], [0, 0, 0, 0, 0, 2, 0, 0,",
"in range(len(matrix)): if 0 not in matrix[row]: lst.add(row) if (i",
"0, 0, 0, 0, 0, 0, 0, 0, 0], [1,",
"elif matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False) else:",
"0, 0, 0, 0, 0, 0, 0, 0], [1, 0,",
"0, 0, 0, 0], [1, 0, 1, 1, 1, 1,",
"print(\"\") # takes a screenshot pyautogui.moveTo(338, 580, duration = 0)",
"pyautogui pyautogui.FAILSAFE = True matrix = [[0, 0, 0, 0,",
"* 10, \"green\")) else: for element in range(len(matrix[row])): if i",
"(i == 20 or i > row) and row in",
"import colored import time import imageio import pyautogui pyautogui.FAILSAFE =",
"article from termcolor import colored import time import imageio import",
"row in range(len(matrix)): if 0 not in matrix[row]: lst.add(row) if",
"580, duration = 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration",
"z in range(10): for row in range(len(matrix)): if 0 not",
"== element: print(colored(matrix[row][element], \"green\"), end=\" \", flush=False) elif matrix[row][element] ==",
"matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False) else: print(matrix[row][element],",
"range(10): for row in range(len(matrix)): if 0 not in matrix[row]:",
"> row) and row in lst: print(colored(\"1 \" * 10,",
"0, 0, 0, 0, 0, 0, 0, 0], [0, 0,",
"== 2: print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False) else: print(matrix[row][element], end=\"",
"in matrix[row]: lst.add(row) if (i == 20 or i >",
"in range(len(matrix[row])): if i == row and z == element:",
"0, 0, 0, 0, 0], [0, 0, 0, 0, 0,",
"0], [0, 0, 0, 0, 2, 2, 2, 0, 0,",
"in range(10): for row in range(len(matrix)): if 0 not in",
"<reponame>daniel-chuang/tetris # animation for medium article from termcolor import colored",
"0], [1, 0, 1, 1, 1, 1, 1, 1, 1,",
"1, 1, 0], [1, 0, 1, 0, 0, 0, 0,",
"1], [0, 1, 0, 1, 0, 1, 0, 0, 1,",
"2, 2, 2, 0, 0, 0], [0, 0, 0, 0,",
"1, 1], [0, 1, 0, 1, 0, 1, 0, 0,",
"0, 0, 2, 0, 0, 0, 0], [0, 0, 0,",
"flush=False) else: print(matrix[row][element], end=\" \", flush=False) print(\"\") print(\"\") # takes",
"for medium article from termcolor import colored import time import",
"0, 0, 1, 0, 1], [1, 1, 1, 1, 1,",
"1, 1], [1, 1, 1, 1, 1, 1, 1, 1,",
"0, 0, 0], [0, 0, 0, 0, 0, 0, 0,",
"0, 1, 0, 1, 0, 0, 1, 1], [1, 1,",
"0, 0, 0], [0, 0, 0, 0, 2, 2, 2,",
"= [[0, 0, 0, 0, 0, 0, 0, 0, 0,",
"1: print(colored(matrix[row][element], \"red\"), end=\" \", flush=False) elif matrix[row][element] == 2:",
"if (i == 20 or i > row) and row",
"2, 0, 0, 0, 0], [0, 0, 0, 0, 0,",
"0], [0, 0, 0, 0, 0, 0, 0, 0, 0,",
"1]] lst = set() for i in range(21): for z",
"0, 0, 0], [1, 0, 1, 1, 1, 1, 1,",
"== 1: print(colored(matrix[row][element], \"red\"), end=\" \", flush=False) elif matrix[row][element] ==",
"else: print(matrix[row][element], end=\" \", flush=False) print(\"\") print(\"\") # takes a",
"[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],",
"element: print(colored(matrix[row][element], \"green\"), end=\" \", flush=False) elif matrix[row][element] == 1:",
"end=\" \", flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"), end=\"",
"0, 2, 2, 2, 0, 0, 0], [0, 0, 0,",
"print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False) else: print(matrix[row][element], end=\" \", flush=False)",
"end=\" \", flush=False) else: print(matrix[row][element], end=\" \", flush=False) print(\"\") print(\"\")",
"0, 0, 0, 0, 0, 0, 0], [0, 0, 0,",
"0, 0], [0, 0, 0, 0, 0, 0, 0, 0,",
"# takes a screenshot pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command',",
"[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]",
"flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"), end=\" \", flush=False)",
"elif matrix[row][element] == 1: print(colored(matrix[row][element], \"red\"), end=\" \", flush=False) elif",
"1, 1, 1, 1, 1], [0, 1, 0, 1, 0,",
"0, 1, 1], [1, 1, 1, 1, 1, 1, 1,",
"= 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration = 0,",
"0, 0], [0, 0, 0, 0, 2, 2, 2, 0,",
"2: print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False) else: print(matrix[row][element], end=\" \",",
"\", flush=False) else: print(matrix[row][element], end=\" \", flush=False) print(\"\") print(\"\") #",
"0, 1], [1, 1, 1, 1, 1, 1, 1, 1,",
"duration = 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration =",
"1, 1, 1, 1, 1, 1]] lst = set() for",
"== row and z == element: print(colored(matrix[row][element], \"green\"), end=\" \",",
"1, 1, 1, 1, 1, 0], [1, 0, 1, 0,",
"flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element], \"blue\"), end=\" \", flush=False)",
"20 or i > row) and row in lst: print(colored(\"1",
"pyautogui.FAILSAFE = True matrix = [[0, 0, 0, 0, 0,",
"1, 1, 1, 1]] lst = set() for i in",
"[0, 0, 0, 0, 0, 2, 0, 0, 0, 0],",
"0, 0, 0, 2, 0, 0, 0, 0], [0, 0,",
"0, 0, 0, 0, 2, 0, 0, 0, 0], [0,",
"1, 1, 1, 1, 1, 1, 1, 1]] lst =",
"1, 0, 0, 0, 0, 1, 0, 1], [1, 1,",
"== 20 or i > row) and row in lst:",
"1, 0], [1, 0, 1, 0, 0, 0, 0, 1,",
"\" * 10, \"green\")) else: for element in range(len(matrix[row])): if",
"for row in range(len(matrix)): if 0 not in matrix[row]: lst.add(row)",
"import pyautogui pyautogui.FAILSAFE = True matrix = [[0, 0, 0,",
"print(matrix[row][element], end=\" \", flush=False) print(\"\") print(\"\") # takes a screenshot",
"lst = set() for i in range(21): for z in",
"0, 0, 0, 0, 0], [0, 0, 0, 0, 2,",
"set() for i in range(21): for z in range(10): for",
"screenshot pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547,",
"1, 1, 1, 1, 1, 1, 1, 0], [1, 0,",
"1, 1, 1, 1, 1, 1, 1]] lst = set()",
"for i in range(21): for z in range(10): for row",
"= True matrix = [[0, 0, 0, 0, 0, 0,",
"0, 0, 0, 0, 0, 0, 0], [1, 0, 1,",
"colored import time import imageio import pyautogui pyautogui.FAILSAFE = True"
] |
[
"models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment = models.BooleanField(default=False) def __str__(self): return",
"Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100, blank=True, null=True) supplier = models.CharField(max_length=100,",
"from products.models import Product from utils.models import Utility class Inventory(Utility):",
"import Product from utils.models import Utility class Inventory(Utility): inventory_number =",
"= models.BooleanField(default=False) def __str__(self): return self.inventory_number class InventoryItem(Utility): inventory =",
"utils.models import Utility class Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100, blank=True,",
"= models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1)",
"= models.CharField(unique=True, max_length=100, blank=True, null=True) supplier = models.CharField(max_length=100, blank=True, null=True)",
"blank=True, null=True) supplier = models.CharField(max_length=100, blank=True, null=True) user = models.ForeignKey('auth.User',",
"Utility class Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100, blank=True, null=True) supplier",
"models.CharField(unique=True, max_length=100, blank=True, null=True) supplier = models.CharField(max_length=100, blank=True, null=True) user",
"max_length=100, blank=True, null=True) supplier = models.CharField(max_length=100, blank=True, null=True) user =",
"class InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE)",
"blank=True, null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment =",
"return self.inventory_number class InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product =",
"product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return",
"inventory_number = models.CharField(unique=True, max_length=100, blank=True, null=True) supplier = models.CharField(max_length=100, blank=True,",
"django.db import models from products.models import Product from utils.models import",
"products.models import Product from utils.models import Utility class Inventory(Utility): inventory_number",
"= models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return self.product.name",
"def __str__(self): return self.inventory_number class InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE)",
"models from products.models import Product from utils.models import Utility class",
"on_delete=models.SET_NULL, blank=True, null=True) is_adjusment = models.BooleanField(default=False) def __str__(self): return self.inventory_number",
"models.BooleanField(default=False) def __str__(self): return self.inventory_number class InventoryItem(Utility): inventory = models.ForeignKey(Inventory,",
"is_adjusment = models.BooleanField(default=False) def __str__(self): return self.inventory_number class InventoryItem(Utility): inventory",
"Product from utils.models import Utility class Inventory(Utility): inventory_number = models.CharField(unique=True,",
"user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment = models.BooleanField(default=False) def",
"supplier = models.CharField(max_length=100, blank=True, null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True,",
"from utils.models import Utility class Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100,",
"null=True) supplier = models.CharField(max_length=100, blank=True, null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL,",
"= models.CharField(max_length=100, blank=True, null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True)",
"= models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment = models.BooleanField(default=False) def __str__(self):",
"models.CharField(max_length=100, blank=True, null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment",
"import Utility class Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100, blank=True, null=True)",
"inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity =",
"models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def",
"__str__(self): return self.inventory_number class InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product",
"InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity",
"on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self):",
"self.inventory_number class InventoryItem(Utility): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) product = models.ForeignKey(Product,",
"blank=True, null=True) is_adjusment = models.BooleanField(default=False) def __str__(self): return self.inventory_number class",
"import models from products.models import Product from utils.models import Utility",
"null=True) user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, blank=True, null=True) is_adjusment = models.BooleanField(default=False)",
"null=True) is_adjusment = models.BooleanField(default=False) def __str__(self): return self.inventory_number class InventoryItem(Utility):",
"from django.db import models from products.models import Product from utils.models",
"class Inventory(Utility): inventory_number = models.CharField(unique=True, max_length=100, blank=True, null=True) supplier ="
] |
[
"index_view(request): return render(request, 'index.html', {'welcome': \"Welcome to Kens Hierarchical Data",
"your views here. def index_view(request): return render(request, 'index.html', {'welcome': \"Welcome",
"from django.shortcuts import render from hierarchical_app.models import Folder # Create",
"\"Welcome to Kens Hierarchical Data and You assessment\", 'folders': Folder.objects.all()})",
"import render from hierarchical_app.models import Folder # Create your views",
"return render(request, 'index.html', {'welcome': \"Welcome to Kens Hierarchical Data and",
"render(request, 'index.html', {'welcome': \"Welcome to Kens Hierarchical Data and You",
"'index.html', {'welcome': \"Welcome to Kens Hierarchical Data and You assessment\",",
"render from hierarchical_app.models import Folder # Create your views here.",
"from hierarchical_app.models import Folder # Create your views here. def",
"{'welcome': \"Welcome to Kens Hierarchical Data and You assessment\", 'folders':",
"views here. def index_view(request): return render(request, 'index.html', {'welcome': \"Welcome to",
"import Folder # Create your views here. def index_view(request): return",
"Create your views here. def index_view(request): return render(request, 'index.html', {'welcome':",
"# Create your views here. def index_view(request): return render(request, 'index.html',",
"hierarchical_app.models import Folder # Create your views here. def index_view(request):",
"here. def index_view(request): return render(request, 'index.html', {'welcome': \"Welcome to Kens",
"Folder # Create your views here. def index_view(request): return render(request,",
"def index_view(request): return render(request, 'index.html', {'welcome': \"Welcome to Kens Hierarchical",
"django.shortcuts import render from hierarchical_app.models import Folder # Create your"
] |
[
"numpy as np from sklearn import metrics from easydict import",
"dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int,",
"is True: from torchsummary import summary if cfg.fix_ratio: h, w",
"DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header =",
"import numpy as np from sklearn import metrics from easydict",
"{'epoch': 0, 'step': 0} summary_dev = {'loss': float('inf'), 'acc': 0.0}",
"from torch.utils.data import DataLoader import torch.nn.functional as F from torch.nn",
"torch from torch.utils.data import DataLoader import torch.nn.functional as F from",
"= iter(dataloader) label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now =",
"os import argparse import logging import json import time import",
"= True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best']",
"/ target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss",
"+ '/../' dst_folder = os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du",
"len(dataloader) dataiter = iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks)",
"sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent))",
"SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset",
"os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] >",
"= subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1' % src_folder) if",
"= list(x for x in range(len(cfg.num_classes))) for step in range(steps):",
"{},' 'Auc :{},Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'],",
": {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best']))",
"sklearn import metrics from easydict import EasyDict as edict import",
"F from torch.nn import DataParallel from vit_pytorch import ViT from",
"auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev,",
"save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'],",
"model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids",
"Acc : {},Auc :{},' 'Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d",
"h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not",
"target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if",
"cfg.test_every == 0: time_now = time.time() summary_dev, predlist, true_list =",
"dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids =",
"{}, Loss : {}, Acc : {}, Auc : {},'",
"to the config file in yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH',",
"if save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best':",
"= target.to(device) output = model(image) output = [torch.unsqueeze(i, 1) for",
"0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1} if",
"model.utils import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path',",
"cut -f1' % src_folder) if rc != 0: raise Exception('Copy",
"tasks loss = 0 for t in range(num_tasks): loss_t, acc_t",
"sys import os import argparse import logging import json import",
"'#available gpu : {} < --device_ids : {}' .format(num_devices, len(device_ids)))",
"not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt',",
"args, model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now =",
"Loss : {}, Acc : {},' 'Auc :{},Best Auc :",
"get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH',",
"'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if",
": {}, Acc : {},' 'Auc :{},Best Auc : {:.3f}'",
"'/../' dst_folder = os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0",
"config file in yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path",
"for step in range(steps): image, target = next(dataiter) image =",
"in range(steps): image, target = next(dataiter) image = image.to(device) target",
"= lr summary_train, best_dict = train_epoch( summary_train, summary_dev, cfg, args,",
"info\") def get_loss(output, target, index, device, cfg): if cfg.criterion ==",
"Loss : {}, ' 'Acc : {}, Run Time :",
"list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices < len(device_ids): raise",
"sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset #",
"in cfg.num_classes: assert num_class == 1 target = target[:, index].view(-1)",
"argparse import logging import json import time import subprocess from",
"Best, Step : {}, Loss : {}, Acc : {},'",
"best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main():",
"cfg = edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg, indent=4)) if",
"+ 1, summary['step'], loss_str, acc_str, time_spent)) for t in range(num_tasks):",
"summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]),",
"t, device, cfg) # AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor",
"= [torch.unsqueeze(i, 1) for i in output.T] # different number",
"help=\"Path to the config file in yaml format\") parser.add_argument('save_path', default=None,",
"file in yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path to",
"1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{},",
"{:.3f} ''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'],",
"+= acc_t.item() summary['loss'] = loss_sum / steps summary['acc'] = acc_sum",
"is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if",
"metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda",
"map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] =",
"torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps",
"summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step'])",
"def main(): args = parser.parse_args() if args.verbose is True: print('Using",
"for i in output.T] # different number of tasks loss",
"# different number of tasks for t in range(len(cfg.num_classes)): loss_t,",
"/ steps return summary, predlist, true_list def run(args): with open(args.cfg_path)",
"'w') as f: json.dump(cfg, f, indent=1) device_ids = list(map(int, args.device_ids.split(',')))",
"acc_t.item() summary['loss'] = loss_sum / steps summary['acc'] = acc_sum /",
"= len(dataloader) dataiter = iter(dataloader) label_header = dataloader.dataset._label_header num_tasks =",
"for i in output.T] # different number of tasks for",
"shutil import copyfile import numpy as np from sklearn import",
"weight = (target.size()[0] - target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits(",
"EasyDict as edict import torch from torch.utils.data import DataLoader import",
": {}, Auc : {},' 'Mean auc: {:.3f} ''Run Time",
"np.zeros(num_tasks) for step in range(steps): image, target = next(dataiter) image",
"x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc']))",
"summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best =",
"list(x for x in range(len(cfg.num_classes))) true_list = list(x for x",
"= image.to(device) target = target.to(device) output = model(image) output =",
"'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] =",
"best_dict = train_epoch( summary_train, summary_dev, cfg, args, model, dataloader_train, dataloader_dev,",
"{}, Loss : {}, Acc : {},' 'Auc :{},Best Auc",
"== 'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc",
"acc_sum)) logging.info( '{}, Train, Epoch : {}, Step : {},",
".format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1, summary['step'], loss_str, acc_str, time_spent)) for",
"import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import",
"import os import argparse import logging import json import time",
"if target.sum() == 0: loss = torch.tensor(0., requires_grad=True).to(device) else: weight",
"predlist[t] = output_tensor true_list[t] = target_tensor else: predlist[t] = np.append(predlist[t],",
"% (src_folder, dst_folder)) if rc != 0: raise Exception('copy folder",
"% src_folder) if rc != 0: raise Exception('Copy folder error",
"' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x:",
"\"\"comma separated, e.g. '0,1' \") parser.add_argument('--pre_train', default=None, type=str, help=\"If get\"",
"summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step'])",
"= target[:, t].view(-1).cpu().detach().numpy() if step == 0: predlist[t] = output_tensor",
"summary if cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side else: h,",
"Acc : {}, Auc : {},' 'Mean auc: {:.3f} ''Run",
"'{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info(",
"summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best",
"{:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train()",
"%H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'],",
"+ '/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume: with",
"best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close()",
"optimizer = get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder",
"summary['step'], loss_str, acc_str, time_spent)) for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]),",
"cfg.batch_weight: if target.sum() == 0: loss = torch.tensor(0., requires_grad=True).to(device) else:",
"if args.verbose is True: print('Using the specified args:') print(args) run(args)",
"torchsummary import summary if cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side",
"\" \"in save_path/log.txt if set True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail",
"{}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg)",
"np from sklearn import metrics from easydict import EasyDict as",
"edict import torch from torch.utils.data import DataLoader import torch.nn.functional as",
"'loss': save_best = True if save_best: torch.save( {'epoch': summary_train['epoch'], 'step':",
"save_best = True if save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'],",
"raise Exception( '#available gpu : {} < --device_ids : {}'",
"(src_folder, dst_folder)) if rc != 0: raise Exception('copy folder error",
"= torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) num_tasks =",
".format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for",
"indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices",
"= 0 best_dict = { \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\":",
"import torch from torch.utils.data import DataLoader import torch.nn.functional as F",
"\") parser.add_argument('--pre_train', default=None, type=str, help=\"If get\" \"parameters from pretrained model\")",
"x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch : {}, Step",
"default='0,1,2,3', type=str, help=\"GPU indices \"\"comma separated, e.g. '0,1' \") parser.add_argument('--pre_train',",
"cfg.criterion == 'BCE': for num_class in cfg.num_classes: assert num_class ==",
"= 0 for t in range(num_tasks): loss_t, acc_t = get_loss(output,",
"== 'loss': save_best = True if save_best: torch.save( {'epoch': summary['epoch'],",
"args.verbose is True: print('Using the specified args:') print(args) run(args) if",
"' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step :",
"torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps",
"error : {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R %s %s'",
": {}, Acc : {},Auc :{},' 'Best Auc : {:.3f}'",
"target, t, device, cfg) loss += loss_t loss_sum[t] += loss_t.item()",
"summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best':",
"True: print('Using the specified args:') print(args) run(args) if __name__ ==",
"num_devices = torch.cuda.device_count() if num_devices < len(device_ids): raise Exception( '#available",
"loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc",
"acc_sum /= cfg.log_every loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum))",
"true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc",
"number of tasks for t in range(len(cfg.num_classes)): loss_t, acc_t =",
"= os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path, 'classification') rc, size",
"for param_group in optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict =",
"target_tensor else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor)",
"os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch':",
"device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) num_tasks",
"list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter =",
"'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >=",
"'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'],",
"loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str = '",
"auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t],",
"ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch']",
"pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str",
"'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'),",
"loss_sum / steps summary['acc'] = acc_sum / steps return summary,",
"not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg, f,",
"'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx']",
"default=8, type=int, help=\"Number of \" \"workers for each data loader\")",
"iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks)",
"if cfg.batch_weight: if target.sum() == 0: loss = torch.tensor(0., requires_grad=True).to(device)",
"indices \"\"comma separated, e.g. '0,1' \") parser.add_argument('--pre_train', default=None, type=str, help=\"If",
"= np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist = list(x for x",
"from easydict import EasyDict as edict import torch from torch.utils.data",
"np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist = list(x for x in",
"\"fused_dev_best\": 0.0, \"best_idx\": 1} if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt')",
"ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best']",
"dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0]))",
"'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start = 0 best_dict =",
"import lr_schedule # noqa from model.utils import get_optimizer # noqa",
"range(num_tasks): loss_t, acc_t = get_loss(output, target, t, device, cfg) loss",
"cfg.long_side else: h, w = cfg.height, cfg.width summary(model.to(device), (3, h,",
"= torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0] - target.sum()) /",
"def train_epoch(summary, summary_dev, cfg, args, model, dataloader, dataloader_dev, optimizer, summary_writer,",
"the config file in yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str,",
"ViT( cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8,",
"summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss']))",
"dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False)",
": {}, Loss : {}, ' 'Acc : {}, Run",
"torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) num_tasks = len(cfg.num_classes)",
"'.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch : {},",
"if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best,",
"if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg,",
"drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers,",
"ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step':",
"from torch.nn import DataParallel from vit_pytorch import ViT from tensorboardX",
"yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path to the saved",
"= cfg.height, cfg.width summary(model.to(device), (3, h, w)) model = DataParallel(model,",
"'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if",
"{},' 'Mean auc: {:.3f} ''Run Time : {:.2f} sec' .format(",
"help=\"Detail info\") def get_loss(output, target, index, device, cfg): if cfg.criterion",
"'step': 0} summary_dev = {'loss': float('inf'), 'acc': 0.0} summary_writer =",
"model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now = time.time()",
"steps = len(dataloader) dataiter = iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum",
"= DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev",
"error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train",
"{'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'],",
"if set True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\") def get_loss(output,",
"from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from",
"for t in range(num_tasks): loss_t, acc_t = get_loss(output, target, t,",
"\"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1} if args.resume: ckpt_path =",
"= list(x for x in range(len(cfg.num_classes))) true_list = list(x for",
"summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc =",
"1 if summary['step'] % cfg.log_every == 0: time_spent = time.time()",
"acc_t = get_loss(output, target, t, device, cfg) # AUC output_tensor",
"model(image) output = [torch.unsqueeze(i, 1) for i in output.T] #",
"True if save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'],",
"auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str =",
"= np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step'] % cfg.test_every ==",
"torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() == 0: loss",
"torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) label_header = dataloader.dataset._label_header",
"= test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent = time.time()",
"acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train,",
"{'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'],",
"best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start",
": {}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary, summary_dev, cfg, args,",
"h, w = cfg.long_side, cfg.long_side else: h, w = cfg.height,",
"time.time() - time_now auclist = [] for i in range(len(cfg.num_classes)):",
"get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path,",
"DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev =",
"else: weight = (target.size()[0] - target.sum()) / target.sum() loss =",
"gpu : {} < --device_ids : {}' .format(num_devices, len(device_ids))) device",
"= ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda",
"best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss': save_best = True",
"'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True,",
"w = cfg.long_side, cfg.long_side else: h, w = cfg.height, cfg.width",
"args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(','))) device",
"loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar(",
"as np from sklearn import metrics from easydict import EasyDict",
"assert num_class == 1 target = target[:, index].view(-1) pos_weight =",
"summary_dev = {'loss': float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start",
"'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx']",
":{},' 'Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str,",
"metrics from easydict import EasyDict as edict import torch from",
"F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target",
"cfg.num_classes: assert num_class == 1 target = target[:, index].view(-1) pos_weight",
"dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now = time.time() summary_dev,",
"Classifier(cfg) model = ViT( cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5,",
"summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict':",
"args.verbose is True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if",
"t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t],",
"torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'],",
"loss_t, acc_t = get_loss(output, target, t, device, cfg) # AUC",
"the saved models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number of \" \"workers",
"mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc",
"help=\"Number of \" \"workers for each data loader\") parser.add_argument('--device_ids', default='0,1,2,3',",
"[] for i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true =",
"auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x),",
"ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch in",
"'/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa from",
"predlist, true_list def run(args): with open(args.cfg_path) as f: cfg =",
"cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path, 'classification')",
"Step : {}, Loss : {}, ' 'Acc : {},",
"different number of tasks loss = 0 for t in",
"return summary, predlist, true_list def run(args): with open(args.cfg_path) as f:",
"drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step':",
"cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512,",
": {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R %s %s' %",
"time import subprocess from shutil import copyfile import numpy as",
"batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'),",
"dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step': 0} summary_dev = {'loss':",
"args = parser.parse_args() if args.verbose is True: print('Using the specified",
"torch.nn.functional as F from torch.nn import DataParallel from vit_pytorch import",
"summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks)",
"for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]),",
"mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss",
"range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target, t, device, cfg) #",
"args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict'])",
"'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args",
"best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args =",
"loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step in range(steps):",
":{},Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str,",
"acc_sum = np.zeros(num_tasks) predlist = list(x for x in range(len(cfg.num_classes)))",
"next(dataiter) image = image.to(device) target = target.to(device) output = model(image)",
"len(device_ids): raise Exception( '#available gpu : {} < --device_ids :",
"= (target.size()[0] - target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1),",
"{}, Acc : {}, Auc : {},' 'Mean auc: {:.3f}",
"time.time() summary_dev, predlist, true_list = test_epoch( summary_dev, cfg, args, model,",
"= true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1)",
"pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() ==",
"target = target.to(device) output = model(image) output = [torch.unsqueeze(i, 1)",
"loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] = loss_sum / steps summary['acc']",
"ImageDataset # noqa from model.classifier import Classifier # noqa from",
"predlist[i] y_true = true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true,",
"metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc']",
"True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] =",
"= os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train =",
"pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum() /",
"True if save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'],",
"output_tensor true_list[t] = target_tensor else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t]",
"pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label =",
"save_best = True if save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'],",
"logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume:",
"np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t]",
"h, w = cfg.height, cfg.width summary(model.to(device), (3, h, w)) model",
"'.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step : {},",
"torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best':",
"target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] = loss_sum",
"'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()},",
"summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False mean_acc =",
".format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'],",
"'{}, Best, Step : {}, Loss : {}, Acc :",
"default=0, type=int, help=\"If resume from \" \"previous run\") parser.add_argument('--logtofile', default=False,",
"%H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in",
"import DataParallel from vit_pytorch import ViT from tensorboardX import SummaryWriter",
"len(dataloader) dataiter = iter(dataloader) label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes)",
"summary_dev, cfg, args, model, dataloader_dev) time_spent = time.time() - time_now",
"= time.time() - time_now auclist = [] for i in",
"= torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() == 0:",
"summary['epoch'] += 1 return summary, best_dict def test_epoch(summary, cfg, args,",
"get_loss(output, target, t, device, cfg) # AUC output_tensor = torch.sigmoid(",
"run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log \" \"in save_path/log.txt if",
"--device_ids : {}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model",
"cfg.log_every loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str =",
"{}, Step : {}, Loss : {}, ' 'Acc :",
"ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best']",
"default=None, metavar='CFG_PATH', type=str, help=\"Path to the config file in yaml",
"for x in range(len(cfg.num_classes))) true_list = list(x for x in",
"(target == label).float().sum() / len(label) else: raise Exception('Unknown criterion :",
"device, cfg) loss += loss_t loss_sum[t] += loss_t.item() acc_sum[t] +=",
"save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'],",
"from shutil import copyfile import numpy as np from sklearn",
"not None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer",
"criterion : {}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary, summary_dev, cfg,",
"summary_writer = SummaryWriter(args.save_path) epoch_start = 0 best_dict = { \"acc_dev_best\":",
"dev_header) time_now = time.time() summary_dev, predlist, true_list = test_epoch( summary_dev,",
"best_dict['best_idx'] = 1 logging.info( '{}, Best, Step : {}, Loss",
": {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train =",
"= os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0 %s |",
"depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose is",
"x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc']))",
"'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <=",
"= subprocess.getstatusoutput('cp -R %s %s' % (src_folder, dst_folder)) if rc",
"= model(image) output = model(image) output = [torch.unsqueeze(i, 1) for",
"cfg) # AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:,",
"num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch': 0,",
"output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step",
"= edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg, indent=4)) if not",
"logging import json import time import subprocess from shutil import",
": {},' 'Mean auc: {:.3f} ''Run Time : {:.2f} sec'",
">= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc': save_best",
"i in output.T] # different number of tasks loss =",
"summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best']",
"parser.add_argument('--pre_train', default=None, type=str, help=\"If get\" \"parameters from pretrained model\") parser.add_argument('--resume',",
"save_path/log.txt if set True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\") def",
"= iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum =",
"= np.zeros(num_tasks) predlist = list(x for x in range(len(cfg.num_classes))) true_list",
"steps = len(dataloader) dataiter = iter(dataloader) label_header = dataloader.dataset._label_header num_tasks",
"json.dump(cfg, f, indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count()",
"True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] =",
"logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f:",
"len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist = list(x",
"from pretrained model\") parser.add_argument('--resume', default=0, type=int, help=\"If resume from \"",
"torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0] - target.sum()) / target.sum()",
"time_spent = time.time() - time_now time_now = time.time() loss_sum /=",
"DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not None: if os.path.exists(args.pre_train): ckpt",
"summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str =",
"{:.3f} ''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'],",
"os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k:",
"dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step': 0} summary_dev",
"target[:, t].view(-1).cpu().detach().numpy() if step == 0: predlist[t] = output_tensor true_list[t]",
"DataLoader import torch.nn.functional as F from torch.nn import DataParallel from",
"iter(dataloader) label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now = time.time()",
"if cfg.best_target == 'loss': save_best = True if save_best: torch.save(",
"noqa from utils.misc import lr_schedule # noqa from model.utils import",
"best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx']))",
"get\" \"parameters from pretrained model\") parser.add_argument('--resume', default=0, type=int, help=\"If resume",
"best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx']",
"optimizer.step() summary['step'] += 1 if summary['step'] % cfg.log_every == 0:",
"best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1",
"import metrics from easydict import EasyDict as edict import torch",
"raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary,",
"summary_dev, cfg, args, model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header):",
"acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step']",
"Train, Epoch : {}, Step : {}, Loss : {},",
"1 logging.info( '{}, Best, Step : {}, Loss : {},",
"model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not None: if",
"np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step'] % cfg.test_every == 0:",
"vit_pytorch import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')",
"(target.size()[0] - target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target,",
"'Acc : {}, Run Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"),",
"models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number of \" \"workers for each",
"\"previous run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log \" \"in save_path/log.txt",
"' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch :",
"- time_now time_now = time.time() loss_sum /= cfg.log_every acc_sum /=",
"level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w')",
"'Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str,",
"if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path +",
"torch.cuda.device_count() if num_devices < len(device_ids): raise Exception( '#available gpu :",
"summary_dev, cfg, args, model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header)",
"dst_folder = os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0 %s",
"type=int, help=\"If resume from \" \"previous run\") parser.add_argument('--logtofile', default=False, type=bool,",
"for x in range(len(cfg.num_classes))) for step in range(steps): image, target",
"len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model =",
"map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) +",
"1 target = target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target)",
"list(x for x in range(len(cfg.num_classes))) for step in range(steps): image,",
"else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t]",
"= list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter",
"Loss : {}, Acc : {}, Auc : {},' 'Mean",
"= torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step ==",
"import argparse import logging import json import time import subprocess",
"cfg.log_every == 0: time_spent = time.time() - time_now time_now =",
"/= cfg.log_every acc_sum /= cfg.log_every loss_str = ' '.join(map(lambda x:",
"summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1",
"acc_t = get_loss(output, target, t, device, cfg) loss += loss_t",
"summary['epoch'] + 1, summary['step'], loss_str, acc_str, time_spent)) for t in",
"== 0: time_spent = time.time() - time_now time_now = time.time()",
"auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return summary, best_dict",
"= cfg.long_side, cfg.long_side else: h, w = cfg.height, cfg.width summary(model.to(device),",
"image, target = next(dataiter) image = image.to(device) target = target.to(device)",
"t in range(num_tasks): loss_t, acc_t = get_loss(output, target, t, device,",
"true_list def run(args): with open(args.cfg_path) as f: cfg = edict(json.load(f))",
"1} if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path,",
"cfg.width summary(model.to(device), (3, h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if",
"summary_train, summary_dev, cfg, args, model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict,",
"device_ids = list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices <",
"model.train() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps =",
"data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices \"\"comma separated, e.g.",
"summary, best_dict def test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval()",
"= target.to(device) # output, logit_map = model(image) output = model(image)",
"= False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best']",
"in range(num_tasks): loss_t, acc_t = get_loss(output, target, t, device, cfg)",
"= ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda",
".format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True)",
"if step == 0: predlist[t] = output_tensor true_list[t] = target_tensor",
"= {'loss': float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start =",
"{:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(),",
"range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum",
"ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0)",
"# noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str,",
"folder error : {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R %s",
"in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step'])",
"model.eval() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps =",
"= DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header",
"time_now auclist = [] for i in range(len(cfg.num_classes)): y_pred =",
"-f1' % src_folder) if rc != 0: raise Exception('Copy folder",
"model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best']",
"for each data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices \"\"comma",
"'{}, Train, Epoch : {}, Step : {}, Loss :",
"num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if",
"noqa from model.utils import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train",
"for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]),",
"t in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target, t, device,",
"type=str, help=\"Path to the config file in yaml format\") parser.add_argument('save_path',",
"i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i] fpr,",
"np.zeros(num_tasks) predlist = list(x for x in range(len(cfg.num_classes))) true_list =",
": {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str,",
"cfg, args, model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True)",
"%s %s' % (src_folder, dst_folder)) if rc != 0: raise",
"lr summary_train, best_dict = train_epoch( summary_train, summary_dev, cfg, args, model,",
"0: time_spent = time.time() - time_now time_now = time.time() loss_sum",
"data.dataset import ImageDataset # noqa from model.classifier import Classifier #",
"dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0]))",
"{}, Loss : {}, ' 'Acc : {}, Run Time",
"+= loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] = loss_sum / steps",
"cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3,",
"loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum",
"'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k:",
": {} < --device_ids : {}' .format(num_devices, len(device_ids))) device =",
"src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path, 'classification') rc,",
"= np.zeros(num_tasks) for step in range(steps): image, target = next(dataiter)",
"mean_acc if cfg.best_target == 'acc': save_best = True mean_auc =",
"image = image.to(device) target = target.to(device) # output, logit_map =",
"float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start = 0 best_dict",
"= SummaryWriter(args.save_path) epoch_start = 0 best_dict = { \"acc_dev_best\": 0.0,",
"args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO)",
"float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1} if args.resume: ckpt_path = os.path.join(args.save_path,",
"dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now = time.time() loss_sum = np.zeros(num_tasks)",
"\"best_idx\": 1} if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt =",
"if args.verbose is True: from torchsummary import summary if cfg.fix_ratio:",
"= acc_sum / steps return summary, predlist, true_list def run(args):",
"loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step']",
"output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] +=",
"def run(args): with open(args.cfg_path) as f: cfg = edict(json.load(f)) if",
"else: h, w = cfg.height, cfg.width summary(model.to(device), (3, h, w))",
"+= 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info(",
"= np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str",
"(3, h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is",
"= np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step in range(steps): image,",
"acc) def train_epoch(summary, summary_dev, cfg, args, model, dataloader, dataloader_dev, optimizer,",
"= np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item()",
"= np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() summary['loss']",
"range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group",
"if summary['step'] % cfg.test_every == 0: time_now = time.time() summary_dev,",
"x in range(len(cfg.num_classes))) for step in range(steps): image, target =",
"type=bool, help=\"Save log \" \"in save_path/log.txt if set True\") parser.add_argument('--verbose',",
"Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str,",
"'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt'))",
"help=\"Path to the saved models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number of",
": {}, Loss : {}, Acc : {}, Auc :",
"from model.utils import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model')",
"{}, Acc : {},' 'Auc :{},Best Auc : {:.3f}' .format(",
"format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path to the saved models\")",
"return (loss, acc) def train_epoch(summary, summary_dev, cfg, args, model, dataloader,",
"as edict import torch from torch.utils.data import DataLoader import torch.nn.functional",
"t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t],",
"'.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x),",
"target = next(dataiter) image = image.to(device) target = target.to(device) output",
"different number of tasks for t in range(len(cfg.num_classes)): loss_t, acc_t",
"default=False, type=bool, help=\"Save log \" \"in save_path/log.txt if set True\")",
"argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path to the config",
"index, device, cfg): if cfg.criterion == 'BCE': for num_class in",
"label).float().sum() / len(label) else: raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return",
"loss_str, acc_str, time_spent)) for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t],",
"label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now = time.time() loss_sum",
"summary['acc'] = acc_sum / steps return summary, predlist, true_list def",
"in range(len(cfg.num_classes))) true_list = list(x for x in range(len(cfg.num_classes))) for",
"cfg): if cfg.criterion == 'BCE': for num_class in cfg.num_classes: assert",
"epoch_start = 0 best_dict = { \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0,",
"as F from torch.nn import DataParallel from vit_pytorch import ViT",
"= ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch",
"torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best']",
"range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar(",
"= parser.parse_args() if args.verbose is True: print('Using the specified args:')",
"= ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr,",
"summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean()",
"the specified args:') print(args) run(args) if __name__ == '__main__': main()",
"print('Using the specified args:') print(args) run(args) if __name__ == '__main__':",
"model, dataloader_dev) time_spent = time.time() - time_now auclist = []",
"num_devices < len(device_ids): raise Exception( '#available gpu : {} <",
"args.verbose is True: from torchsummary import summary if cfg.fix_ratio: h,",
"loss = torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0] - target.sum())",
"summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum =",
"summary_dev['auc'])) logging.info( '{}, Dev, Step : {}, Loss : {},",
"i in output.T] # different number of tasks for t",
"\"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1} if args.resume:",
"dst_folder)) if rc != 0: raise Exception('copy folder error :",
"import json import time import subprocess from shutil import copyfile",
"= {'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] =",
"ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header",
"= DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not None: if os.path.exists(args.pre_train):",
"model\") parser.add_argument('--resume', default=0, type=int, help=\"If resume from \" \"previous run\")",
"if summary['step'] % cfg.log_every == 0: time_spent = time.time() -",
"shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False,",
"range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar(",
"in output.T] # different number of tasks for t in",
"'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def",
"default=False, type=bool, help=\"Detail info\") def get_loss(output, target, index, device, cfg):",
"true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item()",
"image.to(device) target = target.to(device) output = model(image) output = [torch.unsqueeze(i,",
"- time_now auclist = [] for i in range(len(cfg.num_classes)): y_pred",
"np.zeros(num_tasks) if summary['step'] % cfg.test_every == 0: time_now = time.time()",
"'cfg.json'), 'w') as f: json.dump(cfg, f, indent=1) device_ids = list(map(int,",
"dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose",
"type=str, help=\"GPU indices \"\"comma separated, e.g. '0,1' \") parser.add_argument('--pre_train', default=None,",
"err_msg = subprocess.getstatusoutput('cp -R %s %s' % (src_folder, dst_folder)) if",
"time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t",
"from data.dataset import ImageDataset # noqa from model.classifier import Classifier",
"'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) )",
"if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target ==",
"main(): args = parser.parse_args() if args.verbose is True: print('Using the",
"0 for t in range(num_tasks): loss_t, acc_t = get_loss(output, target,",
"= Classifier(cfg) model = ViT( cfg = cfg, image_size=cfg.width, patch_size=32,",
"cfg.log_every acc_sum /= cfg.log_every loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x),",
"= dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step': 0} summary_dev =",
"best_dict def test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids",
"param_group in optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict = train_epoch(",
"ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder",
"/= cfg.log_every loss_str = ' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str",
"folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv'))",
"ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor,",
"summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best =",
"DataParallel from vit_pytorch import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__))",
"subprocess from shutil import copyfile import numpy as np from",
": {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best']))",
"= (target == label).float().sum() / len(label) else: raise Exception('Unknown criterion",
"== 'BCE': for num_class in cfg.num_classes: assert num_class == 1",
"'.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x),",
"Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1, summary['step'],",
"optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict = train_epoch( summary_train, summary_dev,",
"output[index].view(-1), target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index])",
"torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step == 0:",
"parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices \"\"comma separated, e.g. '0,1' \")",
"type=str, help=\"If get\" \"parameters from pretrained model\") parser.add_argument('--resume', default=0, type=int,",
"args, model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train()",
"--max-depth=0 %s | cut -f1' % src_folder) if rc !=",
"optimizer, summary_writer, best_dict, dev_header) time_now = time.time() summary_dev, predlist, true_list",
"'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx']))",
"metavar='CFG_PATH', type=str, help=\"Path to the config file in yaml format\")",
"acc = (target == label).float().sum() / len(label) else: raise Exception('Unknown",
"= summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if",
"model(image) output = model(image) output = [torch.unsqueeze(i, 1) for i",
"summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc",
"open(args.cfg_path) as f: cfg = edict(json.load(f)) if args.verbose is True:",
"%H:%M:%S\"), summary['epoch'] + 1, summary['step'], loss_str, acc_str, time_spent)) for t",
"parser.add_argument('--resume', default=0, type=int, help=\"If resume from \" \"previous run\") parser.add_argument('--logtofile',",
"dataiter = iter(dataloader) label_header = dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now",
"None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer =",
": {},Auc :{},' 'Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"),",
"0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1} if args.resume: ckpt_path",
"# different number of tasks loss = 0 for t",
"= target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight:",
"save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']:",
"loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices \"\"comma separated, e.g. '0,1'",
"if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device)",
"Dev, Step : {}, Loss : {}, Acc : {},",
"== 0: loss = torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0]",
"cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best, Step : {},",
"{}, Acc : {},Auc :{},' 'Best Auc : {:.3f}' .format(",
"summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best",
"best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(','))) device =",
"acc_sum = np.zeros(num_tasks) for step in range(steps): image, target =",
"'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1",
"summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step'])",
"parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\") def get_loss(output, target, index, device,",
"torch.nn import DataParallel from vit_pytorch import ViT from tensorboardX import",
"x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step : {}, Loss",
"loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] = loss_sum /",
"Epoch : {}, Step : {}, Loss : {}, '",
"of tasks for t in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output,",
"torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum() / len(label) else: raise",
"is not None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt)",
"epoch in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs)",
"y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist)",
"= { \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0,",
"if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target ==",
": {}, Loss : {}, Acc : {},' 'Auc :{},Best",
"== 1 target = target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight,",
"summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False mean_acc",
"# AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy()",
"' '.join(map(lambda x: '{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda x:",
"raise Exception('Copy folder error : {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp",
"subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1' % src_folder) if rc",
"else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float()",
"time.time() - time_now time_now = time.time() loss_sum /= cfg.log_every acc_sum",
"device, cfg): if cfg.criterion == 'BCE': for num_class in cfg.num_classes:",
"Step : {}, Loss : {}, Acc : {}, Auc",
"subprocess.getstatusoutput('cp -R %s %s' % (src_folder, dst_folder)) if rc !=",
"batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch':",
"0.0, \"best_idx\": 1} if args.resume: ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt",
"target.to(device) # output, logit_map = model(image) output = model(image) output",
"{}, Auc : {},' 'Mean auc: {:.3f} ''Run Time :",
"logging.info( '{}, Best, Step : {}, Loss : {}, Acc",
"get_loss(output, target, t, device, cfg) loss += loss_t loss_sum[t] +=",
"help=\"GPU indices \"\"comma separated, e.g. '0,1' \") parser.add_argument('--pre_train', default=None, type=str,",
"optimizer, summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(',')))",
"sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1, summary['step'], loss_str, acc_str, time_spent))",
"= train_epoch( summary_train, summary_dev, cfg, args, model, dataloader_train, dataloader_dev, optimizer,",
"== label).float().sum() / len(label) else: raise Exception('Unknown criterion : {}'.format(cfg.criterion))",
"summary_writer, best_dict, dev_header): torch.set_grad_enabled(True) model.train() device_ids = list(map(int, args.device_ids.split(','))) device",
"resume from \" \"previous run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log",
".format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for",
"model.classifier import Classifier # noqa from utils.misc import lr_schedule #",
"for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]),",
"\" \"workers for each data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU",
"y_pred = predlist[i] y_true = true_list[i] fpr, tpr, thresholds =",
"y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] =",
"'{}, Dev, Step : {}, Loss : {}, Acc :",
"loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'],",
"param_group['lr'] = lr summary_train, best_dict = train_epoch( summary_train, summary_dev, cfg,",
"torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best':",
"logging.info( '{}, Train, Epoch : {}, Step : {}, Loss",
"1, summary['step'], loss_str, acc_str, time_spent)) for t in range(num_tasks): summary_writer.add_scalar(",
"'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args = parser.parse_args()",
"0: loss = torch.tensor(0., requires_grad=True).to(device) else: weight = (target.size()[0] -",
"Step : {}, Loss : {}, Acc : {},Auc :{},'",
"'/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path,",
"range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i] fpr, tpr, thresholds",
"num_class == 1 target = target[:, index].view(-1) pos_weight = torch.from_numpy(",
"(loss, acc) def train_epoch(summary, summary_dev, cfg, args, model, dataloader, dataloader_dev,",
"import ImageDataset # noqa from model.classifier import Classifier # noqa",
"dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() == 0: loss = torch.tensor(0.,",
"if rc != 0: raise Exception('copy folder error : {}'.format(err_msg))",
"best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss': save_best =",
"= len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist =",
"{},Auc :{},' 'Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'],",
"if rc != 0: raise Exception('Copy folder error : {}'.format(rc))",
"f, indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if",
"summary_train, best_dict = train_epoch( summary_train, summary_dev, cfg, args, model, dataloader_train,",
"'Auc :{},Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str,",
"image = image.to(device) target = target.to(device) output = model(image) output",
"get_loss(output, target, index, device, cfg): if cfg.criterion == 'BCE': for",
"set True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\") def get_loss(output, target,",
"t, device, cfg) loss += loss_t loss_sum[t] += loss_t.item() acc_sum[t]",
"import DataLoader import torch.nn.functional as F from torch.nn import DataParallel",
"\" \"previous run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log \" \"in",
"dataiter = iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum",
"dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True)",
"number of tasks loss = 0 for t in range(num_tasks):",
"= loss_sum / steps summary['acc'] = acc_sum / steps return",
"sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent))",
"%H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] +=",
"torch.set_grad_enabled(True) summary['epoch'] += 1 return summary, best_dict def test_epoch(summary, cfg,",
"from model.classifier import Classifier # noqa from utils.misc import lr_schedule",
"== 0: time_now = time.time() summary_dev, predlist, true_list = test_epoch(",
"summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{},",
"loss = 0 for t in range(num_tasks): loss_t, acc_t =",
"ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch): lr",
"utils.misc import lr_schedule # noqa from model.utils import get_optimizer #",
"'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False",
"'{:.3f}'.format(x), acc_sum)) logging.info( '{}, Train, Epoch : {}, Step :",
"args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices < len(device_ids): raise Exception(",
"summary['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >=",
"= get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder =",
"= ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step",
"F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target,",
"Step : {}, Loss : {}, Acc : {},' 'Auc",
"= lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr']",
"help=\"If resume from \" \"previous run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save",
"'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] +=",
"{}, ' 'Acc : {}, Run Time : {:.2f} sec'",
"auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'],",
"True: from torchsummary import summary if cfg.fix_ratio: h, w =",
"num_class in cfg.num_classes: assert num_class == 1 target = target[:,",
"\"in save_path/log.txt if set True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\")",
"summary_train['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >=",
"'{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info(",
"best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if",
"return summary, best_dict def test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False)",
"'0,1' \") parser.add_argument('--pre_train', default=None, type=str, help=\"If get\" \"parameters from pretrained",
"output = [torch.unsqueeze(i, 1) for i in output.T] # different",
"print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True:",
"cfg, mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train",
"is True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile",
"of tasks loss = 0 for t in range(num_tasks): loss_t,",
"> cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best, Step :",
"tasks for t in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target,",
"loss_t, acc_t = get_loss(output, target, t, device, cfg) loss +=",
"+= acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1 if summary['step']",
"mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose is True: from",
"from \" \"previous run\") parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log \"",
"os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO)",
"from sklearn import metrics from easydict import EasyDict as edict",
"True\") parser.add_argument('--verbose', default=False, type=bool, help=\"Detail info\") def get_loss(output, target, index,",
"Exception('Copy folder error : {}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R",
"target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss =",
": {},' 'Auc :{},Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"),",
"'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if",
"= True if save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best':",
"= model(image) output = [torch.unsqueeze(i, 1) for i in output.T]",
"'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t],",
"= mean_auc if cfg.best_target == 'auc': save_best = True mean_loss",
"= time.time() loss_sum /= cfg.log_every acc_sum /= cfg.log_every loss_str =",
"mode='dev'), batch_size=cfg.dev_batch_size, num_workers=args.num_workers, drop_last=False, shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train =",
"noqa from model.classifier import Classifier # noqa from utils.misc import",
"import EasyDict as edict import torch from torch.utils.data import DataLoader",
"{:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1, summary['step'], loss_str, acc_str,",
"def test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids =",
"steps summary['acc'] = acc_sum / steps return summary, predlist, true_list",
"model = ViT( cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024,",
"'Mean auc: {:.3f} ''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d",
"time_now = time.time() loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for",
"target.to(device) output = model(image) output = [torch.unsqueeze(i, 1) for i",
"time.time() loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step in",
"output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step == 0: predlist[t]",
"time_now = time.time() summary_dev, predlist, true_list = test_epoch( summary_dev, cfg,",
"summary_train = {'epoch': 0, 'step': 0} summary_dev = {'loss': float('inf'),",
"open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg, f, indent=1) device_ids =",
"summary(model.to(device), (3, h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train",
"with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg, f, indent=1) device_ids",
"cfg, args, model, dataloader_train, dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now",
"import subprocess from shutil import copyfile import numpy as np",
"default=None, metavar='SAVE_PATH', type=str, help=\"Path to the saved models\") parser.add_argument('--num_workers', default=8,",
"= next(dataiter) image = image.to(device) target = target.to(device) output =",
"# noqa from utils.misc import lr_schedule # noqa from model.utils",
"summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum =",
"in output.T] # different number of tasks loss = 0",
": {}, Loss : {}, Acc : {},Auc :{},' 'Best",
"Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str,",
"next(dataiter) image = image.to(device) target = target.to(device) # output, logit_map",
"t].view(-1).cpu().detach().numpy() if step == 0: predlist[t] = output_tensor true_list[t] =",
"os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers,",
"0: time_now = time.time() summary_dev, predlist, true_list = test_epoch( summary_dev,",
"len(cfg.num_classes) time_now = time.time() loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks)",
"False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] =",
"model.module.state_dict()}, os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args = parser.parse_args() if",
"summary_dev['auc'][t], summary['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc",
"step == 0: predlist[t] = output_tensor true_list[t] = target_tensor else:",
"image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3",
"rc != 0: raise Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv,",
"auclist = [] for i in range(len(cfg.num_classes)): y_pred = predlist[i]",
"if cfg.criterion == 'BCE': for num_class in cfg.num_classes: assert num_class",
"is True: print('Using the specified args:') print(args) run(args) if __name__",
"best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return summary, best_dict def",
"Auc : {},' 'Mean auc: {:.3f} ''Run Time : {:.2f}",
"if cfg.best_target == 'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean()",
"'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False",
"output.T] # different number of tasks for t in range(len(cfg.num_classes)):",
"best_dict = { \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\":",
"summary, predlist, true_list def run(args): with open(args.cfg_path) as f: cfg",
"time_now time_now = time.time() loss_sum /= cfg.log_every acc_sum /= cfg.log_every",
"time_spent = time.time() - time_now auclist = [] for i",
"test_epoch(summary, cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int,",
": {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1, summary['step'], loss_str,",
"target, t, device, cfg) # AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy()",
"ckpt_path = os.path.join(args.save_path, 'train.ckpt') ckpt = torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train",
"summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)):",
"loss_sum /= cfg.log_every acc_sum /= cfg.log_every loss_str = ' '.join(map(lambda",
"= argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path to the",
"target = target[:, index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if",
"torch.utils.data import DataLoader import torch.nn.functional as F from torch.nn import",
"cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict",
"in optimizer.param_groups: param_group['lr'] = lr summary_train, best_dict = train_epoch( summary_train,",
"== 'loss': save_best = True if save_best: torch.save( {'epoch': summary_train['epoch'],",
"= F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1),",
"'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1'",
"{}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader(",
"f: json.dump(cfg, f, indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices =",
"emb_dropout=0.3, channels=3 ) if args.verbose is True: from torchsummary import",
": {}, Run Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch']",
"for epoch in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'],",
"len(label) else: raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss, acc)",
"auc: {:.3f} ''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"),",
"= True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best']",
"heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose is True:",
"0.0} summary_writer = SummaryWriter(args.save_path) epoch_start = 0 best_dict = {",
"parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path to",
"loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1",
"predlist = list(x for x in range(len(cfg.num_classes))) true_list = list(x",
"AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor = target[:, t].view(-1).cpu().detach().numpy() if",
"os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg)",
"lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups:",
"in range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i] fpr, tpr,",
"Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str,",
"+ '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa",
"for num_class in cfg.num_classes: assert num_class == 1 target =",
"summary['loss'] = loss_sum / steps summary['acc'] = acc_sum / steps",
"- target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight)",
"predlist, true_list = test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent",
"True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not",
"from utils.misc import lr_schedule # noqa from model.utils import get_optimizer",
"torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa from model.classifier import",
"target.sum() == 0: loss = torch.tensor(0., requires_grad=True).to(device) else: weight =",
"best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc': save_best =",
"= np.zeros(num_tasks) if summary['step'] % cfg.test_every == 0: time_now =",
"= len(dataloader) dataiter = iter(dataloader) num_tasks = len(cfg.num_classes) loss_sum =",
"if num_devices < len(device_ids): raise Exception( '#available gpu : {}",
"cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in",
"if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target ==",
"np.append(true_list[t], target_tensor) loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() summary['loss'] =",
"'{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str",
"os.path.join(args.save_path, 'train.ckpt')) summary_writer.close() def main(): args = parser.parse_args() if args.verbose",
"\"workers for each data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices",
"target = target.to(device) # output, logit_map = model(image) output =",
"summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr'] = lr summary_train,",
"time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch']",
"time_spent)) for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar(",
"device_ids=device_ids).to(device).train() if args.pre_train is not None: if os.path.exists(args.pre_train): ckpt =",
"model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx']",
"if cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side else: h, w",
"= ViT( cfg = cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6,",
"torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__))",
"model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(','))) device =",
"w)) model = DataParallel(model, device_ids=device_ids).to(device).train() if args.pre_train is not None:",
"/ len(label) else: raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss,",
"acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return summary,",
"target.sum()) / target.sum() loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else:",
"{}, Run Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] +",
"logging.info( '{}, Dev, Step : {}, Loss : {}, Acc",
"best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] +=",
"rc, err_msg = subprocess.getstatusoutput('cp -R %s %s' % (src_folder, dst_folder))",
"acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1 if summary['step'] %",
"'{:.3f}'.format(x), summary_dev['auc'])) logging.info( '{}, Dev, Step : {}, Loss :",
"< len(device_ids): raise Exception( '#available gpu : {} < --device_ids",
"= len(cfg.num_classes) time_now = time.time() loss_sum = np.zeros(num_tasks) acc_sum =",
"parser.parse_args() if args.verbose is True: print('Using the specified args:') print(args)",
"for i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true = true_list[i]",
"saved models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number of \" \"workers for",
"of \" \"workers for each data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str,",
"parser.add_argument('--logtofile', default=False, type=bool, help=\"Save log \" \"in save_path/log.txt if set",
"import logging import json import time import subprocess from shutil",
"def get_loss(output, target, index, device, cfg): if cfg.criterion == 'BCE':",
"optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1 if summary['step'] % cfg.log_every",
"best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] = 1 logging.info( '{}, Best, Step",
"index].view(-1) pos_weight = torch.from_numpy( np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum()",
"1 return summary, best_dict def test_epoch(summary, cfg, args, model, dataloader):",
"best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format( best_dict['best_idx'])) ) best_dict['best_idx'] += 1",
"requires_grad=True).to(device) else: weight = (target.size()[0] - target.sum()) / target.sum() loss",
"device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) label_header",
"logit_map = model(image) output = model(image) output = [torch.unsqueeze(i, 1)",
"acc_str, time_spent)) for t in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step'])",
"True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is",
"indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path",
"src_folder) if rc != 0: raise Exception('Copy folder error :",
"!= 0: raise Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path,",
"== 'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if mean_loss",
"{'loss': float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path) epoch_start = 0",
"summary_writer, best_dict, dev_header) time_now = time.time() summary_dev, predlist, true_list =",
"Loss : {}, Acc : {},Auc :{},' 'Best Auc :",
"train_epoch( summary_train, summary_dev, cfg, args, model, dataloader_train, dataloader_dev, optimizer, summary_writer,",
"with open(args.cfg_path) as f: cfg = edict(json.load(f)) if args.verbose is",
"\"parameters from pretrained model\") parser.add_argument('--resume', default=0, type=int, help=\"If resume from",
"Exception( '#available gpu : {} < --device_ids : {}' .format(num_devices,",
"else: raise Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss, acc) def",
"range(len(cfg.num_classes))) for step in range(steps): image, target = next(dataiter) image",
"summary_writer.close() def main(): args = parser.parse_args() if args.verbose is True:",
"= get_loss(output, target, t, device, cfg) loss += loss_t loss_sum[t]",
"tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = ' '.join(map(lambda x:",
"best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc': save_best = True",
"summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary_train['step']) save_best = False mean_acc",
"else: logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as",
"time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t",
"Classifier # noqa from utils.misc import lr_schedule # noqa from",
"= mean_acc if cfg.best_target == 'acc': save_best = True mean_auc",
": {}, Acc : {}, Auc : {},' 'Mean auc:",
"lr_schedule # noqa from model.utils import get_optimizer # noqa parser",
">= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc': save_best",
"device_ids = list(map(int, args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader)",
"{}, Loss : {}, Acc : {},Auc :{},' 'Best Auc",
"from vit_pytorch import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) +",
"= output_tensor true_list[t] = target_tensor else: predlist[t] = np.append(predlist[t], output_tensor)",
"= time.time() summary_dev, predlist, true_list = test_epoch( summary_dev, cfg, args,",
"%s' % (src_folder, dst_folder)) if rc != 0: raise Exception('copy",
"torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa from model.classifier",
"loss += loss_t loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad()",
"to the saved models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number of \"",
"tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset",
"import Classifier # noqa from utils.misc import lr_schedule # noqa",
"true_list = test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent =",
"cfg.height, cfg.width summary(model.to(device), (3, h, w)) model = DataParallel(model, device_ids=device_ids).to(device).train()",
"if args.verbose is True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path): os.mkdir(args.save_path)",
"summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target",
"# noqa from model.classifier import Classifier # noqa from utils.misc",
"import torch.nn.functional as F from torch.nn import DataParallel from vit_pytorch",
"summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target",
"loss_sum)) acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum)) logging.info( '{},",
"best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx']",
"type=str, help=\"Path to the saved models\") parser.add_argument('--num_workers', default=8, type=int, help=\"Number",
"edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg, indent=4)) if not os.path.exists(args.save_path):",
"!= 0: raise Exception('Copy folder error : {}'.format(rc)) rc, err_msg",
"steps return summary, predlist, true_list def run(args): with open(args.cfg_path) as",
"= target_tensor else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t],",
"in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target, t, device, cfg)",
"cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side else: h, w =",
"easydict import EasyDict as edict import torch from torch.utils.data import",
"range(len(cfg.num_classes))) true_list = list(x for x in range(len(cfg.num_classes))) for step",
"for t in range(len(cfg.num_classes)): loss_t, acc_t = get_loss(output, target, t,",
"pretrained model\") parser.add_argument('--resume', default=0, type=int, help=\"If resume from \" \"previous",
"target_tensor = target[:, t].view(-1).cpu().detach().numpy() if step == 0: predlist[t] =",
"loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return",
"os.path.join(args.save_path, 'classification') rc, size = subprocess.getstatusoutput('du --max-depth=0 %s | cut",
"%s | cut -f1' % src_folder) if rc != 0:",
"\"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\": 1}",
"size = subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1' % src_folder)",
"parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path to the config file in",
"copyfile import numpy as np from sklearn import metrics from",
"np.array(auclist) loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str =",
": {}, ' 'Acc : {}, Run Time : {:.2f}",
"in range(epoch_start, cfg.epoch): lr = lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for",
"np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step in range(steps): image, target",
"= {'epoch': 0, 'step': 0} summary_dev = {'loss': float('inf'), 'acc':",
"'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx']",
"{:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch':",
"acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best':",
"os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg,",
": {}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model =",
"= 1 logging.info( '{}, Best, Step : {}, Loss :",
"-R %s %s' % (src_folder, dst_folder)) if rc != 0:",
"+= 1 return summary, best_dict def test_epoch(summary, cfg, args, model,",
"best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for",
"= predlist[i] y_true = true_list[i] fpr, tpr, thresholds = metrics.roc_curve(",
"output = model(image) output = [torch.unsqueeze(i, 1) for i in",
"= summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if",
"run(args): with open(args.cfg_path) as f: cfg = edict(json.load(f)) if args.verbose",
"summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict':",
"| cut -f1' % src_folder) if rc != 0: raise",
"cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr'] = lr",
"= ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda",
"if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(),",
"x in range(len(cfg.num_classes))) true_list = list(x for x in range(len(cfg.num_classes)))",
"= torch.cuda.device_count() if num_devices < len(device_ids): raise Exception( '#available gpu",
"import sys import os import argparse import logging import json",
"y_true = true_list[i] fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred,",
"help=\"Save log \" \"in save_path/log.txt if set True\") parser.add_argument('--verbose', default=False,",
"'train.ckpt')) summary_writer.close() def main(): args = parser.parse_args() if args.verbose is",
"os.path.dirname(os.path.abspath(__file__)) + '/../' dst_folder = os.path.join(args.save_path, 'classification') rc, size =",
"as f: cfg = edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg,",
"mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc",
".format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model",
"'step': summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()},",
"= torch.load(ckpt_path, map_location=device) model.module.load_state_dict(ckpt['state_dict']) summary_train = {'epoch': ckpt['epoch'], 'step': ckpt['step']}",
"'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t],",
"label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum() / len(label)",
"'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if",
"'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step']) loss_sum = np.zeros(num_tasks)",
"target = next(dataiter) image = image.to(device) target = target.to(device) #",
"Run Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['epoch'] + 1,",
"true_list = list(x for x in range(len(cfg.num_classes))) for step in",
"{}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary, summary_dev, cfg, args, model,",
"lr_schedule(cfg.lr, cfg.lr_factor, summary_train['epoch'], cfg.lr_epochs) for param_group in optimizer.param_groups: param_group['lr'] =",
"= summary_dev['loss'][cfg.save_index].mean() if mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if",
"if cfg.best_target == 'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean()",
"save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean() if mean_acc >= best_dict['acc_dev_best']:",
"args.resume: with open(os.path.join(args.save_path, 'cfg.json'), 'w') as f: json.dump(cfg, f, indent=1)",
"= metrics.auc(fpr, tpr) auclist.append(auc) summary_dev['auc'] = np.array(auclist) loss_dev_str = '",
"''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str,",
"mean_acc >= best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc':",
"log \" \"in save_path/log.txt if set True\") parser.add_argument('--verbose', default=False, type=bool,",
"patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3, emb_dropout=0.3, channels=3 )",
"Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path,",
"summary['step'] % cfg.log_every == 0: time_spent = time.time() - time_now",
"cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv,",
"save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']:",
"summary['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path,",
"device, cfg) # AUC output_tensor = torch.sigmoid( output[t].view(-1)).cpu().detach().numpy() target_tensor =",
"x: '{:.5f}'.format(x), loss_sum)) acc_str = ' '.join(map(lambda x: '{:.3f}'.format(x), acc_sum))",
"summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step'])",
"[torch.unsqueeze(i, 1) for i in output.T] # different number of",
"model.train() torch.set_grad_enabled(True) summary['epoch'] += 1 return summary, best_dict def test_epoch(summary,",
"import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0)",
"summary_dev['auc'][cfg.save_index].mean() if mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target",
"<= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss': save_best",
"+= loss_t loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward()",
"0: raise Exception('Copy folder error : {}'.format(rc)) rc, err_msg =",
"mean_auc if cfg.best_target == 'auc': save_best = True mean_loss =",
"json import time import subprocess from shutil import copyfile import",
"torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model = ViT( cfg =",
"summary['step'] += 1 if summary['step'] % cfg.log_every == 0: time_spent",
"{ \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'), \"fused_dev_best\": 0.0, \"best_idx\":",
"summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)):",
"'BCE': for num_class in cfg.num_classes: assert num_class == 1 target",
"= torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model = ViT( cfg",
"= torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader) label_header =",
"target, index, device, cfg): if cfg.criterion == 'BCE': for num_class",
"'.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x),",
"best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best':",
"acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] += 1 if",
"in yaml format\") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path to the",
"cfg, args, model, dataloader): torch.set_grad_enabled(False) model.eval() device_ids = list(map(int, args.device_ids.split(',')))",
"best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch in range(epoch_start,",
"= True if save_best: torch.save( {'epoch': summary['epoch'], 'step': summary['step'], 'acc_dev_best':",
"SummaryWriter(args.save_path) epoch_start = 0 best_dict = { \"acc_dev_best\": 0.0, \"auc_dev_best\":",
"fpr, tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc =",
"mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg,",
"num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader( ImageDataset(cfg.dev_csv, cfg, mode='dev'), batch_size=cfg.dev_batch_size,",
"acc_sum / steps return summary, predlist, true_list def run(args): with",
"in range(len(cfg.num_classes))) for step in range(steps): image, target = next(dataiter)",
"cfg.long_side, cfg.long_side else: h, w = cfg.height, cfg.width summary(model.to(device), (3,",
"= cfg, image_size=cfg.width, patch_size=32, num_classes=5, dim=1024, depth=6, heads=8, mlp_dim=512, dropout=0.3,",
"%H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in",
"as f: json.dump(cfg, f, indent=1) device_ids = list(map(int, args.device_ids.split(','))) num_devices",
"step in range(steps): image, target = next(dataiter) image = image.to(device)",
": {}, Step : {}, Loss : {}, ' 'Acc",
"shuffle=False) dev_header = dataloader_dev.dataset._label_header summary_train = {'epoch': 0, 'step': 0}",
"summary_dev, predlist, true_list = test_epoch( summary_dev, cfg, args, model, dataloader_dev)",
"copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv,",
"+= loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step() summary['step'] +=",
"# model = Classifier(cfg) model = ViT( cfg = cfg,",
"summary['step']) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step'] %",
"args.pre_train is not None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train, map_location=device)",
"Acc : {},' 'Auc :{},Best Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d",
"0: predlist[t] = output_tensor true_list[t] = target_tensor else: predlist[t] =",
"import summary if cfg.fix_ratio: h, w = cfg.long_side, cfg.long_side else:",
"if args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\", level=logging.INFO) else:",
"acc_dev_str = ' '.join(map(lambda x: '{:.3f}'.format(x), summary_dev['acc'])) auc_dev_str = '",
"0: raise Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv'))",
"time.time() loss_sum /= cfg.log_every acc_sum /= cfg.log_every loss_str = '",
"true_list[t] = target_tensor else: predlist[t] = np.append(predlist[t], output_tensor) true_list[t] =",
"target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum()",
"f: cfg = edict(json.load(f)) if args.verbose is True: print(json.dumps(cfg, indent=4))",
"= ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch",
"raise Exception('copy folder error : {}'.format(err_msg)) copyfile(cfg.train_csv, os.path.join(args.save_path, 'train.csv')) copyfile(cfg.dev_csv,",
"e.g. '0,1' \") parser.add_argument('--pre_train', default=None, type=str, help=\"If get\" \"parameters from",
"import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None,",
": {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str, acc_dev_str, auc_dev_str,",
"acc_sum[t] += acc_t.item() summary['loss'] = loss_sum / steps summary['acc'] =",
"image.to(device) target = target.to(device) # output, logit_map = model(image) output",
"= ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best'] best_dict['auc_dev_best'] = ckpt['auc_dev_best'] epoch_start =",
"type=bool, help=\"Detail info\") def get_loss(output, target, index, device, cfg): if",
"= torch.load(args.pre_train, map_location=device) model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder =",
"= torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target == label).float().sum() / len(label) else:",
"Exception('Unknown criterion : {}'.format(cfg.criterion)) return (loss, acc) def train_epoch(summary, summary_dev,",
"dataloader_dev, optimizer, summary_writer, best_dict, dev_header) time_now = time.time() summary_dev, predlist,",
"args.device_ids.split(','))) device = torch.device('cuda:{}'.format(device_ids[0])) steps = len(dataloader) dataiter = iter(dataloader)",
"# noqa from model.utils import get_optimizer # noqa parser =",
"num_tasks = len(cfg.num_classes) time_now = time.time() loss_sum = np.zeros(num_tasks) acc_sum",
"metavar='SAVE_PATH', type=str, help=\"Path to the saved models\") parser.add_argument('--num_workers', default=8, type=int,",
"= metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr) auclist.append(auc)",
"< --device_ids : {}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0])) #",
"np.array(cfg.pos_weight, dtype=np.float32)).to(device).type_as(target) if cfg.batch_weight: if target.sum() == 0: loss =",
"model.module.load_state_dict(ckpt) optimizer = get_optimizer(model.parameters(), cfg) src_folder = os.path.dirname(os.path.abspath(__file__)) + '/../'",
"mean_loss if cfg.best_target == 'loss': save_best = True if save_best:",
"help=\"If get\" \"parameters from pretrained model\") parser.add_argument('--resume', default=0, type=int, help=\"If",
"acc_dev_str, auc_dev_str, summary_dev['auc'].mean(), time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]),",
"copyfile(cfg.dev_csv, os.path.join(args.save_path, 'dev.csv')) dataloader_train = DataLoader( ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size,",
"device = torch.device('cuda:{}'.format(device_ids[0])) # model = Classifier(cfg) model = ViT(",
"w = cfg.height, cfg.width summary(model.to(device), (3, h, w)) model =",
"parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help=\"Path to the saved models\") parser.add_argument('--num_workers',",
"type=int, help=\"Number of \" \"workers for each data loader\") parser.add_argument('--device_ids',",
"= list(map(int, args.device_ids.split(','))) num_devices = torch.cuda.device_count() if num_devices < len(device_ids):",
"range(steps): image, target = next(dataiter) image = image.to(device) target =",
"output, logit_map = model(image) output = model(image) output = [torch.unsqueeze(i,",
"summary['step'] % cfg.test_every == 0: time_now = time.time() summary_dev, predlist,",
"0, 'step': 0} summary_dev = {'loss': float('inf'), 'acc': 0.0} summary_writer",
"if save_best: torch.save( {'epoch': summary_train['epoch'], 'step': summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best':",
"# output, logit_map = model(image) output = model(image) output =",
"output.T] # different number of tasks loss = 0 for",
"separated, e.g. '0,1' \") parser.add_argument('--pre_train', default=None, type=str, help=\"If get\" \"parameters",
"acc_sum = np.zeros(num_tasks) if summary['step'] % cfg.test_every == 0: time_now",
"% cfg.test_every == 0: time_now = time.time() summary_dev, predlist, true_list",
"Auc : {:.3f}' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str,",
"loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits(",
"best_dict['acc_dev_best']: best_dict['acc_dev_best'] = mean_acc if cfg.best_target == 'acc': save_best =",
"if args.pre_train is not None: if os.path.exists(args.pre_train): ckpt = torch.load(args.pre_train,",
"os.path.exists(args.save_path): os.mkdir(args.save_path) if args.logtofile is True: logging.basicConfig(filename=args.save_path + '/log.txt', filemode=\"w\",",
"loss_t loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item() optimizer.zero_grad() loss.backward() optimizer.step()",
"time_now = time.time() loss_sum /= cfg.log_every acc_sum /= cfg.log_every loss_str",
"time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar(",
"/ steps summary['acc'] = acc_sum / steps return summary, predlist,",
"cfg.best_target == 'auc': save_best = True mean_loss = summary_dev['loss'][cfg.save_index].mean() if",
"predlist[t] = np.append(predlist[t], output_tensor) true_list[t] = np.append(true_list[t], target_tensor) loss_sum[t] +=",
"rc, size = subprocess.getstatusoutput('du --max-depth=0 %s | cut -f1' %",
"= image.to(device) target = target.to(device) # output, logit_map = model(image)",
"cfg.best_target == 'loss': save_best = True if save_best: torch.save( {'epoch':",
"= time.time() loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) for step",
"best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc': save_best = True",
"= time.time() - time_now time_now = time.time() loss_sum /= cfg.log_every",
"t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t],",
"' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = ' '.join(map(lambda x:",
"Best, Step : {}, Loss : {}, Acc : {},Auc",
"cfg) loss += loss_t loss_sum[t] += loss_t.item() acc_sum[t] += acc_t.item()",
"loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) if summary['step'] % cfg.test_every",
"summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]), summary_dev['auc'][t], summary['step']) save_best = False mean_acc = summary_dev['acc'][cfg.save_index].mean()",
"= F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc =",
"= get_loss(output, target, t, device, cfg) # AUC output_tensor =",
"test_epoch( summary_dev, cfg, args, model, dataloader_dev) time_spent = time.time() -",
"dropout=0.3, emb_dropout=0.3, channels=3 ) if args.verbose is True: from torchsummary",
"model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path to the config file",
"{}'.format(rc)) rc, err_msg = subprocess.getstatusoutput('cp -R %s %s' % (src_folder,",
"target, pos_weight=weight) else: loss = F.binary_cross_entropy_with_logits( output[index].view(-1), target, pos_weight=pos_weight[index]) label",
"output[index].view(-1), target, pos_weight=pos_weight[index]) label = torch.sigmoid(output[index].view(-1)).ge(0.5).float() acc = (target ==",
"tpr, thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr,",
"time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, best_dict['auc_dev_best'])) torch.save({'epoch': summary_train['epoch'], 'step':",
"parser.add_argument('--num_workers', default=8, type=int, help=\"Number of \" \"workers for each data",
"channels=3 ) if args.verbose is True: from torchsummary import summary",
"{} < --device_ids : {}' .format(num_devices, len(device_ids))) device = torch.device('cuda:{}'.format(device_ids[0]))",
"== 0: predlist[t] = output_tensor true_list[t] = target_tensor else: predlist[t]",
"'loss': save_best = True if save_best: torch.save( {'epoch': summary['epoch'], 'step':",
"epoch_start = ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch): lr =",
"model = Classifier(cfg) model = ViT( cfg = cfg, image_size=cfg.width,",
"summary_train['step'], 'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path,",
"+= 1 if summary['step'] % cfg.log_every == 0: time_spent =",
"= next(dataiter) image = image.to(device) target = target.to(device) # output,",
"thresholds = metrics.roc_curve( y_true, y_pred, pos_label=1) auc = metrics.auc(fpr, tpr)",
"mean_auc >= best_dict['auc_dev_best']: best_dict['auc_dev_best'] = mean_auc if cfg.best_target == 'auc':",
"time_spent)) for t in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar(",
"{'epoch': ckpt['epoch'], 'step': ckpt['step']} best_dict['acc_dev_best'] = ckpt['acc_dev_best'] best_dict['loss_dev_best'] = ckpt['loss_dev_best']",
"'acc_dev_best': best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(",
"= mean_loss if cfg.best_target == 'loss': save_best = True if",
"noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help=\"Path",
"% cfg.log_every == 0: time_spent = time.time() - time_now time_now",
"filemode=\"w\", level=logging.INFO) else: logging.basicConfig(level=logging.INFO) if not args.resume: with open(os.path.join(args.save_path, 'cfg.json'),",
"0 best_dict = { \"acc_dev_best\": 0.0, \"auc_dev_best\": 0.0, \"loss_dev_best\": float('inf'),",
"train_epoch(summary, summary_dev, cfg, args, model, dataloader, dataloader_dev, optimizer, summary_writer, best_dict,",
"best_dict['acc_dev_best'], 'auc_dev_best': best_dict['auc_dev_best'], 'loss_dev_best': best_dict['loss_dev_best'], 'state_dict': model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) )",
"import time import subprocess from shutil import copyfile import numpy",
"{:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary_train['step'], loss_dev_str, acc_dev_str, auc_dev_str, summary_dev['auc'].mean(),",
"= ckpt['auc_dev_best'] epoch_start = ckpt['epoch'] for epoch in range(epoch_start, cfg.epoch):",
"each data loader\") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help=\"GPU indices \"\"comma separated,",
"default=None, type=str, help=\"If get\" \"parameters from pretrained model\") parser.add_argument('--resume', default=0,",
"' 'Acc : {}, Run Time : {:.2f} sec' .format(time.strftime(\"%Y-%m-%d",
"summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary_train['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary_train['step']) summary_writer.add_scalar( 'dev/auc_{}'.format(dev_header[t]),",
"dataloader_dev) time_spent = time.time() - time_now auclist = [] for",
"cfg, args, model, dataloader_dev) time_spent = time.time() - time_now auclist",
"num_tasks = len(cfg.num_classes) loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist",
"args, model, dataloader_dev) time_spent = time.time() - time_now auclist =",
"cfg.best_target == 'acc': save_best = True mean_auc = summary_dev['auc'][cfg.save_index].mean() if",
"= dataloader.dataset._label_header num_tasks = len(cfg.num_classes) time_now = time.time() loss_sum =",
"in range(num_tasks): summary_writer.add_scalar( 'train/loss_{}'.format(label_header[t]), loss_sum[t], summary['step']) summary_writer.add_scalar( 'train/acc_{}'.format(label_header[t]), acc_sum[t], summary['step'])",
"in range(len(cfg.num_classes)): summary_writer.add_scalar( 'dev/loss_{}'.format(dev_header[t]), summary_dev['loss'][t], summary['step']) summary_writer.add_scalar( 'dev/acc_{}'.format(dev_header[t]), summary_dev['acc'][t], summary['step'])",
") best_dict['best_idx'] += 1 if best_dict['best_idx'] > cfg.save_top_k: best_dict['best_idx'] =",
") if args.verbose is True: from torchsummary import summary if",
"rc != 0: raise Exception('Copy folder error : {}'.format(rc)) rc,",
"from torchsummary import summary if cfg.fix_ratio: h, w = cfg.long_side,",
"mean_loss <= best_dict['loss_dev_best']: best_dict['loss_dev_best'] = mean_loss if cfg.best_target == 'loss':",
"0} summary_dev = {'loss': float('inf'), 'acc': 0.0} summary_writer = SummaryWriter(args.save_path)",
"ImageDataset(cfg.train_csv, cfg, mode='train'), batch_size=cfg.train_batch_size, num_workers=args.num_workers, drop_last=True, shuffle=True) dataloader_dev = DataLoader(",
"loss_sum = np.zeros(num_tasks) acc_sum = np.zeros(num_tasks) predlist = list(x for",
"= [] for i in range(len(cfg.num_classes)): y_pred = predlist[i] y_true",
"loss.backward() optimizer.step() summary['step'] += 1 if summary['step'] % cfg.log_every ==",
"''Run Time : {:.2f} sec' .format( time.strftime(\"%Y-%m-%d %H:%M:%S\"), summary['step'], loss_dev_str,",
"loss_dev_str = ' '.join(map(lambda x: '{:.5f}'.format(x), summary_dev['loss'])) acc_dev_str = '",
"model.module.state_dict()}, os.path.join(args.save_path, 'best{}.ckpt'.format(best_dict['best_idx'])) ) best_dict['best_idx'] += 1 if best_dict['best_idx'] >",
"import copyfile import numpy as np from sklearn import metrics",
"1) for i in output.T] # different number of tasks",
"best_dict, dev_header) time_now = time.time() summary_dev, predlist, true_list = test_epoch("
] |
[
"groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for",
"in groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i)",
"input() groups = list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 =",
"tmpArray2 = set() for i in groups: if i in",
"if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i",
"set() tmpArray2 = set() for i in groups: if i",
"= set() tmpArray2 = set() for i in groups: if",
"tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in tmpArray2: print(i)",
"= list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 = set() for",
"for i in groups: if i in tmpArray1: tmpArray2.discard(i) else:",
"'))) tmpArray1 = set() tmpArray2 = set() for i in",
"groupSize = input() groups = list(map(int,input().split(' '))) tmpArray1 = set()",
"groups = list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 = set()",
"= set() for i in groups: if i in tmpArray1:",
"i in groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i)",
"set() for i in groups: if i in tmpArray1: tmpArray2.discard(i)",
"in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in tmpArray2:",
"i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in",
"tmpArray1 = set() tmpArray2 = set() for i in groups:",
"= input() groups = list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2",
"list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 = set() for i"
] |
[
"from hf_src.main import soma class TestSoma(unittest.TestCase): def test_retorno_soma_15_30(self): self.assertEqual(soma(15, 30),",
"unittest from hf_src.main import soma class TestSoma(unittest.TestCase): def test_retorno_soma_15_30(self): self.assertEqual(soma(15,",
"import unittest from hf_src.main import soma class TestSoma(unittest.TestCase): def test_retorno_soma_15_30(self):",
"hf_src.main import soma class TestSoma(unittest.TestCase): def test_retorno_soma_15_30(self): self.assertEqual(soma(15, 30), 45)"
] |
[
"for phase in flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self, client_cls, config,",
"except Exception: raise conv.position = url conv.last_response = _resp conv.last_content",
"= _cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response",
"for the HTTP _client :return: A cls or ErrorResponse instance",
"for param in [\"tests\", \"block\", \"mode\", \"expect_exception\"]: try: res[param] =",
"kid_template = \"a%d\" kid = 0 for typ, info in",
"\"block\", \"mode\", \"expect_exception\"]: try: res[param] = _flow[param] except KeyError: pass",
"not significant for the election process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\",",
"definitions \"\"\" sequence = flow2sequence(self.test_defs, flow) res = {\"sequence\": sequence,",
"== \"RegistrationRequest\": _register = False except TypeError: pass if _register:",
"args = {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) #",
"if any :param body_type: The format of the body of",
"from oic.utils.keyio import KeyBundle __author__ = 'roland' import logging logger",
"except KeyError: pass else: # export JWKS f = open(\"export/jwk.json\",",
"_response = _cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return",
"> status: status = item[\"status\"] if status == 0: status",
"json from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from",
"\"post\": []}, \"flow\": [flow], \"block\": [], \"mode\": \"\", \"expect_exception\": False}",
"in self.test_features and \\ \"registration\" not in test_spec[\"block\"]: _register =",
"add_init(self, test_spec): \"\"\" Add _client registration and provider info gathering",
"= 0 for typ, info in key_conf.items(): kb = KeyBundle(source=\"file://%s\"",
"body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response def test_summation(conv, sid):",
"= kid_template % kid kid += 1 _client.kid[k.use][k.kty] = k.kid",
"op_spec) _flow.insert(0, \"provider-discovery\") return test_spec def request_and_return(conv, url, response=None, method=\"GET\",",
"try: jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass else: #",
"make_sequence(self, flow): \"\"\" Translate a flow name into a sequence",
"{} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour",
"copy.copy(kwargs[\"preferences\"]) except KeyError: pass else: _key_set.discard(\"preferences\") if \"client_info\" in _key_set:",
"Add _client registration and provider info gathering if necessary :param",
"= False except TypeError: pass if _register: _ext = self.test_defs.PHASES[\"oic-registration\"]",
"copy import json from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import",
"if item[\"status\"] > status: status = item[\"status\"] if status ==",
"_key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"]",
"= 'roland' import logging logger = logging.getLogger(__name__) class OIDCError(Exception): pass",
"item[\"status\"] > status: status = item[\"status\"] if status == 0:",
":param body_type: The format of the body of the return",
"_flow = self.test_defs.FLOWS[flow] for param in [\"tests\", \"block\", \"mode\", \"expect_exception\"]:",
"{} _cli = conv._client try: _resp = _cli.http_request(url, method, data=body,",
"response instance if no response body was expected. \"\"\" if",
"from oic.utils.keyio import KeyJar from oic.utils.keyio import KeyBundle __author__ =",
"= test_defs def create_client(self, **kwargs): \"\"\" Instantiate a _client instance",
"a sequence of request/responses. :param flow: Which test flow to",
"import copy import json from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio",
"if necessary :param test_spec: :return: \"\"\" _seq = test_spec[\"sequence\"] _flow",
"first item in the sequence for sq in _seq: try:",
"= k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks = {\"keys\": []} for",
"_key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set: reg_info",
"flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self, client_cls, config, test_defs): \"\"\" :param",
"response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\" :param url:",
"response body was expected. \"\"\" if http_args is None: http_args",
"method: Which HTTP method to use :param body: A message",
"\"\"\" self.client_cls = client_cls self.config = config self.test_features = []",
"= [] kid_template = \"a%d\" kid = 0 for typ,",
"k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks = {\"keys\": []} for kb",
"!= 'oct']) return jwks def make_sequence(self, flow): \"\"\" Translate a",
"k.kid = kid_template % kid kid += 1 _client.kid[k.use][k.kty] =",
"for sq in _seq: try: if sq[0].request == \"RegistrationRequest\": _register",
"op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in _seq: _seq.insert(0, op_spec)",
"test_spec def request_and_return(conv, url, response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None,",
"operations.FLOWS[item] return [operations.PHASES[phase] for phase in flow[\"sequence\"]] class OIDCTestSetup(object): def",
"def construct_jwks(_client, key_conf): \"\"\" Construct the jwks \"\"\" if _client.keyjar",
"request/responses. :param flow: Which test flow to use :return: test",
"sid): status = 0 for item in conv.test_output: if item[\"status\"]",
"Translate a flow name into a sequence of request/responses. :param",
"True # May not be the first item in the",
"k.kty != 'oct']) return jwks def make_sequence(self, flow): \"\"\" Translate",
"Exception: raise conv.position = url conv.last_response = _resp conv.last_content =",
"for k in kb.keys(): k.serialize() k.kid = kid_template % kid",
"_client registration and provider info gathering if necessary :param test_spec:",
"[], \"post\": []}, \"flow\": [flow], \"block\": [], \"mode\": \"\", \"expect_exception\":",
"in _seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return test_spec def request_and_return(conv,",
"kbl = [] kid_template = \"a%d\" kid = 0 for",
"sq[0].request == \"RegistrationRequest\": _register = False except TypeError: pass if",
"to which the request should be sent :param response: Response",
"\"provider_info\". \"keys] :return: _client instance \"\"\" _key_set = set(kwargs.keys()) args",
"and \\ \"registration\" not in test_spec[\"block\"]: _register = True #",
"\"\"\" if http_args is None: http_args = {} _cli =",
"the sequence for sq in _seq: try: if sq[0].request ==",
"item[\"status\"] if status == 0: status = 1 info =",
"_client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour parameter",
"k in kb.keys() if k.kty != 'oct']) return jwks def",
"any :param body_type: The format of the body of the",
"f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try: _client.client_prefs =",
"http_args is None: http_args = {} _cli = conv._client try:",
"body_type: The format of the body of the return message",
"self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris",
"\"client_registration\" in _key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id",
"is not significant for the election process _key_set.discard(\"behaviour\") try: setattr(_client,",
"behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour parameter is not significant",
"and test definitions \"\"\" sequence = flow2sequence(self.test_defs, flow) res =",
"return res def add_init(self, test_spec): \"\"\" Add _client registration and",
"self.test_features = [] self.client = self.create_client(**config.CLIENT) self.test_defs = test_defs def",
"\"srv_discovery_url\" in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in",
"= {\"sequence\": sequence, \"tests\": {\"pre\": [], \"post\": []}, \"flow\": [flow],",
"are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys] :return: _client instance \"\"\"",
"'oct']) return jwks def make_sequence(self, flow): \"\"\" Translate a flow",
"_client instance :param: Keyword arguments Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\",",
"from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from oic.utils.keyio",
"the return message :param http_args: Arguments for the HTTP _client",
"import KeyJar from oic.utils.keyio import KeyBundle __author__ = 'roland' import",
"Which HTTP method to use :param body: A message body",
"import logging logger = logging.getLogger(__name__) class OIDCError(Exception): pass def flow2sequence(operations,",
"election process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError: pass",
"[\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys] :return: _client instance \"\"\" _key_set",
"Response type :param method: Which HTTP method to use :param",
"0 for item in conv.test_output: if item[\"status\"] > status: status",
"http_args = {} _cli = conv._client try: _resp = _cli.http_request(url,",
"test definitions \"\"\" sequence = flow2sequence(self.test_defs, flow) res = {\"sequence\":",
"_client @staticmethod def construct_jwks(_client, key_conf): \"\"\" Construct the jwks \"\"\"",
"_register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\"",
"try: setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError: pass else: _key_set.discard(\"allow\") try:",
"use :return: test sequence and test definitions \"\"\" sequence =",
"% info[\"key\"], fileformat=\"der\", keytype=typ) for k in kb.keys(): k.serialize() k.kid",
"self.client_cls = client_cls self.config = config self.test_features = [] self.client",
"conv.last_content = _resp.content if not \"keyjar\" in kwargs: kwargs[\"keyjar\"] =",
"return jwks def make_sequence(self, flow): \"\"\" Translate a flow name",
"in kb.keys(): k.serialize() k.kid = kid_template % kid kid +=",
"= True # May not be the first item in",
"info[\"key\"], fileformat=\"der\", keytype=typ) for k in kb.keys(): k.serialize() k.kid =",
"test sequence and test definitions \"\"\" sequence = flow2sequence(self.test_defs, flow)",
"= set(kwargs.keys()) args = {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL,",
"self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass else: # export JWKS f",
"= _key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError: pass else:",
"_resp.content)) return _response def test_summation(conv, sid): status = 0 for",
"\"RegistrationRequest\": _register = False except TypeError: pass if _register: _ext",
"if _client.keyjar is None: _client.keyjar = KeyJar() kbl = []",
"pass else: # export JWKS f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks))",
"conv._client try: _resp = _cli.http_request(url, method, data=body, **http_args) except Exception:",
"= _resp.content if not \"keyjar\" in kwargs: kwargs[\"keyjar\"] = conv.keyjar",
"= test_spec[\"flow\"] if \"client_info\" in self.test_features and \\ \"registration\" not",
"to use :param body: A message body if any :param",
"KeyError: pass else: _key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except",
"\"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris =",
"Keyword arguments Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys] :return:",
"% kid kid += 1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb)",
"HTTP method to use :param body: A message body if",
"TypeError: pass if _register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0,",
"arguments Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys] :return: _client",
"\"mode\": \"\", \"expect_exception\": False} _flow = self.test_defs.FLOWS[flow] for param in",
"_seq: try: if sq[0].request == \"RegistrationRequest\": _register = False except",
":return: _client instance \"\"\" _key_set = set(kwargs.keys()) args = {}",
"_ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in",
"oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from oic.utils.keyio import",
"self.test_defs.FLOWS[flow] for param in [\"tests\", \"block\", \"mode\", \"expect_exception\"]: try: res[param]",
"test_spec): \"\"\" Add _client registration and provider info gathering if",
"jwks = {\"keys\": []} for kb in kbl: # ignore",
"in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in _seq:",
"in [\"tests\", \"block\", \"mode\", \"expect_exception\"]: try: res[param] = _flow[param] except",
"if http_args is None: http_args = {} _cli = conv._client",
"= reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return _client",
"\"client_info\" in self.test_features and \\ \"registration\" not in test_spec[\"block\"]: _register",
"[] self.client = self.create_client(**config.CLIENT) self.test_defs = test_defs def create_client(self, **kwargs):",
"key_conf): \"\"\" Construct the jwks \"\"\" if _client.keyjar is None:",
"KeyJar from oic.utils.keyio import KeyBundle __author__ = 'roland' import logging",
"= copy.copy(kwargs[\"preferences\"]) except KeyError: pass else: _key_set.discard(\"preferences\") if \"client_info\" in",
"= self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass else: # export JWKS",
"conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content))",
"pass if _register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\")",
"if op_spec not in _seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return",
"or ErrorResponse instance or the HTTP response instance if no",
"try: _resp = _cli.http_request(url, method, data=body, **http_args) except Exception: raise",
"\"\", \"expect_exception\": False} _flow = self.test_defs.FLOWS[flow] for param in [\"tests\",",
"in _key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id =",
"method, data=body, **http_args) except Exception: raise conv.position = url conv.last_response",
"__init__(self, client_cls, config, test_defs): \"\"\" :param config: Imported configuration module",
"for typ, info in key_conf.items(): kb = KeyBundle(source=\"file://%s\" % info[\"key\"],",
"\"\"\" Translate a flow name into a sequence of request/responses.",
"self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError:",
"the jwks \"\"\" if _client.keyjar is None: _client.keyjar = KeyJar()",
"= {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The",
"state=\"\", http_args=None, **kwargs): \"\"\" :param url: The URL to which",
"_key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError: pass else: _key_set.discard(\"allow\")",
"behaviour parameter is not significant for the election process _key_set.discard(\"behaviour\")",
"in _key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set:",
"test_spec[\"block\"]: _register = True # May not be the first",
"\"\"\" Instantiate a _client instance :param: Keyword arguments Keys are",
"config: Imported configuration module :return: \"\"\" self.client_cls = client_cls self.config",
"\"client_info\" in _key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in",
"\"\"\" sequence = flow2sequence(self.test_defs, flow) res = {\"sequence\": sequence, \"tests\":",
"KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ) for k in kb.keys(): k.serialize()",
"= self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret =",
"\"expect_exception\"]: try: res[param] = _flow[param] except KeyError: pass return res",
"if not \"keyjar\" in kwargs: kwargs[\"keyjar\"] = conv.keyjar _response =",
"phase in flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self, client_cls, config, test_defs):",
"not \"keyjar\" in kwargs: kwargs[\"keyjar\"] = conv.keyjar _response = _cli.parse_request_response(_resp,",
"should be sent :param response: Response type :param method: Which",
"key_conf.items(): kb = KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ) for k",
"\"\"\" _key_set = set(kwargs.keys()) args = {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD,",
"self.test_features = _key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError: pass",
"registration and provider info gathering if necessary :param test_spec: :return:",
"kwargs[\"keys\"]) except KeyError: pass else: # export JWKS f =",
"try: if sq[0].request == \"RegistrationRequest\": _register = False except TypeError:",
"res = {\"sequence\": sequence, \"tests\": {\"pre\": [], \"post\": []}, \"flow\":",
"= self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set: reg_info = self.config.CLIENT[\"client_registration\"]",
"jwks \"\"\" if _client.keyjar is None: _client.keyjar = KeyJar() kbl",
"\"\"\" :param config: Imported configuration module :return: \"\"\" self.client_cls =",
"instance or the HTTP response instance if no response body",
"\"oic-registration\") if \"srv_discovery_url\" in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec",
"[operations.PHASES[phase] for phase in flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self, client_cls,",
"in kwargs: kwargs[\"keyjar\"] = conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type,",
"if \"client_info\" in self.test_features and \\ \"registration\" not in test_spec[\"block\"]:",
"kwargs[\"keyjar\"] = conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type, state, **kwargs)",
"sequence, \"tests\": {\"pre\": [], \"post\": []}, \"flow\": [flow], \"block\": [],",
"the HTTP response instance if no response body was expected.",
"= open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features =",
"kbl.append(kb) jwks = {\"keys\": []} for kb in kbl: #",
"test_defs def create_client(self, **kwargs): \"\"\" Instantiate a _client instance :param:",
"instance \"\"\" _key_set = set(kwargs.keys()) args = {} _client =",
"the HTTP _client :return: A cls or ErrorResponse instance or",
"# ignore simple keys jwks[\"keys\"].extend([k.to_dict() for k in kb.keys() if",
"name into a sequence of request/responses. :param flow: Which test",
"request_and_return(conv, url, response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\"",
"= client_cls self.config = config self.test_features = [] self.client =",
"test_spec: :return: \"\"\" _seq = test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if",
"{\"keys\": []} for kb in kbl: # ignore simple keys",
"\"\"\" :param url: The URL to which the request should",
"test_spec[\"flow\"] if \"client_info\" in self.test_features and \\ \"registration\" not in",
":return: \"\"\" self.client_cls = client_cls self.config = config self.test_features =",
"kid kid += 1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb)",
"_register = True # May not be the first item",
"1 info = { \"id\": sid, \"status\": status, \"tests\": conv.test_output",
"url, response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\" :param",
"flow) res = {\"sequence\": sequence, \"tests\": {\"pre\": [], \"post\": []},",
"flow): \"\"\" Translate a flow name into a sequence of",
"the request should be sent :param response: Response type :param",
":param body: A message body if any :param body_type: The",
"jwks def make_sequence(self, flow): \"\"\" Translate a flow name into",
"expected. \"\"\" if http_args is None: http_args = {} _cli",
":param flow: Which test flow to use :return: test sequence",
"sent :param response: Response type :param method: Which HTTP method",
"ErrorResponse instance or the HTTP response instance if no response",
":param test_spec: :return: \"\"\" _seq = test_spec[\"sequence\"] _flow = test_spec[\"flow\"]",
"module :return: \"\"\" self.client_cls = client_cls self.config = config self.test_features",
"@staticmethod def construct_jwks(_client, key_conf): \"\"\" Construct the jwks \"\"\" if",
"= reg_info[\"client_secret\"] return _client @staticmethod def construct_jwks(_client, key_conf): \"\"\" Construct",
"flow: Which test flow to use :return: test sequence and",
"return test_spec def request_and_return(conv, url, response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\",",
"be sent :param response: Response type :param method: Which HTTP",
"raise conv.position = url conv.last_response = _resp conv.last_content = _resp.content",
"flow = operations.FLOWS[item] return [operations.PHASES[phase] for phase in flow[\"sequence\"]] class",
"jwks[\"keys\"].extend([k.to_dict() for k in kb.keys() if k.kty != 'oct']) return",
"f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try: _client.client_prefs",
"conv.last_response = _resp conv.last_content = _resp.content if not \"keyjar\" in",
"body: A message body if any :param body_type: The format",
"pass def flow2sequence(operations, item): flow = operations.FLOWS[item] return [operations.PHASES[phase] for",
"{\"sequence\": sequence, \"tests\": {\"pre\": [], \"post\": []}, \"flow\": [flow], \"block\":",
"_client.keyjar = KeyJar() kbl = [] kid_template = \"a%d\" kid",
"\"\"\" _seq = test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if \"client_info\" in",
"data=body, **http_args) except Exception: raise conv.position = url conv.last_response =",
"status = 1 info = { \"id\": sid, \"status\": status,",
"test_summation(conv, sid): status = 0 for item in conv.test_output: if",
"import json from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar",
"body of the return message :param http_args: Arguments for the",
"return message :param http_args: Arguments for the HTTP _client :return:",
"_response def test_summation(conv, sid): status = 0 for item in",
"construct_jwks(_client, key_conf): \"\"\" Construct the jwks \"\"\" if _client.keyjar is",
"item in conv.test_output: if item[\"status\"] > status: status = item[\"status\"]",
"was expected. \"\"\" if http_args is None: http_args = {}",
"for kb in kbl: # ignore simple keys jwks[\"keys\"].extend([k.to_dict() for",
"_client :return: A cls or ErrorResponse instance or the HTTP",
"ignore simple keys jwks[\"keys\"].extend([k.to_dict() for k in kb.keys() if k.kty",
"into a sequence of request/responses. :param flow: Which test flow",
"== 0: status = 1 info = { \"id\": sid,",
"info gathering if necessary :param test_spec: :return: \"\"\" _seq =",
"self.test_defs = test_defs def create_client(self, **kwargs): \"\"\" Instantiate a _client",
"sequence for sq in _seq: try: if sq[0].request == \"RegistrationRequest\":",
"_client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks = {\"keys\": []}",
"client_cls, config, test_defs): \"\"\" :param config: Imported configuration module :return:",
"param in [\"tests\", \"block\", \"mode\", \"expect_exception\"]: try: res[param] = _flow[param]",
"_resp = _cli.http_request(url, method, data=body, **http_args) except Exception: raise conv.position",
"return _client @staticmethod def construct_jwks(_client, key_conf): \"\"\" Construct the jwks",
"[], \"mode\": \"\", \"expect_exception\": False} _flow = self.test_defs.FLOWS[flow] for param",
"except KeyError: pass else: _key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client, kwargs[\"keys\"])",
"_client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return",
"URL to which the request should be sent :param response:",
"self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"]",
"_client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\" in _key_set: reg_info =",
"in kbl: # ignore simple keys jwks[\"keys\"].extend([k.to_dict() for k in",
"False} _flow = self.test_defs.FLOWS[flow] for param in [\"tests\", \"block\", \"mode\",",
"_client.keyjar is None: _client.keyjar = KeyJar() kbl = [] kid_template",
"conv.test_output: if item[\"status\"] > status: status = item[\"status\"] if status",
"\"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try:",
"0 for typ, info in key_conf.items(): kb = KeyBundle(source=\"file://%s\" %",
"\"client_info\", \"client_registration\", \"provider_info\". \"keys] :return: _client instance \"\"\" _key_set =",
"http_args=None, **kwargs): \"\"\" :param url: The URL to which the",
"Imported configuration module :return: \"\"\" self.client_cls = client_cls self.config =",
"body if any :param body_type: The format of the body",
"a _client instance :param: Keyword arguments Keys are [\"srv_discovery_url\", \"client_info\",",
"if _register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if",
"sequence of request/responses. :param flow: Which test flow to use",
"no response body was expected. \"\"\" if http_args is None:",
"try: res[param] = _flow[param] except KeyError: pass return res def",
"else: _key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass",
"if k.kty != 'oct']) return jwks def make_sequence(self, flow): \"\"\"",
"be the first item in the sequence for sq in",
"open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set",
"HTTP _client :return: A cls or ErrorResponse instance or the",
"Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys] :return: _client instance",
"def create_client(self, **kwargs): \"\"\" Instantiate a _client instance :param: Keyword",
"\"keys] :return: _client instance \"\"\" _key_set = set(kwargs.keys()) args =",
"format of the body of the return message :param http_args:",
"None: http_args = {} _cli = conv._client try: _resp =",
"**kwargs): \"\"\" :param url: The URL to which the request",
"= config self.test_features = [] self.client = self.create_client(**config.CLIENT) self.test_defs =",
"oic.utils.keyio import KeyJar from oic.utils.keyio import KeyBundle __author__ = 'roland'",
":param url: The URL to which the request should be",
"= _cli.http_request(url, method, data=body, **http_args) except Exception: raise conv.position =",
"is None: _client.keyjar = KeyJar() kbl = [] kid_template =",
"{ \"id\": sid, \"status\": status, \"tests\": conv.test_output } return info",
"import KeyBundle __author__ = 'roland' import logging logger = logging.getLogger(__name__)",
"verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour parameter is not significant for",
"0: status = 1 info = { \"id\": sid, \"status\":",
"create_client(self, **kwargs): \"\"\" Instantiate a _client instance :param: Keyword arguments",
"response: Response type :param method: Which HTTP method to use",
"\"expect_exception\": False} _flow = self.test_defs.FLOWS[flow] for param in [\"tests\", \"block\",",
"_cli = conv._client try: _resp = _cli.http_request(url, method, data=body, **http_args)",
"[flow], \"block\": [], \"mode\": \"\", \"expect_exception\": False} _flow = self.test_defs.FLOWS[flow]",
"= [] self.client = self.create_client(**config.CLIENT) self.test_defs = test_defs def create_client(self,",
"import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from oic.utils.keyio import KeyBundle",
"_key_set.discard(\"preferences\") if \"client_info\" in _key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif",
"k in kb.keys(): k.serialize() k.kid = kid_template % kid kid",
":return: test sequence and test definitions \"\"\" sequence = flow2sequence(self.test_defs,",
"test flow to use :return: test sequence and test definitions",
"the body of the return message :param http_args: Arguments for",
"k.serialize() k.kid = kid_template % kid kid += 1 _client.kid[k.use][k.kty]",
"# May not be the first item in the sequence",
"Instantiate a _client instance :param: Keyword arguments Keys are [\"srv_discovery_url\",",
"type :param method: Which HTTP method to use :param body:",
"kid = 0 for typ, info in key_conf.items(): kb =",
"keys jwks[\"keys\"].extend([k.to_dict() for k in kb.keys() if k.kty != 'oct'])",
"pass else: _key_set.discard(\"preferences\") if \"client_info\" in _key_set: _client.redirect_uris = self.config.CLIENT[",
"of request/responses. :param flow: Which test flow to use :return:",
"status == 0: status = 1 info = { \"id\":",
"\"flow\": [flow], \"block\": [], \"mode\": \"\", \"expect_exception\": False} _flow =",
"try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError: pass else: _key_set.discard(\"preferences\") if",
"sequence and test definitions \"\"\" sequence = flow2sequence(self.test_defs, flow) res",
"instance :param: Keyword arguments Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\".",
"None: _client.keyjar = KeyJar() kbl = [] kid_template = \"a%d\"",
"_seq = test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if \"client_info\" in self.test_features",
"OIDCError(Exception): pass def flow2sequence(operations, item): flow = operations.FLOWS[item] return [operations.PHASES[phase]",
"'roland' import logging logger = logging.getLogger(__name__) class OIDCError(Exception): pass def",
"http_args: Arguments for the HTTP _client :return: A cls or",
"flow name into a sequence of request/responses. :param flow: Which",
"= self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except",
"self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in _seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\")",
"status: status = item[\"status\"] if status == 0: status =",
"_seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return test_spec def request_and_return(conv, url, response=None,",
"KeyBundle __author__ = 'roland' import logging logger = logging.getLogger(__name__) class",
"elif \"client_registration\" in _key_set: reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"]",
"**http_args) except Exception: raise conv.position = url conv.last_response = _resp",
"message body if any :param body_type: The format of the",
"= self.create_client(**config.CLIENT) self.test_defs = test_defs def create_client(self, **kwargs): \"\"\" Instantiate",
"request should be sent :param response: Response type :param method:",
"= { \"id\": sid, \"status\": status, \"tests\": conv.test_output } return",
"def test_summation(conv, sid): status = 0 for item in conv.test_output:",
"self.create_client(**config.CLIENT) self.test_defs = test_defs def create_client(self, **kwargs): \"\"\" Instantiate a",
"test_defs): \"\"\" :param config: Imported configuration module :return: \"\"\" self.client_cls",
"return [operations.PHASES[phase] for phase in flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self,",
"fileformat=\"der\", keytype=typ) for k in kb.keys(): k.serialize() k.kid = kid_template",
"OIDCTestSetup(object): def __init__(self, client_cls, config, test_defs): \"\"\" :param config: Imported",
"def add_init(self, test_spec): \"\"\" Add _client registration and provider info",
"__author__ = 'roland' import logging logger = logging.getLogger(__name__) class OIDCError(Exception):",
"kb) kbl.append(kb) jwks = {\"keys\": []} for kb in kbl:",
"May not be the first item in the sequence for",
"url conv.last_response = _resp conv.last_content = _resp.content if not \"keyjar\"",
"[]} for kb in kbl: # ignore simple keys jwks[\"keys\"].extend([k.to_dict()",
"_client.client_id = reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return _client @staticmethod def",
"config, test_defs): \"\"\" :param config: Imported configuration module :return: \"\"\"",
"and provider info gathering if necessary :param test_spec: :return: \"\"\"",
"_flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if",
"kwargs: kwargs[\"keyjar\"] = conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type, state,",
"except KeyError: pass return res def add_init(self, test_spec): \"\"\" Add",
"info in key_conf.items(): kb = KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ)",
"self.config = config self.test_features = [] self.client = self.create_client(**config.CLIENT) self.test_defs",
":return: A cls or ErrorResponse instance or the HTTP response",
"_client instance \"\"\" _key_set = set(kwargs.keys()) args = {} _client",
"= self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in self.test_features:",
"_resp.content if not \"keyjar\" in kwargs: kwargs[\"keyjar\"] = conv.keyjar _response",
"self.client = self.create_client(**config.CLIENT) self.test_defs = test_defs def create_client(self, **kwargs): \"\"\"",
"def request_and_return(conv, url, response=None, method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs):",
"for item in conv.test_output: if item[\"status\"] > status: status =",
"kid += 1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks",
"which the request should be sent :param response: Response type",
"KeyJar() kbl = [] kid_template = \"a%d\" kid = 0",
"of the body of the return message :param http_args: Arguments",
"kb.keys(): k.serialize() k.kid = kid_template % kid kid += 1",
"= item[\"status\"] if status == 0: status = 1 info",
"= conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response,",
"JWKS f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"]",
"= conv._client try: _resp = _cli.http_request(url, method, data=body, **http_args) except",
"= flow2sequence(self.test_defs, flow) res = {\"sequence\": sequence, \"tests\": {\"pre\": [],",
"= logging.getLogger(__name__) class OIDCError(Exception): pass def flow2sequence(operations, item): flow =",
"= operations.FLOWS[item] return [operations.PHASES[phase] for phase in flow[\"sequence\"]] class OIDCTestSetup(object):",
"else: # export JWKS f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close()",
"\"client_registration\", \"provider_info\". \"keys] :return: _client instance \"\"\" _key_set = set(kwargs.keys())",
"\"a%d\" kid = 0 for typ, info in key_conf.items(): kb",
"self.test_features and \\ \"registration\" not in test_spec[\"block\"]: _register = True",
"body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\" :param url: The URL",
"= KeyJar() kbl = [] kid_template = \"a%d\" kid =",
"return _response def test_summation(conv, sid): status = 0 for item",
"config self.test_features = [] self.client = self.create_client(**config.CLIENT) self.test_defs = test_defs",
"\"\"\" if _client.keyjar is None: _client.keyjar = KeyJar() kbl =",
"_flow.insert(0, \"provider-discovery\") return test_spec def request_and_return(conv, url, response=None, method=\"GET\", body=None,",
"body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\" :param url: The URL to",
"logger = logging.getLogger(__name__) class OIDCError(Exception): pass def flow2sequence(operations, item): flow",
"item in the sequence for sq in _seq: try: if",
"export JWKS f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri =",
"= self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour parameter is",
"Construct the jwks \"\"\" if _client.keyjar is None: _client.keyjar =",
"if no response body was expected. \"\"\" if http_args is",
"reg_info[\"client_secret\"] return _client @staticmethod def construct_jwks(_client, key_conf): \"\"\" Construct the",
"res def add_init(self, test_spec): \"\"\" Add _client registration and provider",
"self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in self.test_features: op_spec",
"_key_set = set(kwargs.keys()) args = {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"],",
"_cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response def",
"typ, info in key_conf.items(): kb = KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\",",
"The behaviour parameter is not significant for the election process",
"oic.utils.keyio import KeyBundle __author__ = 'roland' import logging logger =",
"except KeyError: pass else: _key_set.discard(\"preferences\") if \"client_info\" in _key_set: _client.redirect_uris",
"is None: http_args = {} _cli = conv._client try: _resp",
"_resp conv.last_content = _resp.content if not \"keyjar\" in kwargs: kwargs[\"keyjar\"]",
"pass else: _key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError:",
"in _seq: try: if sq[0].request == \"RegistrationRequest\": _register = False",
"_cli.http_request(url, method, data=body, **http_args) except Exception: raise conv.position = url",
"_seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return test_spec def request_and_return(conv, url,",
"set(kwargs.keys()) args = {} _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args)",
"conv.protocol_response.append((_response, _resp.content)) return _response def test_summation(conv, sid): status = 0",
"kb = KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ) for k in",
"url: The URL to which the request should be sent",
"reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return _client @staticmethod def construct_jwks(_client, key_conf):",
"KeyError: pass else: # export JWKS f = open(\"export/jwk.json\", \"w\")",
"not in test_spec[\"block\"]: _register = True # May not be",
"= test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if \"client_info\" in self.test_features and",
":return: \"\"\" _seq = test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if \"client_info\"",
"a flow name into a sequence of request/responses. :param flow:",
"_client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features = _key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"])",
"self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in _seq: _seq.insert(0,",
"if \"client_info\" in _key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"] elif \"client_registration\"",
"self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD, behaviour=kwargs[\"behaviour\"], verify_ssl=self.config.VERIFY_SSL, **args) # The behaviour parameter is not",
"[]}, \"flow\": [flow], \"block\": [], \"mode\": \"\", \"expect_exception\": False} _flow",
"= {\"keys\": []} for kb in kbl: # ignore simple",
"flow to use :return: test sequence and test definitions \"\"\"",
"the election process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError:",
"provider info gathering if necessary :param test_spec: :return: \"\"\" _seq",
"\"registration\" not in test_spec[\"block\"]: _register = True # May not",
"client_cls self.config = config self.test_features = [] self.client = self.create_client(**config.CLIENT)",
"= self.test_defs.FLOWS[flow] for param in [\"tests\", \"block\", \"mode\", \"expect_exception\"]: try:",
"The URL to which the request should be sent :param",
"sq in _seq: try: if sq[0].request == \"RegistrationRequest\": _register =",
"= 0 for item in conv.test_output: if item[\"status\"] > status:",
"reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return _client @staticmethod",
"= \"a%d\" kid = 0 for typ, info in key_conf.items():",
"# export JWKS f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri",
"def flow2sequence(operations, item): flow = operations.FLOWS[item] return [operations.PHASES[phase] for phase",
"# The behaviour parameter is not significant for the election",
"_key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass else:",
"= KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ) for k in kb.keys():",
"Arguments for the HTTP _client :return: A cls or ErrorResponse",
"**kwargs): \"\"\" Instantiate a _client instance :param: Keyword arguments Keys",
"to use :return: test sequence and test definitions \"\"\" sequence",
"sequence = flow2sequence(self.test_defs, flow) res = {\"sequence\": sequence, \"tests\": {\"pre\":",
"instance if no response body was expected. \"\"\" if http_args",
"setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError: pass else: _key_set.discard(\"allow\") try: jwks",
":param method: Which HTTP method to use :param body: A",
"keytype=typ) for k in kb.keys(): k.serialize() k.kid = kid_template %",
"\\ \"registration\" not in test_spec[\"block\"]: _register = True # May",
"method to use :param body: A message body if any",
"= _resp conv.last_content = _resp.content if not \"keyjar\" in kwargs:",
"= 1 info = { \"id\": sid, \"status\": status, \"tests\":",
"test_spec[\"sequence\"] _flow = test_spec[\"flow\"] if \"client_info\" in self.test_features and \\",
"{\"pre\": [], \"post\": []}, \"flow\": [flow], \"block\": [], \"mode\": \"\",",
"_register = False except TypeError: pass if _register: _ext =",
"KeyError: pass else: _key_set.discard(\"preferences\") if \"client_info\" in _key_set: _client.redirect_uris =",
"_ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"]",
"process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"]) except KeyError: pass else:",
"configuration module :return: \"\"\" self.client_cls = client_cls self.config = config",
"_client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks = {\"keys\": []} for kb in",
":param: Keyword arguments Keys are [\"srv_discovery_url\", \"client_info\", \"client_registration\", \"provider_info\". \"keys]",
"in test_spec[\"block\"]: _register = True # May not be the",
"logging logger = logging.getLogger(__name__) class OIDCError(Exception): pass def flow2sequence(operations, item):",
"kwargs[\"allow\"]) except KeyError: pass else: _key_set.discard(\"allow\") try: jwks = self.construct_jwks(_client,",
"class OIDCError(Exception): pass def flow2sequence(operations, item): flow = operations.FLOWS[item] return",
"\"tests\": {\"pre\": [], \"post\": []}, \"flow\": [flow], \"block\": [], \"mode\":",
"of the return message :param http_args: Arguments for the HTTP",
"_flow[param] except KeyError: pass return res def add_init(self, test_spec): \"\"\"",
"parameter is not significant for the election process _key_set.discard(\"behaviour\") try:",
"= self.test_defs.PHASES[\"provider-discovery\"] if op_spec not in _seq: _seq.insert(0, op_spec) _flow.insert(0,",
"kb.keys() if k.kty != 'oct']) return jwks def make_sequence(self, flow):",
"\"allow\", kwargs[\"allow\"]) except KeyError: pass else: _key_set.discard(\"allow\") try: jwks =",
"flow2sequence(self.test_defs, flow) res = {\"sequence\": sequence, \"tests\": {\"pre\": [], \"post\":",
"= url conv.last_response = _resp conv.last_content = _resp.content if not",
"status = item[\"status\"] if status == 0: status = 1",
"reg_info = self.config.CLIENT[\"client_registration\"] _client.redirect_uris = reg_info[\"redirect_uris\"] _client.client_id = reg_info[\"client_id\"] _client.client_secret",
"False except TypeError: pass if _register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0,",
"\"mode\", \"expect_exception\"]: try: res[param] = _flow[param] except KeyError: pass return",
"if \"srv_discovery_url\" in self.test_features: op_spec = self.test_defs.PHASES[\"provider-discovery\"] if op_spec not",
"A cls or ErrorResponse instance or the HTTP response instance",
"**kwargs) conv.protocol_response.append((_response, _resp.content)) return _response def test_summation(conv, sid): status =",
"_flow = test_spec[\"flow\"] if \"client_info\" in self.test_features and \\ \"registration\"",
"else: _key_set.discard(\"preferences\") if \"client_info\" in _key_set: _client.redirect_uris = self.config.CLIENT[ \"client_info\"][\"redirect_uris\"]",
"in key_conf.items(): kb = KeyBundle(source=\"file://%s\" % info[\"key\"], fileformat=\"der\", keytype=typ) for",
"def __init__(self, client_cls, config, test_defs): \"\"\" :param config: Imported configuration",
"in the sequence for sq in _seq: try: if sq[0].request",
"_key_set try: _client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError: pass else: _key_set.discard(\"preferences\")",
"_client.client_prefs = copy.copy(kwargs[\"preferences\"]) except KeyError: pass else: _key_set.discard(\"preferences\") if \"client_info\"",
"def make_sequence(self, flow): \"\"\" Translate a flow name into a",
"res[param] = _flow[param] except KeyError: pass return res def add_init(self,",
"jwks = self.construct_jwks(_client, kwargs[\"keys\"]) except KeyError: pass else: # export",
"_seq.insert(0, _ext) _flow.insert(0, \"oic-registration\") if \"srv_discovery_url\" in self.test_features: op_spec =",
"cls or ErrorResponse instance or the HTTP response instance if",
"status = 0 for item in conv.test_output: if item[\"status\"] >",
":param config: Imported configuration module :return: \"\"\" self.client_cls = client_cls",
"\"block\": [], \"mode\": \"\", \"expect_exception\": False} _flow = self.test_defs.FLOWS[flow] for",
"method=\"GET\", body=None, body_type=\"json\", state=\"\", http_args=None, **kwargs): \"\"\" :param url: The",
"if status == 0: status = 1 info = {",
"flow2sequence(operations, item): flow = operations.FLOWS[item] return [operations.PHASES[phase] for phase in",
"info = { \"id\": sid, \"status\": status, \"tests\": conv.test_output }",
"conv.position = url conv.last_response = _resp conv.last_content = _resp.content if",
":param http_args: Arguments for the HTTP _client :return: A cls",
"simple keys jwks[\"keys\"].extend([k.to_dict() for k in kb.keys() if k.kty !=",
"op_spec not in _seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return test_spec",
"for k in kb.keys() if k.kty != 'oct']) return jwks",
"_client.client_secret = reg_info[\"client_secret\"] return _client @staticmethod def construct_jwks(_client, key_conf): \"\"\"",
"state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response def test_summation(conv, sid): status",
"response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response def test_summation(conv,",
"in flow[\"sequence\"]] class OIDCTestSetup(object): def __init__(self, client_cls, config, test_defs): \"\"\"",
":param response: Response type :param method: Which HTTP method to",
"use :param body: A message body if any :param body_type:",
"except TypeError: pass if _register: _ext = self.test_defs.PHASES[\"oic-registration\"] _seq.insert(0, _ext)",
"not in _seq: _seq.insert(0, op_spec) _flow.insert(0, \"provider-discovery\") return test_spec def",
"HTTP response instance if no response body was expected. \"\"\"",
"A message body if any :param body_type: The format of",
"\"keyjar\" in kwargs: kwargs[\"keyjar\"] = conv.keyjar _response = _cli.parse_request_response(_resp, response,",
"gathering if necessary :param test_spec: :return: \"\"\" _seq = test_spec[\"sequence\"]",
"= reg_info[\"client_id\"] _client.client_secret = reg_info[\"client_secret\"] return _client @staticmethod def construct_jwks(_client,",
"The format of the body of the return message :param",
"significant for the election process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"])",
"= _flow[param] except KeyError: pass return res def add_init(self, test_spec):",
"[] kid_template = \"a%d\" kid = 0 for typ, info",
"CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from oic.utils.keyio import KeyBundle __author__",
"kb in kbl: # ignore simple keys jwks[\"keys\"].extend([k.to_dict() for k",
"necessary :param test_spec: :return: \"\"\" _seq = test_spec[\"sequence\"] _flow =",
"body was expected. \"\"\" if http_args is None: http_args =",
"+= 1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks =",
"not be the first item in the sequence for sq",
"f = open(\"export/jwk.json\", \"w\") f.write(json.dumps(jwks)) f.close() _client.jwks_uri = self.config.CLIENT[\"key_export_url\"] self.test_features",
"KeyError: pass return res def add_init(self, test_spec): \"\"\" Add _client",
"the first item in the sequence for sq in _seq:",
"pass return res def add_init(self, test_spec): \"\"\" Add _client registration",
"Which test flow to use :return: test sequence and test",
"class OIDCTestSetup(object): def __init__(self, client_cls, config, test_defs): \"\"\" :param config:",
"or the HTTP response instance if no response body was",
"message :param http_args: Arguments for the HTTP _client :return: A",
"for the election process _key_set.discard(\"behaviour\") try: setattr(_client, \"allow\", kwargs[\"allow\"]) except",
"\"provider-discovery\") return test_spec def request_and_return(conv, url, response=None, method=\"GET\", body=None, body_type=\"json\",",
"logging.getLogger(__name__) class OIDCError(Exception): pass def flow2sequence(operations, item): flow = operations.FLOWS[item]",
"in kb.keys() if k.kty != 'oct']) return jwks def make_sequence(self,",
"= {} _cli = conv._client try: _resp = _cli.http_request(url, method,",
"item): flow = operations.FLOWS[item] return [operations.PHASES[phase] for phase in flow[\"sequence\"]]",
"if sq[0].request == \"RegistrationRequest\": _register = False except TypeError: pass",
"\"\"\" Construct the jwks \"\"\" if _client.keyjar is None: _client.keyjar",
"1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\", kb) kbl.append(kb) jwks = {\"keys\":",
"\"\"\" Add _client registration and provider info gathering if necessary",
"**args) # The behaviour parameter is not significant for the",
"kid_template % kid kid += 1 _client.kid[k.use][k.kty] = k.kid _client.keyjar.add_kb(\"\",",
"[\"tests\", \"block\", \"mode\", \"expect_exception\"]: try: res[param] = _flow[param] except KeyError:",
"in conv.test_output: if item[\"status\"] > status: status = item[\"status\"] if",
"kbl: # ignore simple keys jwks[\"keys\"].extend([k.to_dict() for k in kb.keys()"
] |
[
"= cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged =",
"hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged",
"= cms.bool(True), useExistingWeights = cms.bool(False), useExp = cms.bool(False), usePUProxyValue =",
"cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True),",
"= cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut = cms.int32(4), vtxZCut =",
"combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor",
"algos = cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0,",
"cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope",
"= cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0,",
"cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4),",
"= cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons =",
"cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr =",
"cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False),",
"cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False),",
"cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False),",
"= cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0),",
"cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False), useExp = cms.bool(False),",
"1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF",
"= cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0,",
"= cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr",
"= cms.double(1.0), useCharged = cms.bool(False) )) ) ), applyCHS =",
"cms.bool(False) )) ) ), applyCHS = cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"),",
"DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons",
"cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt",
"useExp = cms.bool(False), usePUProxyValue = cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut",
"etaMin = cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos =",
"as cms hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs =",
"= cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged =",
"puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False), useExp = cms.bool(False), usePUProxyValue",
"UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0),",
"= cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope =",
"cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0),",
"cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet(",
"EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105,",
"UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet( cms.PSet(",
"MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax",
"DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ",
"PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope",
"cms.double(1.0), useCharged = cms.bool(True) )) ), cms.PSet( EtaMaxExtrap = cms.double(2.0),",
"cms.bool(False), useExp = cms.bool(False), usePUProxyValue = cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"),",
"), applyCHS = cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False),",
"EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight",
"cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId",
"usePUProxyValue = cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut = cms.int32(4), vtxZCut",
"0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True),",
"= cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor =",
"cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0),",
"= cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged =",
"1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin",
"= cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos =",
"clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep",
"cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False) )) ) ),",
"= cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5,",
"cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.1),",
"= cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF =",
"etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId",
"cms hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2),",
"= cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax =",
"cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF =",
"FWCore.ParameterSet.Config as cms hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs",
"useCharged = cms.bool(False) )) ) ), applyCHS = cms.bool(True), candName",
"cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0),",
"= cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor =",
"= cms.double(1.0), useCharged = cms.bool(True) )) ), cms.PSet( EtaMaxExtrap =",
"= cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos =",
"= cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr =",
"vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut = cms.int32(4), vtxZCut = cms.double(24) )",
"cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0),",
"PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos",
"RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin =",
"cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0),",
"MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF",
"NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals",
"cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0),",
"useCharged = cms.bool(True) )) ), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF",
"= cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep =",
"applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin",
"= cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap",
"EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope",
"= cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821),",
"cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5),",
"puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False), useExp",
"puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt",
"= cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ =",
"cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5),",
"algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone",
"<gh_stars>1-10 import FWCore.ParameterSet.Config as cms hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut =",
"RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin",
"= cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight =",
"= cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals =",
"cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet(",
"cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5),",
"rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True) ))",
"useExistingWeights = cms.bool(False), useExp = cms.bool(False), usePUProxyValue = cms.bool(True), vertexName",
"cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0),",
"cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0),",
"MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope =",
"= cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False), useExp =",
"cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0),",
"= cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF",
"= cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0,",
"cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True),",
"= cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False) )) )",
"= cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin =",
"cms.bool(False), usePUProxyValue = cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut = cms.int32(4),",
"PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight",
"cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False),",
"= cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06,",
"= cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope =",
"cone = cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged",
")) ) ), applyCHS = cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands",
"cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap =",
"import FWCore.ParameterSet.Config as cms hltPFPuppiNoLep = cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1),",
"cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05),",
")) ), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt",
"= cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet(",
"cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True) )) ), cms.PSet(",
"cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656),",
"etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos",
"PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons",
"MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF =",
"EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue",
"= cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi =",
"cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5),",
"ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr",
"= cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons =",
"invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights",
"candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics",
"= cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged =",
"= cms.bool(False) )) ) ), applyCHS = cms.bool(True), candName =",
"cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0),",
"= cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue =",
"cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0),",
"rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True) )) ), cms.PSet( EtaMaxExtrap",
"cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0),",
"= cms.bool(True) )) ), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF =",
"3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos",
"= cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged =",
"combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor",
"ptMin = cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5),",
"MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax =",
"cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut = cms.int32(4), vtxZCut = cms.double(24)",
"cms.bool(True), useExistingWeights = cms.bool(False), useExp = cms.bool(False), usePUProxyValue = cms.bool(True),",
"MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"), PtMaxCharged",
"= cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights =",
"cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0),",
"= cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin =",
"cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.5),",
"= cms.bool(False), usePUProxyValue = cms.bool(True), vertexName = cms.InputTag(\"goodOfflinePrimaryVertices\"), vtxNdofCut =",
"= cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True) )) ),",
"rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False) ))",
"EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged",
"cms.bool(True) )) ), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75),",
"cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05),",
"= cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt =",
"MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin",
"cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag(\"hltPixelClustersMultiplicity\"),",
"= cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId =",
"rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False) )) ) ), applyCHS",
"PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut",
"cms.EDProducer(\"PuppiProducer\", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0),",
"cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt =",
"cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False)",
"2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId =",
"= cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin =",
"cms.double(1.0), useCharged = cms.bool(False) )) ) ), applyCHS = cms.bool(True),",
"etaMax = cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin =",
"), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt =",
"cone = cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged",
"= cms.bool(False), useExp = cms.bool(False), usePUProxyValue = cms.bool(True), vertexName =",
"= cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone =",
"= cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut =",
"cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5),",
"cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0),",
") ), applyCHS = cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands =",
"applyCHS = cms.bool(True), candName = cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi",
"1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin",
"cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True)",
"0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax",
"cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01),",
"= cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight =",
"cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True),",
"= cms.InputTag(\"particleFlowTmp\"), clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics ="
] |
[
"ret_code, build_prep = self.BuildPrep() if ret_code == dbrerrno.ECNCLD: return if",
"# Create final control file UpdateProgress(progress, GT(u'Creating control file')) #",
"Move the working directory becuase dpkg seems to have problems",
"## Installs the built .deb package onto the system #",
"package onto the system # # Uses the system's package",
"md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum') # The » character denotes",
"Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task)",
"build tree os.makedirs(DIR_debian) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"# Make a fresh build tree os.makedirs(DIR_debian) progress += 1",
"task_list[u'changelog'][0] if changelog_target == u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else:",
"import chkid from globals.ident import inputid from globals.ident import pgid",
"GT(u'Creating md5sums')) if not WriteMD5(stage_dir, parent=build_progress): # Couldn't call md5sum",
"GT(u'An unknown error occurred'), __name__ ) return # Command executed",
"directory symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__,",
"for O in options: if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if",
"= len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message, count,",
"dbrerror : SUCCESS if build completed successfully def Build(self, task_list,",
"name=u'MD5', defaultValue=True, commands=u'md5sum') # The » character denotes that an",
"u'files' in task_list: task_count += len(task_list[u'files']) # Add each script",
"returned code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An",
"wx.ID_OK: # Remove old overrides self.lint_overrides = [] for L",
"ui.layout import BoxSizer from ui.output import OutputLog from ui.panel import",
"{}'.format(f, files_total) # Scripts to make scripts_to_make = [] scripts",
"GetPage(pgid.MENU) # Check to make sure that all required fields",
"target_dir = os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks",
"build_status[1]) except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen",
"{}'.format(page_name, field_name)) # Get information from control page for default",
"0o0644) # FIXME: Should check for working fakeroot & dpkg-deb",
"# *** Event Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # ***",
"build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs",
"CheckListDialog from ui.dialog import DetailedMessageDialog from ui.dialog import ShowErrorDialog from",
"# DEBUG: Start if DebugEnabled() and len(lint_tags) > 50: print(u'",
"F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) # FIXME: Strip",
"# Unicode decoder has trouble with certain characters. Replace any",
"case of error before dialogs created save_dia = None prebuild_progress",
"#@UnusedVariable for F in FILES: # Don't check files in",
"create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir) #",
"defaultValue=True, commands=u'md5sum') # The » character denotes that an alternate",
"Files *** # if u'files' in task_list: UpdateProgress(progress, GT(u'Copying files'))",
"in task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() #",
"FileUnstripped from dbr.language import GT from dbr.log import DebugEnabled from",
"__init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD) # ----- Extra Options pnl_options",
"UpdateProgress(progress, GT(u'Creating scripts')) scripts = task_list[u'scripts'] for SCRIPT in scripts:",
"# dpkg fails if there is no newline at end",
"{}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding directory to stage: {}'.format(f_tgt))",
"build_prep = self.BuildPrep() if ret_code == dbrerrno.ECNCLD: return if ret_code",
"\"{}\"'.format(script_filename))) # Individual scripts progress += 1 UpdateProgress(progress) # Entire",
"from filename for char in invalid_chars: menu_filename = menu_filename.replace(char, u'_')",
"*** Strip files ***# # FIXME: Needs only be run",
"source_file = file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir =",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** ERROR",
"else: Logger.Debug(__name__, u'Setting lintian tags failed') return False ## TODO:",
"1 for task_check, id_string in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for:",
"if create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) # If changelog will be",
"Set(self, data): # ???: Redundant self.Reset() build_data = data.split(u'\\n') if",
"error is thrown if self: # Set summary when \"Build\"",
"package), task_list[u'copyright']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"-*- ## \\package wizbin.build # MIT licensing # See: docs/LICENSE.txt",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** md5sums",
"(self.chk_lint, u'lintian'), ) prep_task_count = len(page_checks) + len(other_checks) progress =",
"WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"GT(u'File Count') file_count = u'{}: {}'.format(f, files_total) # Scripts to",
"def Build(self, task_list, build_path, filename): # Declare this here in",
"the package.') e2 = GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename),",
"wiz.helper import GetMainWindow from wiz.helper import GetPage from wiz.wizard import",
"GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c = u'{} -n",
"ExecuteCommand here install_output = subprocess.Popen(install_cmd) # Command appears to not",
"# FIXME: List should be cached so no need for",
"in task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts = task_list[u'scripts'] for SCRIPT",
"wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] = None",
"# Command executed but did not return success code if",
"{}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2),",
"no_follow_link: Logger.Debug(__name__, u'Adding file symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src),",
"GetPage from wiz.wizard import WizardPage ## Build page class Page(WizardPage):",
"Overrides *** # if UsingTest(u'alpha'): # FIXME: Move next to",
"Doxygen # # TODO: Use string names in project file",
"Declare these here in case of error before dialogs created",
"errors os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual scripts progress",
"# *** Layout *** # lyt_options = wx.GridBagSizer() next_row =",
"CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c = u'{} -n --best \"{}/changelog\"'.format(CMD_gzip,",
"for T in mandatory_tasks: task_list[T] = None task_count = len(task_list)",
"task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"FILES in os.walk(stage_dir): for D in DIRS: D = u'{}/{}'.format(ROOT,",
"fld_version, fld_maint, fld_email, ) # Menu launcher page pg_launcher =",
"\\t') version = u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog",
"FLAGS = wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5) if not",
"\\e dict : Task string IDs & page data #",
"doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir) # ***",
"Add each file for updating progress dialog if u'files' in",
"arch = GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for save destination ttype",
"task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c",
"for PID, id_string in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page",
"if exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644) files_data = task_list[u'files']",
"avoid whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual",
"__name__ ) return # Command executed but did not return",
"not added to this list # 'control' should be after",
"might be changed later to set a custom directory menu_dir",
"## TODO: Doxygen def SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS) #",
"= 0 # Option to strip binaries self.chk_strip = CheckBoxESS(pnl_options,",
"overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: # Remove old",
"0 # Installs the deb on the system self.chk_install =",
"build tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg,",
"Command executed but did not return success code if install_output.returncode:",
"success if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created",
"0 prev_row = next_row for CHK in pnl_options.Children: row =",
"lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5)",
"def Set(self, data): # ???: Redundant self.Reset() build_data = data.split(u'\\n')",
"next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build,",
"os.walk(stage_dir): for D in DIRS: D = u'{}/{}'.format(ROOT, D) os.chmod(D,",
"L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return",
"Should be set as class memeber? CMD_lintian = GetExecutable(u'lintian') errors",
"import ShowErrorDialog from ui.layout import BoxSizer from ui.output import OutputLog",
"= 0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count)",
"event=None): pg_scripts = GetPage(pgid.SCRIPTS) # Make sure the page is",
"GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package =",
"from input.toggle import CheckBox from input.toggle import CheckBoxESS from startup.tests",
"member? ExecuteCommand(GetExecutable(u'strip'), F) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"create hashes before populating DEBIAN directory if u'md5sums' in task_list:",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Final build ***",
"build_progress = None try: # Other mandatory tasks that will",
"build failed'), result) else: ShowErrorDialog(GT(u'Package build failed with unknown error'))",
"u'/') # *** Menu launcher *** # if u'launcher' in",
"control page for default filename package = fld_package.GetValue() # Remove",
"# *** Lintian Overrides *** # if UsingTest(u'alpha'): # FIXME:",
"# Actual path to new .deb deb = u'\"{}/{}.deb\"'.format(build_path, filename)",
"u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating menu launcher')) # This might",
"GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required fields is empty:'),",
"(self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count = len(page_checks)",
"to place documentation if create_changelog or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir,",
"O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ##",
"overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags",
".deb package timestamp to confirm build success if ret_code ==",
"progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path, filename))",
"self: # Set summary when \"Build\" page is shown #",
"from wiz.helper import GetPage from wiz.wizard import WizardPage ## Build",
"Option to strip binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'),",
"GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors != wx.EmptyString:",
"GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0 # Checks",
"# Parent <b><i>wx.Window</i></b> instance def __init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD)",
"install_cmd = (system_installer, package,) wx.Yield() # FIXME: Use ExecuteCommand here",
"# Declare this here in case of error before progress",
"CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0",
"Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required fields is empty:'), build_prep))",
"old overrides self.lint_overrides = [] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__,",
"F = ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F))",
"return (dbrerrno.SUCCESS, (task_list, build_path, filename)) except: if save_dia: save_dia.Destroy() if",
"= next_row next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons =",
"os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"lintian tags failed') return False ## TODO: Doxygen # #",
"here install_output = subprocess.Popen(install_cmd) # Command appears to not have",
"u'copyright' in task_list pg_control = GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir",
"len(task_list[u'scripts']) if DebugEnabled(): task_msg = GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}]",
"+= 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Create",
"for updating progress dialog if u'files' in task_list: task_count +=",
"char in invalid_chars: menu_filename = menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir):",
"= package.strip(u' \\t') package = u'-'.join(package.split(u' ')) version = fld_version.GetValue()",
"Don't check files in DEBIAN directory if ROOT != DIR_debian:",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Control file ***",
"not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks from exectuables exe =",
"# # \\param parent # Parent <b><i>wx.Window</i></b> instance def __init__(self,",
"u'lintian»' self.chk_lint.col = 0 # Installs the deb on the",
"build *** # UpdateProgress(progress, GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree",
"= wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5) if not CHK.col:",
"not work if os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding",
"progress = 0 task_msg = GT(u'Preparing build tree') Logger.Debug(__name__, task_msg)",
"that should not be in filenames invalid_chars = (u' ',",
"( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), )",
"task_list[u'launcher']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"from exectuables exe = False if source_file[-1] == u'*': exe",
"filename for char in invalid_chars: menu_filename = menu_filename.replace(char, u'_') if",
"= GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for T",
"# String & unicode string incompatibilities index = 0 for",
"self.chk_install.col = 0 # *** Lintian Overrides *** # if",
"', u'/') # *** Menu launcher *** # if u'launcher'",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Control file *** #",
"= next_row for CHK in pnl_options.Children: row = next_row FLAGS",
"if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name = pg_control.GetName() if item",
"if build completed successfully def Build(self, task_list, build_path, filename): #",
"u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual files progress += 1 UpdateProgress(progress)",
"else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the",
"build_path = os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, &",
"task_list, build_path, filename): # Declare this here in case of",
"pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for",
"FIXME: Strip command should be set as class member? ExecuteCommand(GetExecutable(u'strip'),",
"# TODO: Add cancel option to progress dialog # FIXME:",
"Set summary when \"Build\" page is shown # Get the",
"manager could not be found on the system'), __name__, warn=True",
"error dialog. # \\param package # \\b \\e unicode|str :",
"completed successfullly if not build_status[0]: return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ",
"# DEBUG: End tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count): return",
"u'Installed-Size: {}'.format(installed_size)) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"fld_package = GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION) fld_maint =",
"Task string IDs & page data # \\param build_path #",
"failed'), result) else: ShowErrorDialog(GT(u'Package build failed with unknown error')) return",
"failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation failed with unknown error')) ##",
"\\t') package = u'-'.join(package.split(u' ')) version = fld_version.GetValue() # Remove",
"Installs the built .deb package onto the system # #",
"overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs progress",
"= pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress += 1 if build_progress.WasCancelled():",
"in quotes to avoid whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod +x",
"btnid from globals.ident import chkid from globals.ident import inputid from",
"Close progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build completed successfullly",
"have values required = list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get()",
"GT(u'Preparing to build'), maximum=prep_task_count) if wx.MAJOR_VERSION < 3: # Resize",
"been executed correctly if install_output == None: ShowErrorDialog( GT(u'Could not",
"not CHK.col: prev_row = next_row next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True)",
"= True source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) #",
"Needs only be run if 'files' step is used if",
"# Option to strip binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip",
"c_tree, deb_package))) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"Actual build ret_code, result = self.Build(task_list, build_path, filename) # FIXME:",
"characters from filename for char in invalid_chars: menu_filename = menu_filename.replace(char,",
"at end of file control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure there",
"WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags')))",
"should be very first task task_list = {} # Control",
"from ui.output import OutputLog from ui.panel import BorderedPanel from ui.progress",
"from fileio.fileio import ReadFile from fileio.fileio import WriteFile from globals.bitmaps",
"fld_package, fld_version, fld_maint, fld_email, ) # Menu launcher page pg_launcher",
"after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col =",
"# 'control' should be after 'md5sums' # 'build' should be",
"# The » character denotes that an alternate tooltip should",
"c_tree = os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) # Move the working",
"Check to make sure that all required fields have values",
"in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining",
"Entire script task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"Control file *** # UpdateProgress(progress, GT(u'Getting installed size')) # Get",
"= u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() # Remove invalid characters from",
"build tree'), parent=build_progress) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"free stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None) #",
"launcher')) # This might be changed later to set a",
"{}'), GT(u'An unknown error occurred'), __name__ ) return # Command",
"save_dia = None prebuild_progress = None try: # List of",
"{}'.format(current_task, task_count) if message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task,",
"[{}] {}'.format(__name__, task_msg)) for T in task_list: print(u'\\t{}'.format(T)) create_changelog =",
"if item not in fields_control: page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY,",
"to strip binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»',",
"= [] options = ( self.chk_md5, self.chk_rmstage, self.chk_lint, ) for",
"import ReadFile from fileio.fileio import WriteFile from globals.bitmaps import ICON_EXCLAMATION",
"pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script in scripts: if",
"in options: if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip')",
"*** Delete staged directory *** # if u'rmstage' in task_list:",
"0 task_msg = GT(u'Preparing build tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress",
"if u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts = task_list[u'scripts']",
"is not null terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n')",
"ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip =",
"0 # Option to strip binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP,",
"0 # *** Lintian Overrides *** # if UsingTest(u'alpha'): #",
"ReadFile from fileio.fileio import WriteFile from globals.bitmaps import ICON_EXCLAMATION from",
"ret_code, result = self.Build(task_list, build_path, filename) # FIXME: Check .deb",
"GT(u'Debian packages') save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR)",
"= BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra",
"GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] = None progress +=",
"Count') file_count = u'{}: {}'.format(f, files_total) # Scripts to make",
"GT(u'Creating changelog')) # If changelog will be installed to default",
"\"Build\" page is shown # Get the file count files_total",
"required: if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name = pg_control.GetName() if",
"progress += 1 # Close progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy()",
"GT(u'Scripts') if len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s, u', '.join(scripts_to_make)) else:",
"elif os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding file symbolic",
"directory changelog_target = task_list[u'changelog'][0] if changelog_target == u'STANDARD': changelog_target =",
"None) # Characters that should not be in filenames invalid_chars",
"{}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None) # Actual path to",
"event=None): # Build preparation ret_code, build_prep = self.BuildPrep() if ret_code",
"u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task) #",
"Uses the system's package installer: # gdebi if available or",
"lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'),",
"pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue():",
"in scripts: script_name = SCRIPT script_text = scripts[SCRIPT] script_filename =",
"GS(C) except UnicodeDecodeError: build_output[index] = u'�' index += 1 build_status",
"FIXME: Should check for working fakeroot & dpkg-deb executables build_status",
"string IDs & page data # \\param build_path # \\b",
"build success if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package",
"self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting lintian tags failed') return",
"is not added to this list # 'control' should be",
"# Installing the package if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return",
"GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)):",
"1 # Close progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build",
"wizbin.build # MIT licensing # See: docs/LICENSE.txt import commands, os,",
"set a custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename()",
"file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file) if",
"for T in task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog' in task_list",
"Deletes the temporary build tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete",
"is shown # Get the file count files_total = GetPage(pgid.FILES).GetFileCount()",
"asteriks from exectuables exe = False if source_file[-1] == u'*':",
"error')) ## TODO: Doxygen # # TODO: Show warning dialog",
"if errors != wx.EmptyString: e1 = GT(u'Lintian found some issues",
"None progress += 1 # Close progress dialog wx.Yield() prebuild_progress.Update(progress)",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Delete staged directory",
"DIRS, FILES in os.walk(stage_dir): #@UnusedVariable for F in FILES: #",
"prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen def GetSaveData(self):",
"globals.errorcodes import dbrerrno from globals.execute import ExecuteCommand from globals.execute import",
"= fld_package.GetValue() # Remove whitespace package = package.strip(u' \\t') package",
"progress dialog if u'scripts' in task_list: task_count += len(task_list[u'scripts']) if",
"package.strip(u' \\t') package = u'-'.join(package.split(u' ')) version = fld_version.GetValue() #",
"this list page_checks = ( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG,",
"u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) # Install",
"= commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1], warn=True,",
"prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path, filename)) except: if save_dia:",
"GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress += 1 #",
"in task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT, DIRS, FILES in",
"Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian",
"( GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)), )",
"T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) #",
"= 0 # Checks the output .deb for errors self.chk_lint",
"wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian =",
"globals.execute import GetSystemInstaller from globals.ident import btnid from globals.ident import",
"# FIXME: Check .deb package timestamp to confirm build success",
"task_count = len(task_list) # Add each file for updating progress",
"Menu launcher *** # if u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating",
"with older projects that use # integer values. def Set(self,",
"build_status = commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package)))",
"os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size = installed_size[0] #",
"') source_file = file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Control",
"= OutputLog(self) SetPageToolTips(self) # *** Event Handling *** # btn_build.Bind(wx.EVT_BUTTON,",
"ShowErrorDialog( GT(u'Could not install package: {}'), GT(u'An unknown error occurred'),",
"page is not destroyed so no error is thrown if",
"# Scripts to make scripts_to_make = [] scripts = ((u'preinst',",
"WriteFile from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from",
"globals.ident import inputid from globals.ident import pgid from globals.paths import",
"should be shown if the control is disabled self.chk_md5.tt_name =",
"= wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch))",
"= list(build_status[1]) # String & unicode string incompatibilities index =",
"stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding directory to stage:",
"class member? ExecuteCommand(GetExecutable(u'strip'), F) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"build_list = [] options = ( self.chk_md5, self.chk_rmstage, self.chk_lint, )",
"chkid.LINT, GT(u'Check package for errors with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian')",
"not WriteMD5(stage_dir, parent=build_progress): # Couldn't call md5sum command build_progress.Cancel() progress",
"invalid characters from filename for char in invalid_chars: menu_filename =",
"filename package = fld_package.GetValue() # Remove whitespace package = package.strip(u'",
"return (dbrerrno.ECNCLD, None) package = GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure",
"scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text) # Make",
"this into a file functions module def _copy(f_src, f_tgt, exe=False):",
"for F in FILES: # Don't check files in DEBIAN",
"= GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count') file_count = u'{}: {}'.format(f,",
"values required = list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher,",
"# Uses the system's package installer: # gdebi if available",
"progress dialog # FIXME: List should be cached so no",
"before populating DEBIAN directory if u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating",
"== dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() # Installing",
"id_string in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue():",
"lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End",
"input.toggle import CheckBox from input.toggle import CheckBoxESS from startup.tests import",
"on the system self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after",
"name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col = 0 #",
"GT(u'Command executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An error occurred during",
"wx.Yield() build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task) # *** Files ***",
"Logger.Info(__name__, u'Enabling alpha feature \"lintian overrides\" option') self.lint_overrides = []",
"that an alternate tooltip should be shown if the control",
"return (dbrerrno.ECNCLD, None) # *** Scripts *** # if u'scripts'",
"self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: # Remove",
"PD_DEFAULT_STYLE from ui.progress import ProgressDialog from ui.progress import TimedProgressDialog from",
"script_name = SCRIPT script_text = scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN',",
"all required fields have values required = list(fields_control) if pg_launcher.IsOkay():",
"default tags'))) progress.Start() wx.Yield() # Create the dialog overrides_dialog =",
"Actual path to new .deb deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress",
"instance def __init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD) # ----- Extra",
"code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An error",
"# Individual scripts progress += 1 UpdateProgress(progress) # Entire script",
"TODO: move this into a file functions module def _copy(f_src,",
"in DEBIAN directory if ROOT != DIR_debian: F = ConcatPaths((ROOT,",
"u'DEBIAN', script_name)) WriteFile(script_filename, script_text) # Make sure scipt path is",
"Remove whitespace version = version.strip(u' \\t') version = u''.join(version.split()) arch",
"make scripts_to_make = [] scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst),",
"= ( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'),",
"# TODO: Use string names in project file but retain",
"build_status = (build_status[0], u''.join(build_output)) # Build failed return (build_status[0], build_status[1])",
"sure that all required fields have values required = list(fields_control)",
") ShowErrorDialog( GT(u'An error occurred during installation'), u'\\n'.join(err_details), __name__ )",
"WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal()",
"pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and",
"ICON_INFORMATION from globals.errorcodes import dbrerrno from globals.execute import ExecuteCommand from",
"import ExecuteCommand from globals.execute import GetExecutable from globals.execute import GetSystemInstaller",
"Doxygen def OnBuild(self, event=None): # Build preparation ret_code, build_prep =",
"in task_list: UpdateProgress(progress, GT(u'Creating menu launcher')) # This might be",
"# *** Menu launcher *** # if u'launcher' in task_list:",
"= {} # Control page pg_control = GetPage(pgid.CONTROL) fld_package =",
"as class memeber? CMD_lintian = GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian,",
"Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout *** #",
"TODO: Doxygen def SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS) # Make",
") return ## TODO: Doxygen def OnBuild(self, event=None): # Build",
"count files_total = GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count') file_count =",
"GT(item.GetName().title()) page_name = pg_control.GetName() if item not in fields_control: page_name",
"= GT(u'Preparing build tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(),",
": Directory where .deb will be output # \\param filename",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Final build *** #",
"layout as lyt from wiz.helper import FieldEnabled from wiz.helper import",
"in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return True",
"None) # *** Final build *** # UpdateProgress(progress, GT(u'Running dpkg'))",
"unicode|str : Basename of output file without .deb extension #",
"seems to have problems with spaces in path os.chdir(working_dir) #",
"custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() # Remove",
"= 0 # *** Lintian Overrides *** # if UsingTest(u'alpha'):",
"task_list[u'scripts'] for SCRIPT in scripts: script_name = SCRIPT script_text =",
"in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID) if",
"& build pages not added to this list page_checks =",
"directory is available in which to place documentation if create_changelog",
"0o0755) else: os.chmod(F, 0o0644) # FIXME: Should check for working",
"chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col = 0 #",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Final",
"tree'), parent=build_progress) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"warn=True, title=GT(u'Warning')) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"shutil.copy(f_src, f_tgt) # Set FILE permissions if exe: os.chmod(f_tgt, 0o0755)",
"temp directory')) try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error occurred when",
"the package if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return if result:",
"u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for save destination",
"next_row FLAGS = lyt.PAD_LR if CHK.col: row = prev_row FLAGS",
"F = u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK): os.chmod(F, 0o0755) else:",
"with unknown error')) ## TODO: Doxygen # # TODO: Show",
"else: changelog_target = ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target),",
"GT(u'Attempting to install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd",
"GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() # Create",
"from globals.tooltips import SetPageToolTips from input.toggle import CheckBox from input.toggle",
"dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename)",
"UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT, DIRS, FILES in os.walk(stage_dir): #@UnusedVariable",
"this here in case of error before progress dialog created",
"T in mandatory_tasks: task_list[T] = None task_count = len(task_list) #",
"u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count = len(page_checks) + len(other_checks) progress",
"if not system_installer: ShowErrorDialog( GT(u'Cannot install package'), GT(u'A compatible package",
"os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file is missing: {}'.format(lintian_tags_file)) return False",
"# Make sure the page is not destroyed so no",
"OSError: ShowErrorDialog(GT(u'An error occurred when trying to delete the build",
"binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip')",
"build_progress.Update(current_task) # *** Files *** # if u'files' in task_list:",
"preparation failed with unknown error')) ## TODO: Doxygen # #",
"in task_list: task_count += len(task_list[u'scripts']) if DebugEnabled(): task_msg = GT(u'Total",
"installed_size[0] # Insert Installed-Size into control file control_data = pg_control.Get().split(u'\\n')",
"u'files' in task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked()",
"import PD_DEFAULT_STYLE from ui.progress import ProgressDialog from ui.progress import TimedProgressDialog",
"dbrerrno from globals.execute import ExecuteCommand from globals.execute import GetExecutable from",
"5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian",
"in project file but retain # compatibility with older projects",
"to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if",
"FIXME: if self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop()",
"pg_menu.GetOutputFilename() # Remove invalid characters from filename for char in",
"*** Layout *** # lyt_options = wx.GridBagSizer() next_row = 0",
"wx.MAJOR_VERSION < 3: # Resize dialog for better fit pb_size",
"# \\b \\e dbrerror : SUCCESS if build completed successfully",
"one empty trailing newline # Two '\\n' to show physical",
"from globals.strings import RemoveEmptyLines from globals.strings import TextIsEmpty from globals.system",
"self.chk_lint.tt_name = u'lintian»' self.chk_lint.col = 0 # Installs the deb",
"cancel option to progress dialog # FIXME: List should be",
"overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T in lint_tags: if T",
"end of file control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure there is",
"ProgressDialog from ui.progress import TimedProgressDialog from ui.style import layout as",
"fails if there is no newline at end of file",
"found some issues with the package.') e2 = GT(u'Details saved",
"inputid.FNAME)) for item in required: if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title())",
"self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method that builds the actual Debian",
"# *** Final build *** # UpdateProgress(progress, GT(u'Running dpkg')) working_dir",
"TODO: Doxygen # # \\return # \\b \\e tuple containing",
"self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col",
"scripts')) scripts = task_list[u'scripts'] for SCRIPT in scripts: script_name =",
"----- Extra Options pnl_options = BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5,",
"return if ret_code == dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'),",
"pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL)",
"wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT,",
"without .deb extension # \\return # \\b \\e dbrerror :",
"return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None): task_eval = u'{} /",
"lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5) if not CHK.col: prev_row =",
"files progress += 1 UpdateProgress(progress) # Entire file task progress",
"u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F, 0o0644)",
"= (u' ', u'/') # *** Menu launcher *** #",
"for char in invalid_chars: menu_filename = menu_filename.replace(char, u'_') if not",
"later to set a custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename",
"# Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True)",
"# Make sure that the directory is available in which",
"installed_size = installed_size[0] # Insert Installed-Size into control file control_data",
"Individual scripts progress += 1 UpdateProgress(progress) # Entire script task",
"## TODO: Doxygen # # TODO: Use string names in",
"failed return (build_status[0], build_status[1]) except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc())",
"= CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64) # Display log dsp_log",
"import FieldEnabled from wiz.helper import GetField from wiz.helper import GetMainWindow",
"UpdateProgress(progress, GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move",
"install package: {}'), GT(u'An unknown error occurred'), __name__ ) return",
"= BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'), name=u'MD5',",
"= build_prep # Actual build ret_code, result = self.Build(task_list, build_path,",
"<= 2: # Unicode decoder has trouble with certain characters.",
"CHK.col: row = prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK, (row, CHK.col),",
"here in case of error before dialogs created save_dia =",
"This might be changed later to set a custom directory",
"from ui.dialog import DetailedMessageDialog from ui.dialog import ShowErrorDialog from ui.layout",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Create final control file",
"prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count) if wx.MAJOR_VERSION <",
"= u'{}: {}'.format(f, files_total) # Scripts to make scripts_to_make =",
"({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task) # ***",
"DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required fields is",
"ShowErrorDialog(GT(u'Could not free stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST,",
"filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress",
"\\e unicode|str : Basename of output file without .deb extension",
"staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0 # Checks the",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** md5sums file *** #",
"u'Setting lintian tags failed') return False ## TODO: Doxygen #",
"# if u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts =",
"lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT,",
"= wx.GridBagSizer() next_row = 0 prev_row = next_row for CHK",
"dbr.log import Logger from dbr.md5 import WriteMD5 from fileio.fileio import",
"updating progress dialog if u'files' in task_list: task_count += len(task_list[u'files'])",
"+= 1 UpdateProgress(progress) # Entire script task progress += 1",
"= scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text) #",
"\\b \\e tuple containing Return code & build details def",
"build failed with unknown error')) return if build_prep: ShowErrorDialog(GT(u'Build preparation",
"# Don't check files in DEBIAN directory if ROOT !=",
"and no_follow_link: Logger.Debug(__name__, u'Adding file symbolic link to stage: {}'.format(f_tgt))",
"package if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package",
"inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL) fields_control = ( fld_package, fld_version,",
"os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic link to stage:",
"Remove whitespace package = package.strip(u' \\t') package = u'-'.join(package.split(u' '))",
"# Build completed successfullly if not build_status[0]: return (dbrerrno.SUCCESS, deb_package)",
"control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure there is only one empty",
"TODO: Show warning dialog that this could take a while",
"= pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME))",
"List of tasks for build process # 'stage' should be",
"True else: Logger.Debug(__name__, u'Setting lintian tags failed') return False ##",
"will be installed to default directory changelog_target = task_list[u'changelog'][0] if",
"u'changelog' in task_list create_copyright = u'copyright' in task_list pg_control =",
"os.walk(stage_dir): #@UnusedVariable for F in FILES: # Don't check files",
"import btnid from globals.ident import chkid from globals.ident import inputid",
"prev_row = next_row next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons",
"FILE in files_data: file_defs = FILE.split(u' -> ') source_file =",
"task_list: UpdateProgress(progress, GT(u'Creating menu launcher')) # This might be changed",
"but retain # compatibility with older projects that use #",
"0o0755) else: os.chmod(f_tgt, 0o0644) files_data = task_list[u'files'] for FILE in",
"Doxygen def GetSaveData(self): build_list = [] options = ( self.chk_md5,",
") return # Command executed but did not return success",
"build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task) # *** Files *** #",
"lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides,",
"Start if DebugEnabled() and len(lint_tags) > 50: print(u' Reducing tag",
"import UsingTest from ui.button import CreateButton from ui.checklist import CheckListDialog",
"inputid.EMAIL) fields_control = ( fld_package, fld_version, fld_maint, fld_email, ) #",
"Options pnl_options = BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums",
"0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0,",
"-> ') source_file = file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1])",
"pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"== None: ShowErrorDialog( GT(u'Could not install package: {}'), GT(u'An unknown",
"if clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress",
"wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5) if not CHK.col: prev_row",
"if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built .deb",
"if u'scripts' in task_list: task_count += len(task_list[u'scripts']) if DebugEnabled(): task_msg",
"os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks from exectuables exe = False",
"{}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An error occurred",
"# # \\param task_list # \\b \\e dict : Task",
"from globals.ident import pgid from globals.paths import ConcatPaths from globals.paths",
"task_list = {} # Control page pg_control = GetPage(pgid.CONTROL) fld_package",
"for FILE in files_data: file_defs = FILE.split(u' -> ') source_file",
"# UpdateProgress(progress, GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1]",
"Replace any # non-decodable characters with � (0xFFFD). build_output =",
"Resize dialog for better fit pb_size = prebuild_progress.GetSizeTuple() pb_size =",
"if task_check.GetValue(): task_list[id_string] = None progress += 1 # Close",
"= False if source_file[-1] == u'*': exe = True source_file",
"BuildPrep(self): # Declare these here in case of error before",
"as lyt from wiz.helper import FieldEnabled from wiz.helper import GetField",
"wiz.helper import GetField from wiz.helper import GetMainWindow from wiz.helper import",
"directory if u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if not",
"warn=True ) return Logger.Info(__name__, GT(u'Attempting to install package: {}').format(package)) Logger.Info(__name__,",
"lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End tag_count =",
"task_count += len(task_list[u'scripts']) if DebugEnabled(): task_msg = GT(u'Total tasks: {}').format(task_count)",
"Strip files ***# # FIXME: Needs only be run if",
"except: if save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc())",
"default filename package = fld_package.GetValue() # Remove whitespace package =",
"pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main =",
"filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not free",
"try: GS(C) except UnicodeDecodeError: build_output[index] = u'�' index += 1",
"return if ret_code == dbrerrno.SUCCESS: task_list, build_path, filename = build_prep",
"= ( GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)),",
"self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package build failed'), result) else: ShowErrorDialog(GT(u'Package",
"dpkg seems to have problems with spaces in path os.chdir(working_dir)",
"FIXME: Check .deb package timestamp to confirm build success if",
"pgid.BUILD) # ----- Extra Options pnl_options = BorderedPanel(self) self.chk_md5 =",
"fld_package.GetValue() # Remove whitespace package = package.strip(u' \\t') package =",
"label=GT(u'Lintian overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5)",
"')) version = fld_version.GetValue() # Remove whitespace version = version.strip(u'",
"size')) # Get installed-size installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size",
"UpdateProgress(progress) # Entire file task progress += 1 if build_progress.WasCancelled():",
"# *** md5sums file *** # # Good practice to",
"to confirm build success if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'),",
"UsingTest(u'alpha'): # FIXME: Move next to lintian check box Logger.Info(__name__,",
"List should be cached so no need for re-scanning def",
"if u'files' in task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES),",
"is disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col = 0 # Option",
"= ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text) # Make sure scipt",
"scripts: script_name = SCRIPT script_text = scripts[SCRIPT] script_filename = ConcatPaths((stage_dir,",
"((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script",
"from ui.dialog import ShowErrorDialog from ui.layout import BoxSizer from ui.output",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** ERROR CHECK if u'lintian'",
"ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() #",
"if CHK.col: row = prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK, (row,",
"err_dia.Destroy() return if ret_code == dbrerrno.SUCCESS: task_list, build_path, filename =",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) package = GetField(pg_control, inputid.PACKAGE).GetValue() # Make",
"to delete the build tree'), parent=build_progress) progress += 1 if",
"3 appears to have follow_symlinks option for shutil.copy # FIXME:",
"= 0 task_msg = GT(u'Preparing build tree') Logger.Debug(__name__, task_msg) wx.Yield()",
"have been executed correctly if install_output == None: ShowErrorDialog( GT(u'Could",
"pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data) ## TODO: Doxygen def",
"GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for save destination ttype = GT(u'Debian",
"globals.ident import btnid from globals.ident import chkid from globals.ident import",
"u'{}.deb'.format(filename) # Move the working directory becuase dpkg seems to",
"from globals.paths import PATH_app from globals.strings import GS from globals.strings",
"*** # UpdateProgress(progress, GT(u'Getting installed size')) # Get installed-size installed_size",
"= GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for save destination ttype =",
"= prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID,",
"*** # if create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright'])",
"save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0] filename",
"count to 200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {}",
"return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built .deb package onto the",
"self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal()",
"lyt.PAD_LR if CHK.col: row = prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK,",
"not os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog *** # if create_changelog:",
"dbr.language import GT from dbr.log import DebugEnabled from dbr.log import",
"successfully def Build(self, task_list, build_path, filename): # Declare this here",
"UpdateProgress(progress, GT(u'Compressing changelog')) c = u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target)",
"symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if exe:",
"# \\param task_list # \\b \\e dict : Task string",
"FIXME: Move next to lintian check box Logger.Info(__name__, u'Enabling alpha",
"build_progress.Update(progress) build_progress.Destroy() # Build completed successfullly if not build_status[0]: return",
"not destroyed so no error is thrown if self: #",
"required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item",
"3: # Resize dialog for better fit pb_size = prebuild_progress.GetSizeTuple()",
"os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) # Move the working directory becuase",
"Delete staged directory *** # if u'rmstage' in task_list: UpdateProgress(progress,",
"with � (0xFFFD). build_output = list(build_status[1]) # String & unicode",
"SCRIPT in scripts: script_name = SCRIPT script_text = scripts[SCRIPT] script_filename",
"from ui.progress import ProgressDialog from ui.progress import TimedProgressDialog from ui.style",
"# Couldn't call md5sum command build_progress.Cancel() progress += 1 if",
"fld_version = GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email =",
"Lintian override: {}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting lintian",
"self.chk_lint, ) for O in options: if O.GetValue(): build_list.append(u'1') else:",
"# Close progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build completed",
"Characters that should not be in filenames invalid_chars = (u'",
"source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual files",
"and len(lint_tags) > 50: print(u' Reducing tag count to 200",
"item not in fields_control: page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{}",
"progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T in lint_tags: if T in",
"*** md5sums file *** # # Good practice to create",
"'md5sums' # 'build' should be after 'control' other_checks = (",
"# Ensure there is only one empty trailing newline #",
"shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error occurred when trying to delete",
"GetPage(pgid.SCRIPTS) # Make sure the page is not destroyed so",
"= [] scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm),",
"link may not work if os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link:",
"Logger.Debug(__name__, u'Adding executable to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file",
"version.strip(u' \\t') version = u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection() #",
"task_check.GetValue(): task_list[id_string] = None progress += 1 # Close progress",
"= u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F,",
"from ui.style import layout as lyt from wiz.helper import FieldEnabled",
"\\b \\e dbrerror : SUCCESS if build completed successfully def",
"dialog created build_progress = None try: # Other mandatory tasks",
"is no newline at end of file control_data = u'\\n'.join(control_data).strip(u'\\n')",
"first task task_list = {} # Control page pg_control =",
"ExecuteCommand(GetExecutable(u'strip'), F) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count) if wx.MAJOR_VERSION",
"## TODO: Doxygen # # TODO: Show warning dialog that",
"# UpdateProgress(progress, GT(u'Getting installed size')) # Get installed-size installed_size =",
"return (dbrerrno.ECNCLD, None) # *** Final build *** # UpdateProgress(progress,",
"self.lint_overrides = [] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian",
"Make sure scipt path is wrapped in quotes to avoid",
"None) # *** Control file *** # UpdateProgress(progress, GT(u'Getting installed",
"= RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags set') #",
"u'Lintian tags set') # DEBUG: Start if DebugEnabled() and len(lint_tags)",
"# if u'files' in task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link =",
"import BorderedPanel from ui.progress import PD_DEFAULT_STYLE from ui.progress import ProgressDialog",
"( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), )",
"defaultValue=True) self.chk_rmstage.col = 0 # Checks the output .deb for",
"(dbrerrno.ECNCLD, None) # *** Control file *** # UpdateProgress(progress, GT(u'Getting",
"if there is no newline at end of file control_data",
"*** # if create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) # If changelog",
"# \\param parent # Parent <b><i>wx.Window</i></b> instance def __init__(self, parent):",
"working fakeroot & dpkg-deb executables build_status = commands.getstatusoutput((u'{} {} -b",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Create final",
"page is shown # Get the file count files_total =",
"changelog_target == u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target =",
"task_list # \\b \\e dict : Task string IDs &",
"self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for errors with lintian'),",
"pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2]))",
"build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col = 0",
".deb deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0 task_msg =",
"ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text) # Make sure scipt path",
"if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package build",
"should be custom entries # FIXME: if self.lint_overrides: for T",
"except OSError: ShowErrorDialog(GT(u'Could not free stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue'))",
"import inputid from globals.ident import pgid from globals.paths import ConcatPaths",
"this could take a while # TODO: Add cancel option",
"other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] =",
"package # # \\param task_list # \\b \\e dict :",
"{}'.format(installed_size)) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"directory if ROOT != DIR_debian: F = ConcatPaths((ROOT, F)) if",
"task_list[u'copyright']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"installed_size = installed_size[0].split(u'\\t') installed_size = installed_size[0] # Insert Installed-Size into",
"(task_list, build_path, filename)) except: if save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy()",
"confirm build success if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION,",
"Add each script for updating progress dialog if u'scripts' in",
"from control page for default filename package = fld_package.GetValue() #",
"ui.checklist import CheckListDialog from ui.dialog import DetailedMessageDialog from ui.dialog import",
": Basename of output file without .deb extension # \\return",
"a custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() #",
"from wiz.helper import FieldEnabled from wiz.helper import GetField from wiz.helper",
"could not be found on the system'), __name__, warn=True )",
"u'install_size', u'control', u'build', ) # Add other mandatory tasks for",
"these here in case of error before dialogs created save_dia",
"ui.progress import ProgressDialog from ui.progress import TimedProgressDialog from ui.style import",
"there is no newline at end of file control_data =",
"wx from dbr.functions import FileUnstripped from dbr.language import GT from",
"scripts = task_list[u'scripts'] for SCRIPT in scripts: script_name = SCRIPT",
"UpdateProgress(progress, GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package",
"# Remove whitespace package = package.strip(u' \\t') package = u'-'.join(package.split(u'",
"50: print(u' Reducing tag count to 200 ...') lint_tags =",
": Path to package to be installed def InstallPackage(self, package):",
"which to place documentation if create_changelog or create_copyright: doc_dir =",
"GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item in required: if TextIsEmpty(item.GetValue()):",
"for CHK in pnl_options.Children: row = next_row FLAGS = lyt.PAD_LR",
"os.makedirs(DIR_debian) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"not free stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None)",
"def InstallPackage(self, package): system_installer = GetSystemInstaller() if not system_installer: ShowErrorDialog(",
"globals.strings import RemoveEmptyLines from globals.strings import TextIsEmpty from globals.system import",
"F in FILES: F = u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK):",
"GetField from wiz.helper import GetMainWindow from wiz.helper import GetPage from",
"'.join(install_cmd)), ) ShowErrorDialog( GT(u'An error occurred during installation'), u'\\n'.join(err_details), __name__",
"???: Redundant self.Reset() build_data = data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0]))",
"task_list[id_string] = None progress += 1 # Close progress dialog",
"if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides)))",
"UpdateProgress(progress, GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Strip files ***# #",
"(pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) #",
"from globals.strings import GS from globals.strings import RemoveEmptyLines from globals.strings",
"maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) # Make a fresh",
"\\param task_list # \\b \\e dict : Task string IDs",
"control is disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col = 0 #",
"defaultValue=True, commands=u'strip') self.chk_strip.col = 0 # Deletes the temporary build",
"Doxygen def SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS) # Make sure",
"= GT(item.GetName().title()) page_name = pg_control.GetName() if item not in fields_control:",
"some issues with the package.') e2 = GT(u'Details saved to",
"import RemoveEmptyLines from globals.strings import TextIsEmpty from globals.system import PY_VER_MAJ",
"Build page class Page(WizardPage): ## Constructor # # \\param parent",
"return (dbrerrno.EEXIST, None) # Actual path to new .deb deb",
"in FILES: # Don't check files in DEBIAN directory if",
"False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags",
"PATH_app from globals.strings import GS from globals.strings import RemoveEmptyLines from",
"tags'.format(len(lint_tags))) # DEBUG: End tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count):",
"unknown error occurred'), __name__ ) return # Command executed but",
"import WizardPage ## Build page class Page(WizardPage): ## Constructor #",
"exe = True source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe)",
"os.chmod(F, 0o0755) else: os.chmod(F, 0o0644) # FIXME: Should check for",
"option') self.lint_overrides = [] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON,",
"btnid.BUILD, GT(u'Build'), u'build', 64) # Display log dsp_log = OutputLog(self)",
"else: if exe: Logger.Debug(__name__, u'Adding executable to stage: {}'.format(f_tgt)) else:",
"if u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating menu launcher')) # This",
"Parent <b><i>wx.Window</i></b> instance def __init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD) #",
"save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD,",
"ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count) if wx.MAJOR_VERSION < 3: #",
"system_installer: ShowErrorDialog( GT(u'Cannot install package'), GT(u'A compatible package manager could",
"FIXME: copying nested symbolic link may not work if os.path.isdir(f_src):",
"u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End tag_count = len(lint_tags) def",
"progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start()",
"Logger.Error(__name__, u'Lintian tags file is missing: {}'.format(lintian_tags_file)) return False lint_tags",
"fields is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return if ret_code ==",
"code if install_output.returncode: err_details = ( GT(u'Process returned code {}').format(install_output.returncode),",
"ShowErrorDialog(GT(u'Package build failed'), result) else: ShowErrorDialog(GT(u'Package build failed with unknown",
"deb_package = u'{}.deb'.format(filename) # Move the working directory becuase dpkg",
"docs/LICENSE.txt import commands, os, shutil, subprocess, traceback, wx from dbr.functions",
") prep_task_count = len(page_checks) + len(other_checks) progress = 0 wx.Yield()",
"be after 'md5sums' # 'build' should be after 'control' other_checks",
"inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email",
"not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip:",
"GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION) fld_maint",
"not return success code if install_output.returncode: err_details = ( GT(u'Process",
"not compress changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress += 1 if",
"None task_count = len(task_list) # Add each file for updating",
"self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built .deb package",
"count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default",
"# Get installed-size installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size =",
"to show physical empty line, but not required # Perhaps",
"file control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress += 1",
"exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644) files_data = task_list[u'files'] for",
"import commands, os, shutil, subprocess, traceback, wx from dbr.functions import",
"dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs",
"u'{} / {}'.format(current_task, task_count) if message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval))",
"# Deletes the temporary build tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE,",
"len(task_list) # Add each file for updating progress dialog if",
"+= 1 # Close progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return",
"_copy(f_src, f_tgt, exe=False): # NOTE: Python 3 appears to have",
"case of error before progress dialog created build_progress = None",
"= next_row FLAGS = lyt.PAD_LR if CHK.col: row = prev_row",
"= None try: # List of tasks for build process",
"to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file to stage: {}'.format(f_tgt))",
"before dialogs created save_dia = None prebuild_progress = None try:",
"is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return if ret_code == dbrerrno.SUCCESS:",
"self.chk_md5.tt_name = u'md5»' self.chk_md5.col = 0 # Option to strip",
"if UsingTest(u'alpha'): # FIXME: Move next to lintian check box",
"= None task_count = len(task_list) # Add each file for",
"u'Adding directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif",
"wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if",
"globals.execute import GetExecutable from globals.execute import GetSystemInstaller from globals.ident import",
"btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64) #",
"files ***# # FIXME: Needs only be run if 'files'",
"= GT(u'Debian packages') save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype),",
"\\package wizbin.build # MIT licensing # See: docs/LICENSE.txt import commands,",
"# Shows a success dialog if installed. Otherwise shows an",
"be set as class memeber? CMD_lintian = GetExecutable(u'lintian') errors =",
"executed but did not return success code if install_output.returncode: err_details",
"task_list: task_count += len(task_list[u'scripts']) if DebugEnabled(): task_msg = GT(u'Total tasks:",
"# FIXME: if self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T, True)",
"wiz.helper import GetPage from wiz.wizard import WizardPage ## Build page",
"GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for T in",
"FILE permissions if exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644) files_data",
"scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm))",
"# Individual files progress += 1 UpdateProgress(progress) # Entire file",
"wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not save_dia.ShowModal() ==",
"OSError: ShowErrorDialog(GT(u'Could not free stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return",
"changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'),",
"shutil.copy # FIXME: copying nested symbolic link may not work",
"u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress +=",
"GT(u'Creating control file')) # dpkg fails if there is no",
"return if build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation",
"\\param package # \\b \\e unicode|str : Path to package",
"os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding file symbolic link",
"for task_check, id_string in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel()))",
"to new .deb deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0",
"# if u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating menu launcher')) #",
"(self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count = len(page_checks) + len(other_checks)",
"> 50: print(u' Reducing tag count to 200 ...') lint_tags",
"files_total) # Scripts to make scripts_to_make = [] scripts =",
"in task_list: UpdateProgress(progress, GT(u'Checking package for errors')) # FIXME: Should",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Characters that",
"if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if",
"stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set FILE permissions if exe:",
"options: if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return",
"prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking",
"wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5)",
"def BuildPrep(self): # Declare these here in case of error",
"2: # Unicode decoder has trouble with certain characters. Replace",
"error occurred when trying to delete the build tree'), parent=build_progress)",
"CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col = 0",
".deb for errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Characters that should not be",
"return (build_status[0], build_status[1]) except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ##",
"if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen def",
"and u'strip' in build_data) ## TODO: Doxygen def SetSummary(self, event=None):",
"disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col = 0 # Option to",
"install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd = (system_installer,",
"updating progress dialog if u'scripts' in task_list: task_count += len(task_list[u'scripts'])",
"{}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set FILE permissions if exe: os.chmod(f_tgt,",
"wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C)",
"Changelog *** # if create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) # If",
"not be found on the system'), __name__, warn=True ) return",
"symbolic link may not work if os.path.isdir(f_src): if os.path.islink(f_src) and",
"print(u'\\t{}'.format(T)) create_changelog = u'changelog' in task_list create_copyright = u'copyright' in",
"= u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for F in FILES: F",
"create_copyright = u'copyright' in task_list pg_control = GetPage(pgid.CONTROL) pg_menu =",
"option to progress dialog # FIXME: List should be cached",
"# Make sure scipt path is wrapped in quotes to",
"'build' should be after 'control' other_checks = ( (self.chk_md5, u'md5sums'),",
"from globals.ident import inputid from globals.ident import pgid from globals.paths",
"character denotes that an alternate tooltip should be shown if",
"page data # \\param build_path # \\b \\e unicode|str :",
"prev_row = next_row for CHK in pnl_options.Children: row = next_row",
"= ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) #",
"Logger.Debug(__name__, u'Adding directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755)",
"print(u' Reducing tag count to 200 ...') lint_tags = lint_tags[:50]",
"*** Control file *** # UpdateProgress(progress, GT(u'Getting installed size')) #",
"return u'{} ({} {})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building",
"Debian package # # \\param task_list # \\b \\e dict",
"if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress += 1",
"import GetPage from wiz.wizard import WizardPage ## Build page class",
"# *** Delete staged directory *** # if u'rmstage' in",
"= u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress += 1 if build_progress.WasCancelled():",
"build details def BuildPrep(self): # Declare these here in case",
"fields_control: page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name))",
"os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644) files_data = task_list[u'files'] for FILE",
"{} tags'.format(len(lint_tags))) # DEBUG: End tag_count = len(lint_tags) def GetProgressMessage(message,",
"WizardPage.__init__(self, parent, pgid.BUILD) # ----- Extra Options pnl_options = BorderedPanel(self)",
"Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() # Create the",
"return # Command executed but did not return success code",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) package = GetField(pg_control, inputid.PACKAGE).GetValue()",
"u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) # Install step is not added",
"inputid.PACKAGE).GetValue() # Make sure that the directory is available in",
"PID, id_string in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page =",
"*** # lyt_options = wx.GridBagSizer() next_row = 0 prev_row =",
"(dbrerrno.EEXIST, None) # Actual path to new .deb deb =",
"None) # *** md5sums file *** # # Good practice",
"in fields_control: page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name,",
"progress += 1 UpdateProgress(progress) # Entire file task progress +=",
"commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress +=",
"os.access(F, os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F, 0o0644) # FIXME: Should",
"save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version,",
"for item in required: if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name",
"file'), name=u'MD5', defaultValue=True, commands=u'md5sum') # The » character denotes that",
"file: {}'.format(F)) # FIXME: Strip command should be set as",
"from dbr.log import Logger from dbr.md5 import WriteMD5 from fileio.fileio",
"clog_status[1], warn=True, title=GT(u'Warning')) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"\\return # \\b \\e dbrerror : SUCCESS if build completed",
"deb))) if errors != wx.EmptyString: e1 = GT(u'Lintian found some",
"Logger from dbr.md5 import WriteMD5 from fileio.fileio import ReadFile from",
"GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col = 0 # Deletes",
"dbrerrno.SUCCESS: task_list, build_path, filename = build_prep # Actual build ret_code,",
"the system self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after build'),",
"step is not added to this list # 'control' should",
"package manager could not be found on the system'), __name__,",
"files_data = task_list[u'files'] for FILE in files_data: file_defs = FILE.split(u'",
"ui.progress import TimedProgressDialog from ui.style import layout as lyt from",
"prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] = None progress",
"ExecuteCommand from globals.execute import GetExecutable from globals.execute import GetSystemInstaller from",
"set as class member? ExecuteCommand(GetExecutable(u'strip'), F) progress += 1 if",
"If changelog will be installed to default directory changelog_target =",
"build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir,",
"import WriteFile from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION",
"= CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD,",
"file *** # UpdateProgress(progress, GT(u'Getting installed size')) # Get installed-size",
"if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress += 1 for task_check,",
"dbr.log import DebugEnabled from dbr.log import Logger from dbr.md5 import",
"import CheckBox from input.toggle import CheckBoxESS from startup.tests import UsingTest",
"page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name)) #",
"commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors != wx.EmptyString: e1 = GT(u'Lintian",
"Scripts to make scripts_to_make = [] scripts = ((u'preinst', pg_scripts.chk_preinst),",
"c = u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8'))",
"fld_maint, fld_email, ) # Menu launcher page pg_launcher = GetPage(pgid.MENU)",
"binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col = 0 # Deletes the",
"errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors != wx.EmptyString: e1",
"{}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if exe: Logger.Debug(__name__, u'Adding executable to",
"IDs & page data # \\param build_path # \\b \\e",
"dialog. # \\param package # \\b \\e unicode|str : Path",
"(dbrerrno.ECNCLD, None) # *** Delete staged directory *** # if",
"e1 = GT(u'Lintian found some issues with the package.') e2",
"should be cached so no need for re-scanning def OnSetLintOverrides(self,",
"GetField(pg_control, inputid.EMAIL) fields_control = ( fld_package, fld_version, fld_maint, fld_email, )",
"import DebugEnabled from dbr.log import Logger from dbr.md5 import WriteMD5",
"not null terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress",
"= 0 # Deletes the temporary build tree self.chk_rmstage =",
"GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) # Make",
"(build_status[0], u''.join(build_output)) # Build failed return (build_status[0], build_status[1]) except: if",
"if PY_VER_MAJ <= 2: # Unicode decoder has trouble with",
"{}'.format(F)) # FIXME: Strip command should be set as class",
"subprocess.Popen(install_cmd) # Command appears to not have been executed correctly",
"Reducing tag count to 200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__,",
"changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip')",
"try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data)",
"if self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if",
"index = 0 for C in build_output: try: GS(C) except",
"\\b \\e unicode|str : Directory where .deb will be output",
"= GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION)",
"class memeber? CMD_lintian = GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb)))",
"# FIXME: Strip command should be set as class member?",
"error')) return if build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build",
"if create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress +=",
"from ui.layout import BoxSizer from ui.output import OutputLog from ui.panel",
"GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress += 1 if build_progress.WasCancelled():",
"errors')) # FIXME: Should be set as class memeber? CMD_lintian",
"200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) #",
"only one empty trailing newline # Two '\\n' to show",
"( self.chk_md5, self.chk_rmstage, self.chk_lint, ) for O in options: if",
"# # TODO: Use string names in project file but",
"u'copyright'), ) # Install step is not added to this",
"= u'{}: {}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make = u'{}: 0'.format(s)",
"Build failed return (build_status[0], build_status[1]) except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN,",
"self.chk_strip.col = 0 # Deletes the temporary build tree self.chk_rmstage",
"# if UsingTest(u'alpha'): # FIXME: Move next to lintian check",
"package for errors with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name =",
"= os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks from",
"successfullly if not build_status[0]: return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <=",
"system # # Uses the system's package installer: # gdebi",
"= self.Build(task_list, build_path, filename) # FIXME: Check .deb package timestamp",
"dialog that this could take a while # TODO: Add",
"( fld_package, fld_version, fld_maint, fld_email, ) # Menu launcher page",
"deb_package) if PY_VER_MAJ <= 2: # Unicode decoder has trouble",
"import pgid from globals.paths import ConcatPaths from globals.paths import PATH_app",
"Perhaps because string is not null terminated??? control_data = u'{}\\n\\n'.format(control_data)",
"if not CHK.col: prev_row = next_row next_row += 1 pnl_options.SetSizer(lyt_options)",
"parent=build_progress) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"(u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script in scripts:",
"\\param filename # \\b \\e unicode|str : Basename of output",
"that the directory is available in which to place documentation",
"except UnicodeDecodeError: build_output[index] = u'�' index += 1 build_status =",
"= None try: # Other mandatory tasks that will be",
"wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID) if wizard_page.IsOkay(): task_list[id_string]",
"# Resize dialog for better fit pb_size = prebuild_progress.GetSizeTuple() pb_size",
"ShowErrorDialog( GT(u'Cannot install package'), GT(u'A compatible package manager could not",
"TODO: Add cancel option to progress dialog # FIXME: List",
"chkid from globals.ident import inputid from globals.ident import pgid from",
"ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation failed with unknown",
"Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) #",
"next_row next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL)",
"# \\param package # \\b \\e unicode|str : Path to",
"traceback.format_exc()) ## TODO: Doxygen def GetSaveData(self): build_list = [] options",
"appears to have follow_symlinks option for shutil.copy # FIXME: copying",
"# # Good practice to create hashes before populating DEBIAN",
"menu, & build pages not added to this list page_checks",
"mandatory_tasks: task_list[T] = None task_count = len(task_list) # Add each",
"Event Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout ***",
"in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string]",
"files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move this into",
"os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks from exectuables",
"__name__, warn=True ) return Logger.Info(__name__, GT(u'Attempting to install package: {}').format(package))",
"while # TODO: Add cancel option to progress dialog #",
"0o0644) files_data = task_list[u'files'] for FILE in files_data: file_defs =",
"dialog if installed. Otherwise shows an # error dialog. #",
"not system_installer: ShowErrorDialog( GT(u'Cannot install package'), GT(u'A compatible package manager",
"None) # Actual path to new .deb deb = u'\"{}/{}.deb\"'.format(build_path,",
"*** # if u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts",
"from globals.execute import GetExecutable from globals.execute import GetSystemInstaller from globals.ident",
"'control' other_checks = ( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'),",
"TODO: Doxygen def GetSaveData(self): build_list = [] options = (",
"tasks for T in mandatory_tasks: task_list[T] = None task_count =",
"task_list: UpdateProgress(progress, GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An",
"is used if u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for",
"GT(u'Install package after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»'",
"build_path, filename) # FIXME: Check .deb package timestamp to confirm",
"will be output # \\param filename # \\b \\e unicode|str",
"F) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"globals.ident import chkid from globals.ident import inputid from globals.ident import",
"wx.GridBagSizer() next_row = 0 prev_row = next_row for CHK in",
"{}').format(id_string)) wizard_page = GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress",
"f_tgt) else: Logger.Debug(__name__, u'Adding directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt)",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Strip files",
"files in DEBIAN directory if ROOT != DIR_debian: F =",
"file but retain # compatibility with older projects that use",
"progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining tags should be custom",
"import GS from globals.strings import RemoveEmptyLines from globals.strings import TextIsEmpty",
"available or dpkg # # Shows a success dialog if",
"task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if not WriteMD5(stage_dir, parent=build_progress): # Couldn't",
"defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col = 0 # Installs",
"utf-8 -*- ## \\package wizbin.build # MIT licensing # See:",
"found on the system'), __name__, warn=True ) return Logger.Info(__name__, GT(u'Attempting",
"GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move this into a file functions",
"return wx.Yield() build_progress.Update(current_task) # *** Files *** # if u'files'",
"self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64) # Display",
"os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) # Move the",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** md5sums file ***",
"== wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0] filename =",
"UpdateProgress(progress, GT(u'Creating md5sums')) if not WriteMD5(stage_dir, parent=build_progress): # Couldn't call",
"2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method that builds",
"the output .deb for errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check",
"5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True)",
"progress += 1 # Close progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy()",
"dialogs created save_dia = None prebuild_progress = None try: #",
"in task_list: task_count += len(task_list[u'files']) # Add each script for",
"file *** # # Good practice to create hashes before",
"in case of error before dialogs created save_dia = None",
".deb package onto the system # # Uses the system's",
"exectuables exe = False if source_file[-1] == u'*': exe =",
"Final build *** # UpdateProgress(progress, GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0]",
"self.chk_install.tt_name = u'install»' self.chk_install.col = 0 # *** Lintian Overrides",
"ShowErrorDialog(GT(u'Build preparation failed with unknown error')) ## TODO: Doxygen #",
"build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built .deb package onto",
"terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress += 1",
"available in which to place documentation if create_changelog or create_copyright:",
"parent=build_progress): # Couldn't call md5sum command build_progress.Cancel() progress += 1",
"TODO: Doxygen # # TODO: Use string names in project",
"script task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"= u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file is",
"return (dbrerrno.ECNCLD, None) # Create final control file UpdateProgress(progress, GT(u'Creating",
"dialog for better fit pb_size = prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200,",
"Logger.Debug(__name__, u'Setting lintian tags failed') return False ## TODO: Doxygen",
"= u'�' index += 1 build_status = (build_status[0], u''.join(build_output)) #",
"IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data) ## TODO: Doxygen",
"summary when \"Build\" page is shown # Get the file",
"= commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress",
"import TextIsEmpty from globals.system import PY_VER_MAJ from globals.tooltips import SetPageToolTips",
"to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if exe: Logger.Debug(__name__, u'Adding",
"Logger.Debug(__name__, u'Lintian tags set') # DEBUG: Start if DebugEnabled() and",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Delete staged",
"becuase dpkg seems to have problems with spaces in path",
"chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item in required: if TextIsEmpty(item.GetValue()): field_name",
"package to be installed def InstallPackage(self, package): system_installer = GetSystemInstaller()",
"changelog_target = ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1])",
"install_output.returncode: err_details = ( GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command executed:",
"system's package installer: # gdebi if available or dpkg #",
"system self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after build'), name=u'INSTALL',",
"that this could take a while # TODO: Add cancel",
"(dbrerrno.ECNCLD, None) # Characters that should not be in filenames",
"denotes that an alternate tooltip should be shown if the",
"Logger.Info(__name__, GT(u'Attempting to install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer))",
"lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2,",
"(dbrerrno.ECNCLD, None) # *** Final build *** # UpdateProgress(progress, GT(u'Running",
"title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None) # Actual path to new",
"if DebugEnabled() and len(lint_tags) > 50: print(u' Reducing tag count",
"code & build details def BuildPrep(self): # Declare these here",
"Declare this here in case of error before progress dialog",
"return True else: Logger.Debug(__name__, u'Setting lintian tags failed') return False",
"Overrides'), allow_custom=True) # FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected",
"(dbrerrno.ECNCLD, None) # *** md5sums file *** # # Good",
"None) package = GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure that the",
"# Close progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list,",
"Page(WizardPage): ## Constructor # # \\param parent # Parent <b><i>wx.Window</i></b>",
"[] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L))",
"GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER)",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Strip files ***#",
"u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for F in FILES: F =",
"projects that use # integer values. def Set(self, data): #",
"build_progress.Destroy() # Build completed successfullly if not build_status[0]: return (dbrerrno.SUCCESS,",
"filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, & build pages not",
"build tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE',",
"errors).ShowModal() progress += 1 # Close progress dialog wx.Yield() build_progress.Update(progress)",
"not save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0]",
"[] options = ( self.chk_md5, self.chk_rmstage, self.chk_lint, ) for O",
"# TODO: Show warning dialog that this could take a",
"script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts') if len(scripts_to_make): scripts_to_make = u'{}:",
"feature \"lintian overrides\" option') self.lint_overrides = [] btn_lint_overrides = CreateButton(self,",
"launcher *** # if u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating menu",
"hashes before populating DEBIAN directory if u'md5sums' in task_list: UpdateProgress(progress,",
"details def BuildPrep(self): # Declare these here in case of",
"print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for T in task_list: print(u'\\t{}'.format(T)) create_changelog",
"CHK in pnl_options.Children: row = next_row FLAGS = lyt.PAD_LR if",
"u'strip' in build_data) ## TODO: Doxygen def SetSummary(self, event=None): pg_scripts",
"UpdateProgress(progress, GT(u'Creating menu launcher')) # This might be changed later",
"ShowErrorDialog(GT(u'Package build failed with unknown error')) return if build_prep: ShowErrorDialog(GT(u'Build",
"(dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None): task_eval = u'{} / {}'.format(current_task,",
"ui.dialog import ShowErrorDialog from ui.layout import BoxSizer from ui.output import",
"trailing newline # Two '\\n' to show physical empty line,",
"InstallPackage(self, package): system_installer = GetSystemInstaller() if not system_installer: ShowErrorDialog( GT(u'Cannot",
"should not be in filenames invalid_chars = (u' ', u'/')",
"package = fld_package.GetValue() # Remove whitespace package = package.strip(u' \\t')",
"GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count') file_count = u'{}: {}'.format(f, files_total)",
"u'stage', u'install_size', u'control', u'build', ) # Add other mandatory tasks",
"F) if os.access(F, os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F, 0o0644) #",
"return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen def GetSaveData(self): build_list =",
"wizard_page.Get() progress += 1 for task_check, id_string in other_checks: wx.Yield()",
"# \\b \\e unicode|str : Path to package to be",
"(pgid.COPYRIGHT, u'copyright'), ) # Install step is not added to",
"options = ( self.chk_md5, self.chk_rmstage, self.chk_lint, ) for O in",
"import ICON_INFORMATION from globals.errorcodes import dbrerrno from globals.execute import ExecuteCommand",
"= None progress += 1 # Close progress dialog wx.Yield()",
"wiz.wizard import WizardPage ## Build page class Page(WizardPage): ## Constructor",
"# Move the working directory becuase dpkg seems to have",
"PY_VER_MAJ from globals.tooltips import SetPageToolTips from input.toggle import CheckBox from",
"u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count =",
") return Logger.Info(__name__, GT(u'Attempting to install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing",
"script for updating progress dialog if u'scripts' in task_list: task_count",
"*** Files *** # if u'files' in task_list: UpdateProgress(progress, GT(u'Copying",
"ROOT != DIR_debian: F = ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__,",
"executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An error occurred during installation'),",
"globals.execute import ExecuteCommand from globals.execute import GetExecutable from globals.execute import",
"FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T",
"(pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) # Install step",
"to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding directory to",
"file is missing: {}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True))",
"= u'install»' self.chk_install.col = 0 # *** Lintian Overrides ***",
"in invalid_chars: menu_filename = menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir)",
"# 'stage' should be very first task task_list = {}",
"# 'build' should be after 'control' other_checks = ( (self.chk_md5,",
"ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) #",
"FIXME: Needs only be run if 'files' step is used",
"os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, & build pages",
"{}'.format(__name__, task_msg)) for T in task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog'",
"md5sum command build_progress.Cancel() progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"import TimedProgressDialog from ui.style import layout as lyt from wiz.helper",
"u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir) except",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Delete staged directory ***",
"to default directory changelog_target = task_list[u'changelog'][0] if changelog_target == u'STANDARD':",
"physical empty line, but not required # Perhaps because string",
"u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() # Remove invalid characters from filename",
"files_data: file_defs = FILE.split(u' -> ') source_file = file_defs[0] target_file",
"u'build', ) # Add other mandatory tasks for T in",
"next_row = 0 prev_row = next_row for CHK in pnl_options.Children:",
"(dbrerrno.ECNCLD, None) package = GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure that",
"os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual scripts progress +=",
"def OnBuild(self, event=None): # Build preparation ret_code, build_prep = self.BuildPrep()",
"TextIsEmpty from globals.system import PY_VER_MAJ from globals.tooltips import SetPageToolTips from",
"try: # List of tasks for build process # 'stage'",
"build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation failed with",
"dpkg # # Shows a success dialog if installed. Otherwise",
"create_changelog or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir):",
"= CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for errors with lintian'), name=u'LINTIAN',",
"= CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',))",
"be in filenames invalid_chars = (u' ', u'/') # ***",
"(dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name)) # Get information from control",
"override: {}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting lintian tags",
"ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress += 1",
"coding: utf-8 -*- ## \\package wizbin.build # MIT licensing #",
"None: ShowErrorDialog( GT(u'Could not install package: {}'), GT(u'An unknown error",
"os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog *** # if create_changelog: UpdateProgress(progress,",
"FIXME: Use ExecuteCommand here install_output = subprocess.Popen(install_cmd) # Command appears",
"functions module def _copy(f_src, f_tgt, exe=False): # NOTE: Python 3",
"prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] =",
"Logger.Debug(__name__, u'Adding file to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set",
"destroyed so no error is thrown if self: # Set",
"ui.panel import BorderedPanel from ui.progress import PD_DEFAULT_STYLE from ui.progress import",
"in task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if not WriteMD5(stage_dir, parent=build_progress): #",
"build_path # \\b \\e unicode|str : Directory where .deb will",
"required = list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME))",
"Create final control file UpdateProgress(progress, GT(u'Creating control file')) # dpkg",
"import ConcatPaths from globals.paths import PATH_app from globals.strings import GS",
"control_data, noStrip=u'\\n') progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"filename)) except: if save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN,",
"process # 'stage' should be very first task task_list =",
"from globals.errorcodes import dbrerrno from globals.execute import ExecuteCommand from globals.execute",
"should be after 'control' other_checks = ( (self.chk_md5, u'md5sums'), (self.chk_strip,",
"(u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script in scripts: if script[1].IsChecked():",
"title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting",
"if changelog_target == u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target",
"DEBUG: End tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{}",
"task task_list = {} # Control page pg_control = GetPage(pgid.CONTROL)",
"(build_status[0], build_status[1]) except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO:",
"# \\b \\e unicode|str : Directory where .deb will be",
"None) # *** Scripts *** # if u'scripts' in task_list:",
"error before dialogs created save_dia = None prebuild_progress = None",
"for errors with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»'",
"null terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress +=",
"names in project file but retain # compatibility with older",
"len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message, count, GT(u'tags'))",
"shutil, subprocess, traceback, wx from dbr.functions import FileUnstripped from dbr.language",
"= u'lintian»' self.chk_lint.col = 0 # Installs the deb on",
"(u'postrm', pg_scripts.chk_postrm)) for script in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s",
"alternate tooltip should be shown if the control is disabled",
"TODO: Use string names in project file but retain #",
"SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS) # Make sure the page",
"\\b \\e dict : Task string IDs & page data",
"name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0 # Checks the output .deb",
"Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T in",
"prebuild_progress.CenterOnParent() for PID, id_string in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string))",
"progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build completed successfullly if",
"task_list create_copyright = u'copyright' in task_list pg_control = GetPage(pgid.CONTROL) pg_menu",
"follow_symlinks option for shutil.copy # FIXME: copying nested symbolic link",
"# Control, menu, & build pages not added to this",
"result: ShowErrorDialog(GT(u'Package build failed'), result) else: ShowErrorDialog(GT(u'Package build failed with",
"fileio.fileio import ReadFile from fileio.fileio import WriteFile from globals.bitmaps import",
"return (dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] #",
"task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) # Make a",
"tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message,",
"DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) # Make a fresh build tree",
"{} # Control page pg_control = GetPage(pgid.CONTROL) fld_package = GetField(pg_control,",
"= GetSystemInstaller() if not system_installer: ShowErrorDialog( GT(u'Cannot install package'), GT(u'A",
"len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make =",
"return success code if install_output.returncode: err_details = ( GT(u'Process returned",
"# *** Changelog *** # if create_changelog: UpdateProgress(progress, GT(u'Creating changelog'))",
"for: {}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] = None progress += 1",
"= ( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'),",
") for O in options: if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0')",
"= self.BuildPrep() if ret_code == dbrerrno.ECNCLD: return if ret_code ==",
"DebugEnabled from dbr.log import Logger from dbr.md5 import WriteMD5 from",
"Strip command should be set as class member? ExecuteCommand(GetExecutable(u'strip'), F)",
"import CheckListDialog from ui.dialog import DetailedMessageDialog from ui.dialog import ShowErrorDialog",
"to have follow_symlinks option for shutil.copy # FIXME: copying nested",
"+= 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task,",
"None try: # Other mandatory tasks that will be processed",
"shows an # error dialog. # \\param package # \\b",
"1 UpdateProgress(progress) # Entire file task progress += 1 if",
"globals.ident import pgid from globals.paths import ConcatPaths from globals.paths import",
"dpkg-deb executables build_status = commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'),",
"except OSError: ShowErrorDialog(GT(u'An error occurred when trying to delete the",
"Menu launcher page pg_launcher = GetPage(pgid.MENU) # Check to make",
"required fields have values required = list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher']",
"changelog')) # If changelog will be installed to default directory",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Characters that should",
"D = u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for F in FILES:",
"from globals.bitmaps import ICON_INFORMATION from globals.errorcodes import dbrerrno from globals.execute",
"SCRIPT script_text = scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename,",
"CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64) # Display log dsp_log =",
"in FILES: F = u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK): os.chmod(F,",
"# Set FILE permissions if exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt,",
"is wrapped in quotes to avoid whitespace errors os.chmod(script_filename, 0755)",
"in build_output: try: GS(C) except UnicodeDecodeError: build_output[index] = u'�' index",
"filename = build_prep # Actual build ret_code, result = self.Build(task_list,",
"system'), __name__, warn=True ) return Logger.Info(__name__, GT(u'Attempting to install package:",
"GetSystemInstaller from globals.ident import btnid from globals.ident import chkid from",
"TimedProgressDialog from ui.style import layout as lyt from wiz.helper import",
"with the package.') e2 = GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path,",
"task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian",
"command build_progress.Cancel() progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method that",
"package = u'-'.join(package.split(u' ')) version = fld_version.GetValue() # Remove whitespace",
"install_output = subprocess.Popen(install_cmd) # Command appears to not have been",
"build_prep) else: ShowErrorDialog(GT(u'Build preparation failed with unknown error')) ## TODO:",
"message=None): task_eval = u'{} / {}'.format(current_task, task_count) if message: Logger.Debug(__name__,",
"item in required: if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name =",
"build_prep)) err_dia.ShowModal() err_dia.Destroy() return if ret_code == dbrerrno.SUCCESS: task_list, build_path,",
"Close progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path,",
"that will be processed mandatory_tasks = ( u'stage', u'install_size', u'control',",
"/ {}'.format(current_task, task_count) if message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield()",
"# if u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing temp directory')) try:",
"progress dialog if u'files' in task_list: task_count += len(task_list[u'files']) #",
"progress += 1 for task_check, id_string in other_checks: wx.Yield() prebuild_progress.Update(progress,",
"wx.Yield() build_progress.Update(current_task) # *** Files *** # if u'files' in",
"0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'):",
"# \\param filename # \\b \\e unicode|str : Basename of",
"= CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col =",
"control file control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress +=",
"if script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts') if len(scripts_to_make): scripts_to_make =",
"whitespace version = version.strip(u' \\t') version = u''.join(version.split()) arch =",
"= TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield()",
"u'*': exe = True source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)),",
"whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual scripts",
"builds the actual Debian package # # \\param task_list #",
"0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding file",
"from globals.execute import GetSystemInstaller from globals.ident import btnid from globals.ident",
"== dbrerrno.SUCCESS: task_list, build_path, filename = build_prep # Actual build",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None): task_eval =",
"if len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make",
"thrown if self: # Set summary when \"Build\" page is",
"dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T in lint_tags: if",
"label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'), u'build',",
"from input.toggle import CheckBoxESS from startup.tests import UsingTest from ui.button",
"pb_size = prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for",
"install_output == None: ShowErrorDialog( GT(u'Could not install package: {}'), GT(u'An",
"else: os.chmod(F, 0o0644) # FIXME: Should check for working fakeroot",
"unicode|str : Path to package to be installed def InstallPackage(self,",
"None try: # List of tasks for build process #",
"in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts') if len(scripts_to_make):",
"the deb on the system self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install",
"({} {})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'),",
"cached so no need for re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__,",
"task_count += len(task_list[u'files']) # Add each script for updating progress",
"executable to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file to stage:",
"GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress += 1 for",
"in task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog' in task_list create_copyright =",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None): task_eval = u'{}",
"if 'files' step is used if u'strip' in task_list: UpdateProgress(progress,",
"pg_menu = GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try:",
"if install_output.returncode: err_details = ( GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command",
"return if result: ShowErrorDialog(GT(u'Package build failed'), result) else: ShowErrorDialog(GT(u'Package build",
"{}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting lintian tags failed')",
"if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal()",
"# List of tasks for build process # 'stage' should",
"(pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string in page_checks: wx.Yield()",
"compatibility with older projects that use # integer values. def",
"into control file control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress",
"not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress += 1 if",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** ERROR CHECK",
"# Dialog for save destination ttype = GT(u'Debian packages') save_dia",
"file to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set FILE permissions",
"u'Adding directory symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else:",
"Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End tag_count = len(lint_tags)",
"error before progress dialog created build_progress = None try: #",
"GT(u'Creating menu launcher')) # This might be changed later to",
"DIRS: D = u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for F in",
"Remaining tags should be custom entries # FIXME: if self.lint_overrides:",
"for errors')) # FIXME: Should be set as class memeber?",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Scripts *** # if",
"Add other mandatory tasks for T in mandatory_tasks: task_list[T] =",
"import PATH_app from globals.strings import GS from globals.strings import RemoveEmptyLines",
"GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move this",
"be after 'control' other_checks = ( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'),",
"file for updating progress dialog if u'files' in task_list: task_count",
"GT(u'Checking package for errors')) # FIXME: Should be set as",
"String & unicode string incompatibilities index = 0 for C",
"tags set') # DEBUG: Start if DebugEnabled() and len(lint_tags) >",
"ui.style import layout as lyt from wiz.helper import FieldEnabled from",
"= task_list[u'changelog'][0] if changelog_target == u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package))",
"shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not free stage directory: {}').format(stage_dir), title=GT(u'Cannot",
"characters. Replace any # non-decodable characters with � (0xFFFD). build_output",
"of error before progress dialog created build_progress = None try:",
"{}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for T in task_list: print(u'\\t{}'.format(T))",
"CHK.col: prev_row = next_row next_row += 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout()",
"< 3: # Resize dialog for better fit pb_size =",
"unknown error')) ## TODO: Doxygen # # TODO: Show warning",
"to this list # 'control' should be after 'md5sums' #",
"be run if 'files' step is used if u'strip' in",
"e2 = GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress,",
"sure the page is not destroyed so no error is",
"before progress dialog created build_progress = None try: # Other",
"tooltip should be shown if the control is disabled self.chk_md5.tt_name",
"u'{} ({} {})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag",
"DEBIAN directory if ROOT != DIR_debian: F = ConcatPaths((ROOT, F))",
"except: if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen #",
"package for errors')) # FIXME: Should be set as class",
"inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL) fields_control",
"GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL)",
"for build process # 'stage' should be very first task",
"chkid.INSTALL, GT(u'Install package after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name =",
"-n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could",
"from ui.checklist import CheckListDialog from ui.dialog import DetailedMessageDialog from ui.dialog",
"occurred during installation'), u'\\n'.join(err_details), __name__ ) return ## TODO: Doxygen",
"# TODO: move this into a file functions module def",
"GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get()",
"installed def InstallPackage(self, package): system_installer = GetSystemInstaller() if not system_installer:",
"alpha feature \"lintian overrides\" option') self.lint_overrides = [] btn_lint_overrides =",
"deb_package))) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"binaries')) for ROOT, DIRS, FILES in os.walk(stage_dir): #@UnusedVariable for F",
"== dbrerrno.ECNCLD: return if ret_code == dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(),",
"# Declare these here in case of error before dialogs",
"globals.paths import PATH_app from globals.strings import GS from globals.strings import",
"make sure that all required fields have values required =",
"...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG:",
"*** Final build *** # UpdateProgress(progress, GT(u'Running dpkg')) working_dir =",
"WizardPage ## Build page class Page(WizardPage): ## Constructor # #",
"FILES: # Don't check files in DEBIAN directory if ROOT",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Scripts *** #",
"return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name)) # Get information from",
"= os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) # Move",
"= lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags))) # DEBUG: End tag_count",
"pg_control = GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control,",
"shown # Get the file count files_total = GetPage(pgid.FILES).GetFileCount() f",
"# NOTE: Python 3 appears to have follow_symlinks option for",
"*** Changelog *** # if create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) #",
"DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress += 1",
"if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) # FIXME: Strip command",
"exe=False): # NOTE: Python 3 appears to have follow_symlinks option",
"prep_task_count = len(page_checks) + len(other_checks) progress = 0 wx.Yield() prebuild_progress",
"== dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of",
"Control page pg_control = GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE) fld_version",
"btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout *** # lyt_options = wx.GridBagSizer()",
"Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) if",
"added to this list # 'control' should be after 'md5sums'",
"except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if GetExecutable(u'lintian'):",
"fix file/dir permissions for ROOT, DIRS, FILES in os.walk(stage_dir): for",
"task_list[u'files'] for FILE in files_data: file_defs = FILE.split(u' -> ')",
"Display log dsp_log = OutputLog(self) SetPageToolTips(self) # *** Event Handling",
"1 # Close progress dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS,",
"build_status[0]: return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <= 2: # Unicode",
"index += 1 build_status = (build_status[0], u''.join(build_output)) # Build failed",
"err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required",
"dict : Task string IDs & page data # \\param",
"(dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control,",
"unicode|str : Directory where .deb will be output # \\param",
"5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log,",
"u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built .deb package onto the system",
"for script in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts')",
"target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file) if not",
"scripts progress += 1 UpdateProgress(progress) # Entire script task progress",
"installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size =",
"memeber? CMD_lintian = GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if",
"string is not null terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data,",
"u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog ***",
"# lyt_options = wx.GridBagSizer() next_row = 0 prev_row = next_row",
"u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if not WriteMD5(stage_dir, parent=build_progress):",
"» character denotes that an alternate tooltip should be shown",
"\"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not compress",
"# Remaining tags should be custom entries # FIXME: if",
"to make scripts_to_make = [] scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst',",
"installed_size[0].split(u'\\t') installed_size = installed_size[0] # Insert Installed-Size into control file",
"this list # 'control' should be after 'md5sums' # 'build'",
"pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string in",
"self.chk_rmstage.col = 0 # Checks the output .deb for errors",
"the system'), __name__, warn=True ) return Logger.Info(__name__, GT(u'Attempting to install",
"= ( self.chk_md5, self.chk_rmstage, self.chk_lint, ) for O in options:",
"decoder has trouble with certain characters. Replace any # non-decodable",
"not install package: {}'), GT(u'An unknown error occurred'), __name__ )",
"ui.progress import PD_DEFAULT_STYLE from ui.progress import ProgressDialog from ui.progress import",
"= version.strip(u' \\t') version = u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection()",
"no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move this into a",
"HACK to fix file/dir permissions for ROOT, DIRS, FILES in",
"***# # FIXME: Needs only be run if 'files' step",
"= pg_menu.GetOutputFilename() # Remove invalid characters from filename for char",
"for T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() ==",
"err_dia.ShowModal() err_dia.Destroy() return if ret_code == dbrerrno.SUCCESS: task_list, build_path, filename",
"*** Lintian Overrides *** # if UsingTest(u'alpha'): # FIXME: Move",
"in os.walk(stage_dir): for D in DIRS: D = u'{}/{}'.format(ROOT, D)",
"package): system_installer = GetSystemInstaller() if not system_installer: ShowErrorDialog( GT(u'Cannot install",
"ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress += 1 # Close progress",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Final build",
"os.chmod(f_tgt, 0o0644) files_data = task_list[u'files'] for FILE in files_data: file_defs",
"success code if install_output.returncode: err_details = ( GT(u'Process returned code",
"md5sums file *** # # Good practice to create hashes",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Delete",
"None) # *** ERROR CHECK if u'lintian' in task_list: UpdateProgress(progress,",
"import ProgressDialog from ui.progress import TimedProgressDialog from ui.style import layout",
"# *** Scripts *** # if u'scripts' in task_list: UpdateProgress(progress,",
"64) # Display log dsp_log = OutputLog(self) SetPageToolTips(self) # ***",
"the actual Debian package # # \\param task_list # \\b",
"package: {}'), GT(u'An unknown error occurred'), __name__ ) return #",
"dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() # Installing the",
"pg_launcher = GetPage(pgid.MENU) # Check to make sure that all",
"# Actual build ret_code, result = self.Build(task_list, build_path, filename) #",
"& unicode string incompatibilities index = 0 for C in",
"Get information from control page for default filename package =",
"lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main)",
"task_list: task_count += len(task_list[u'files']) # Add each script for updating",
"to have problems with spaces in path os.chdir(working_dir) # HACK",
"GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'),",
"return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <= 2: # Unicode decoder",
"progress dialog created build_progress = None try: # Other mandatory",
"in task_list create_copyright = u'copyright' in task_list pg_control = GetPage(pgid.CONTROL)",
"page pg_launcher = GetPage(pgid.MENU) # Check to make sure that",
"information from control page for default filename package = fld_package.GetValue()",
"task_list[T] = None task_count = len(task_list) # Add each file",
"GT(u'Installing with {}').format(system_installer)) install_cmd = (system_installer, package,) wx.Yield() # FIXME:",
"& page data # \\param build_path # \\b \\e unicode|str",
"self.OnBuild) # *** Layout *** # lyt_options = wx.GridBagSizer() next_row",
"# \\return # \\b \\e tuple containing Return code &",
"\"lintian overrides\" option') self.lint_overrides = [] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian",
"BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'), name=u'MD5', defaultValue=True,",
"import GT from dbr.log import DebugEnabled from dbr.log import Logger",
"fresh build tree os.makedirs(DIR_debian) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src):",
"else: Logger.Debug(__name__, u'Adding file to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) #",
"else: os.chmod(f_tgt, 0o0644) files_data = task_list[u'files'] for FILE in files_data:",
"== wx.ID_OK: # Remove old overrides self.lint_overrides = [] for",
"wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build completed successfullly if not build_status[0]:",
"if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list))",
"from globals.execute import ExecuteCommand from globals.execute import GetExecutable from globals.execute",
"globals.paths import ConcatPaths from globals.paths import PATH_app from globals.strings import",
"for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L)",
"Copyright *** # if create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package),",
"+= 1 build_status = (build_status[0], u''.join(build_output)) # Build failed return",
"ret_code == dbrerrno.SUCCESS: task_list, build_path, filename = build_prep # Actual",
"= [] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build",
"to 200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing {} tags'.format(len(lint_tags)))",
"return (dbrerrno.ECNCLD, None) # Characters that should not be in",
"= fld_version.GetValue() # Remove whitespace version = version.strip(u' \\t') version",
"stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file to stage: {}'.format(f_tgt)) shutil.copy(f_src,",
"[] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build =",
"deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0 task_msg = GT(u'Preparing",
"with certain characters. Replace any # non-decodable characters with �",
"DebugEnabled() and len(lint_tags) > 50: print(u' Reducing tag count to",
"Layout *** # lyt_options = wx.GridBagSizer() next_row = 0 prev_row",
"for T in lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T)",
"prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string",
"data): # ???: Redundant self.Reset() build_data = data.split(u'\\n') if GetExecutable(u'md5sum'):",
"overrides\" option') self.lint_overrides = [] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides'))",
"changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"+= len(task_list[u'files']) # Add each script for updating progress dialog",
"output # \\param filename # \\b \\e unicode|str : Basename",
"be cached so no need for re-scanning def OnSetLintOverrides(self, event=None):",
"parent): WizardPage.__init__(self, parent, pgid.BUILD) # ----- Extra Options pnl_options =",
"os.path.basename(source_file)), exe) # Individual files progress += 1 UpdateProgress(progress) #",
"GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not",
"with spaces in path os.chdir(working_dir) # HACK to fix file/dir",
"file_defs[1]) target_dir = os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove",
"import GetExecutable from globals.execute import GetSystemInstaller from globals.ident import btnid",
"not in fields_control: page_name = pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜",
"create_changelog = u'changelog' in task_list create_copyright = u'copyright' in task_list",
"# FIXME: Should be set as class memeber? CMD_lintian =",
"executed correctly if install_output == None: ShowErrorDialog( GT(u'Could not install",
"could take a while # TODO: Add cancel option to",
"wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path = os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0]",
"globals.system import PY_VER_MAJ from globals.tooltips import SetPageToolTips from input.toggle import",
"import PY_VER_MAJ from globals.tooltips import SetPageToolTips from input.toggle import CheckBox",
"is only one empty trailing newline # Two '\\n' to",
"(u' ', u'/') # *** Menu launcher *** # if",
"not added to this list page_checks = ( (pgid.FILES, u'files'),",
"build_progress.Cancel() progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"whitespace package = package.strip(u' \\t') package = u'-'.join(package.split(u' ')) version",
"package = package.strip(u' \\t') package = u'-'.join(package.split(u' ')) version =",
"1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main",
"Make sure that the directory is available in which to",
"'control' should be after 'md5sums' # 'build' should be after",
"from ui.progress import TimedProgressDialog from ui.style import layout as lyt",
"from globals.paths import ConcatPaths from globals.paths import PATH_app from globals.strings",
"exe = False if source_file[-1] == u'*': exe = True",
"GT(u'Getting installed size')) # Get installed-size installed_size = os.popen((u'du -hsk",
"from dbr.log import DebugEnabled from dbr.log import Logger from dbr.md5",
"scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts') if len(scripts_to_make): scripts_to_make",
"*** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout *** # lyt_options",
"( u'stage', u'install_size', u'control', u'build', ) # Add other mandatory",
"successfully')).ShowModal() # Installing the package if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result)",
"# \\b \\e dict : Task string IDs & page",
"u'Enabling alpha feature \"lintian overrides\" option') self.lint_overrides = [] btn_lint_overrides",
"!= wx.EmptyString: e1 = GT(u'Lintian found some issues with the",
"input.toggle import CheckBoxESS from startup.tests import UsingTest from ui.button import",
"= os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) # Move the working directory",
"import dbrerrno from globals.execute import ExecuteCommand from globals.execute import GetExecutable",
"= lyt.PAD_LR if CHK.col: row = prev_row FLAGS = wx.RIGHT",
"Doxygen # # \\return # \\b \\e tuple containing Return",
"DetailedMessageDialog from ui.dialog import ShowErrorDialog from ui.layout import BoxSizer from",
"u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col = 0 # *** Lintian",
"Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress += 1 # Close",
"u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking package for errors')) # FIXME:",
"Build preparation ret_code, build_prep = self.BuildPrep() if ret_code == dbrerrno.ECNCLD:",
"and self.chk_install.GetValue(): self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package build failed'), result)",
"file task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"if the control is disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col =",
"commands, os, shutil, subprocess, traceback, wx from dbr.functions import FileUnstripped",
"final control file UpdateProgress(progress, GT(u'Creating control file')) # dpkg fails",
"package timestamp to confirm build success if ret_code == dbrerrno.SUCCESS:",
"fit pb_size = prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent()",
"if build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation failed",
"if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher,",
"licensing # See: docs/LICENSE.txt import commands, os, shutil, subprocess, traceback,",
"return (dbrerrno.ECNCLD, None) # *** Control file *** # UpdateProgress(progress,",
"inputid from globals.ident import pgid from globals.paths import ConcatPaths from",
"\\param build_path # \\b \\e unicode|str : Directory where .deb",
"def SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS) # Make sure the",
"os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not free stage directory:",
"u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0 task_msg = GT(u'Preparing build tree')",
"of file control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure there is only",
"file_defs = FILE.split(u' -> ') source_file = file_defs[0] target_file =",
"u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT, DIRS, FILES",
"check box Logger.Info(__name__, u'Enabling alpha feature \"lintian overrides\" option') self.lint_overrides",
"\\b \\e unicode|str : Basename of output file without .deb",
"Other mandatory tasks that will be processed mandatory_tasks = (",
"## TODO: Doxygen # # \\return # \\b \\e tuple",
"that builds the actual Debian package # # \\param task_list",
"def GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message, count, GT(u'tags')) progress",
"dpkg fails if there is no newline at end of",
"# Checks the output .deb for errors self.chk_lint = CheckBoxESS(pnl_options,",
"to be installed def InstallPackage(self, package): system_installer = GetSystemInstaller() if",
"False ## TODO: Doxygen # # TODO: Use string names",
"os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic link",
"created save_dia = None prebuild_progress = None try: # List",
"return ## TODO: Doxygen def OnBuild(self, event=None): # Build preparation",
"only be run if 'files' step is used if u'strip'",
"ShowErrorDialog(GT(u'An error occurred when trying to delete the build tree'),",
"destination ttype = GT(u'Debian packages') save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(),",
"ttype = GT(u'Debian packages') save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString,",
"Return code & build details def BuildPrep(self): # Declare these",
"return (dbrerrno.ECNCLD, None) # *** Strip files ***# # FIXME:",
"mandatory tasks for T in mandatory_tasks: task_list[T] = None task_count",
"install package'), GT(u'A compatible package manager could not be found",
"script in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s = GT(u'Scripts') if",
"task_eval)) wx.Yield() build_progress.Update(current_task, message) return wx.Yield() build_progress.Update(current_task) # *** Files",
"Good practice to create hashes before populating DEBIAN directory if",
"= u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could",
"when \"Build\" page is shown # Get the file count",
"if not WriteMD5(stage_dir, parent=build_progress): # Couldn't call md5sum command build_progress.Cancel()",
"ConcatPaths((stage_dir, u'DEBIAN')) # Make a fresh build tree os.makedirs(DIR_debian) progress",
"tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count,",
"\\e tuple containing Return code & build details def BuildPrep(self):",
"GetMainWindow from wiz.helper import GetPage from wiz.wizard import WizardPage ##",
"globals.strings import GS from globals.strings import RemoveEmptyLines from globals.strings import",
"DIRS, FILES in os.walk(stage_dir): for D in DIRS: D =",
"required.append(GetField(pg_launcher, inputid.FNAME)) for item in required: if TextIsEmpty(item.GetValue()): field_name =",
"self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining tags",
"here in case of error before progress dialog created build_progress",
"required fields is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return if ret_code",
"overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64)",
"changelog_target = task_list[u'changelog'][0] if changelog_target == u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir),",
"# Get information from control page for default filename package",
"GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"arch)) if not save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path",
"f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__,",
"## TODO: Doxygen def OnBuild(self, event=None): # Build preparation ret_code,",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Create final control file UpdateProgress(progress,",
"5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT, 5)",
"ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from globals.errorcodes import dbrerrno from",
"= installed_size[0] # Insert Installed-Size into control file control_data =",
"tags'), len(self.lint_overrides))) # Remaining tags should be custom entries #",
"pg_scripts.chk_postrm)) for script in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0]) s =",
"row = next_row FLAGS = lyt.PAD_LR if CHK.col: row =",
"overrides'))) for T in lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T)",
"if ret_code == dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION,",
"{}').format(u' '.join(install_cmd)), ) ShowErrorDialog( GT(u'An error occurred during installation'), u'\\n'.join(err_details),",
"Installs the deb on the system self.chk_install = CheckBox(pnl_options, chkid.INSTALL,",
"tag count to 200 ...') lint_tags = lint_tags[:50] Logger.Debug(__name__, u'Processing",
"u'{}: {}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make = u'{}: 0'.format(s) self.summary.SetValue(u'\\n'.join((file_count,",
"create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) # If changelog will be installed",
"self.chk_rmstage, self.chk_lint, ) for O in options: if O.GetValue(): build_list.append(u'1')",
"error occurred'), __name__ ) return # Command executed but did",
"path is wrapped in quotes to avoid whitespace errors os.chmod(script_filename,",
"self.SetSizer(lyt_main) self.Layout() ## Method that builds the actual Debian package",
"fields have values required = list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] =",
"globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from globals.errorcodes import",
"= ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target = ConcatPaths((stage_dir, changelog_target)) if not",
"# *** Copyright *** # if create_copyright: UpdateProgress(progress, GT(u'Creating copyright'))",
"WriteMD5 from fileio.fileio import ReadFile from fileio.fileio import WriteFile from",
"stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if exe: Logger.Debug(__name__, u'Adding executable",
"= FILE.split(u' -> ') source_file = file_defs[0] target_file = u'{}{}/{}'.format(stage_dir,",
"{}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt)",
"Couldn't call md5sum command build_progress.Cancel() progress += 1 if build_progress.WasCancelled():",
"TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() #",
"= prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5)",
"os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F, 0o0644) # FIXME: Should check",
"where .deb will be output # \\param filename # \\b",
"and no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic link to stage: {}'.format(f_tgt))",
"End tag_count = len(lint_tags) def GetProgressMessage(message, count=tag_count): return u'{} ({}",
"prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen def GetSaveData(self): build_list",
"self.chk_md5.col = 0 # Option to strip binaries self.chk_strip =",
"btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'), u'build', 64) # Display log",
"= None prebuild_progress = None try: # List of tasks",
"os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual scripts progress += 1 UpdateProgress(progress)",
"-hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size = installed_size[0] # Insert",
"= u'copyright' in task_list pg_control = GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU)",
"Command appears to not have been executed correctly if install_output",
"style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN')) # Make a fresh build",
"--best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not",
"import Logger from dbr.md5 import WriteMD5 from fileio.fileio import ReadFile",
"s = GT(u'Scripts') if len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s, u',",
"system_installer = GetSystemInstaller() if not system_installer: ShowErrorDialog( GT(u'Cannot install package'),",
"menu_filename), task_list[u'launcher']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass",
"filename) progress = 0 task_msg = GT(u'Preparing build tree') Logger.Debug(__name__,",
"CheckBox from input.toggle import CheckBoxESS from startup.tests import UsingTest from",
"used if u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT,",
"# *** Files *** # if u'files' in task_list: UpdateProgress(progress,",
"if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item in required:",
"overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return True else:",
"# Other mandatory tasks that will be processed mandatory_tasks =",
"working_dir = os.path.split(stage_dir)[0] c_tree = os.path.split(stage_dir)[1] deb_package = u'{}.deb'.format(filename) #",
"CMD_lintian = GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors",
"os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding file symbolic link to stage:",
"[] scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm',",
"= wizard_page.Get() progress += 1 for task_check, id_string in other_checks:",
"if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not free stage",
"None) # Create final control file UpdateProgress(progress, GT(u'Creating control file'))",
") # Install step is not added to this list",
"Set FILE permissions if exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644)",
"populating DEBIAN directory if u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating md5sums'))",
"None) # *** Delete staged directory *** # if u'rmstage'",
"try: # Other mandatory tasks that will be processed mandatory_tasks",
"the system # # Uses the system's package installer: #",
"# Good practice to create hashes before populating DEBIAN directory",
"empty line, but not required # Perhaps because string is",
"ui.output import OutputLog from ui.panel import BorderedPanel from ui.progress import",
"TODO: Doxygen # # TODO: Show warning dialog that this",
"if ret_code == dbrerrno.SUCCESS: task_list, build_path, filename = build_prep #",
"= BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options,",
"page_checks = ( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT,",
"there is only one empty trailing newline # Two '\\n'",
"= ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for",
"DIR_debian: F = ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file:",
"is thrown if self: # Set summary when \"Build\" page",
"UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress += 1 if",
"message) return wx.Yield() build_progress.Update(current_task) # *** Files *** # if",
"*** # if u'files' in task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link",
"in os.walk(stage_dir): #@UnusedVariable for F in FILES: # Don't check",
"pages not added to this list page_checks = ( (pgid.FILES,",
"to progress dialog # FIXME: List should be cached so",
"False if source_file[-1] == u'*': exe = True source_file =",
"# FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for",
"GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL) fields_control = ( fld_package,",
"control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress += 1 if",
"1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT,",
"invalid_chars: menu_filename = menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir,",
"timestamp to confirm build success if ret_code == dbrerrno.SUCCESS: DetailedMessageDialog(GetMainWindow(),",
"UsingTest from ui.button import CreateButton from ui.checklist import CheckListDialog from",
"= u'changelog' in task_list create_copyright = u'copyright' in task_list pg_control",
"= [] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding Lintian override:",
"progress.Start() wx.Yield() # Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian",
"problems with spaces in path os.chdir(working_dir) # HACK to fix",
"if lint_tags: Logger.Debug(__name__, u'Lintian tags set') # DEBUG: Start if",
"# Command appears to not have been executed correctly if",
"# integer values. def Set(self, data): # ???: Redundant self.Reset()",
"+= 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Characters",
"Ensure there is only one empty trailing newline # Two",
"list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not",
"{} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress += 1",
"symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding",
"# Remove invalid characters from filename for char in invalid_chars:",
"link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if exe: Logger.Debug(__name__,",
"if u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir)",
"to make sure that all required fields have values required",
"import layout as lyt from wiz.helper import FieldEnabled from wiz.helper",
"if overrides_dialog.ShowModal() == wx.ID_OK: # Remove old overrides self.lint_overrides =",
"\\param parent # Parent <b><i>wx.Window</i></b> instance def __init__(self, parent): WizardPage.__init__(self,",
"lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0,",
"# Entire script task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if",
"= task_list[u'files'] for FILE in files_data: file_defs = FILE.split(u' ->",
"OutputLog from ui.panel import BorderedPanel from ui.progress import PD_DEFAULT_STYLE from",
"tree os.makedirs(DIR_debian) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD,",
"= (build_status[0], u''.join(build_output)) # Build failed return (build_status[0], build_status[1]) except:",
"parent # Parent <b><i>wx.Window</i></b> instance def __init__(self, parent): WizardPage.__init__(self, parent,",
"dialog wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path, filename)) except:",
"= task_list[u'scripts'] for SCRIPT in scripts: script_name = SCRIPT script_text",
"string names in project file but retain # compatibility with",
"build_list.append(u'0') if self.chk_strip.GetValue(): build_list.append(u'strip') return u'<<BUILD>>\\n{}\\n<</BUILD>>'.format(u'\\n'.join(build_list)) ## Installs the built",
"a success dialog if installed. Otherwise shows an # error",
"{}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd = (system_installer, package,) wx.Yield()",
"version = u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for",
"errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for errors with",
"warning dialog that this could take a while # TODO:",
"tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True)",
"extension # \\return # \\b \\e dbrerror : SUCCESS if",
".deb extension # \\return # \\b \\e dbrerror : SUCCESS",
"self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if",
"GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error occurred",
"errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress +=",
"is not destroyed so no error is thrown if self:",
"from globals.ident import btnid from globals.ident import chkid from globals.ident",
"u'scripts'), (pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) # Install step is",
"u'Adding file to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set FILE",
"box Logger.Info(__name__, u'Enabling alpha feature \"lintian overrides\" option') self.lint_overrides =",
"os.symlink(os.readlink(f_src), f_tgt) else: if exe: Logger.Debug(__name__, u'Adding executable to stage:",
"scripts_to_make = u'{}: {}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make = u'{}:",
"u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target = ConcatPaths((stage_dir, changelog_target))",
"shown if the control is disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col",
"task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher,",
"dialog # FIXME: List should be cached so no need",
"{}').format(task_check.GetLabel())) if task_check.GetValue(): task_list[id_string] = None progress += 1 #",
"return Logger.Info(__name__, GT(u'Attempting to install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Copyright ***",
"(0xFFFD). build_output = list(build_status[1]) # String & unicode string incompatibilities",
"package = GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure that the directory",
"T in task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog' in task_list create_copyright",
"BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')),",
"for errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for errors",
"no need for re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian",
"is available in which to place documentation if create_changelog or",
"# HACK to fix file/dir permissions for ROOT, DIRS, FILES",
"dialog if u'files' in task_list: task_count += len(task_list[u'files']) # Add",
"= ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT) DIR_debian = ConcatPaths((stage_dir, u'DEBIAN'))",
"build_prep # Actual build ret_code, result = self.Build(task_list, build_path, filename)",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Create final control",
"use # integer values. def Set(self, data): # ???: Redundant",
"parent, pgid.BUILD) # ----- Extra Options pnl_options = BorderedPanel(self) self.chk_md5",
"os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress += 1 if build_progress.WasCancelled():",
"# btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout *** # lyt_options =",
"call md5sum command build_progress.Cancel() progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"from startup.tests import UsingTest from ui.button import CreateButton from ui.checklist",
"pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string in page_checks: wx.Yield() prebuild_progress.Update(progress,",
"if os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic",
"in build_data) ## TODO: Doxygen def SetSummary(self, event=None): pg_scripts =",
"each script for updating progress dialog if u'scripts' in task_list:",
"package.') e2 = GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors)",
"(system_installer, package,) wx.Yield() # FIXME: Use ExecuteCommand here install_output =",
"page_name = pg_control.GetName() if item not in fields_control: page_name =",
"GT from dbr.log import DebugEnabled from dbr.log import Logger from",
"None) def UpdateProgress(current_task, message=None): task_eval = u'{} / {}'.format(current_task, task_count)",
"Check .deb package timestamp to confirm build success if ret_code",
"u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count = len(page_checks) +",
"= u'\\n'.join(control_data).strip(u'\\n') # Ensure there is only one empty trailing",
"Redundant self.Reset() build_data = data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except",
"progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) #",
"def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app)",
"0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ##",
"not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file is missing: {}'.format(lintian_tags_file)) return",
"output file without .deb extension # \\return # \\b \\e",
"retain # compatibility with older projects that use # integer",
"Individual files progress += 1 UpdateProgress(progress) # Entire file task",
"Two '\\n' to show physical empty line, but not required",
"= u''.join(version.split()) arch = GetField(pg_control, inputid.ARCH).GetStringSelection() # Dialog for save",
"delete the build tree'), parent=build_progress) progress += 1 if build_progress.WasCancelled():",
"Use ExecuteCommand here install_output = subprocess.Popen(install_cmd) # Command appears to",
"default directory changelog_target = task_list[u'changelog'][0] if changelog_target == u'STANDARD': changelog_target",
"to fix file/dir permissions for ROOT, DIRS, FILES in os.walk(stage_dir):",
"lintian check box Logger.Info(__name__, u'Enabling alpha feature \"lintian overrides\" option')",
"os.chmod(D, 0o0755) for F in FILES: F = u'{}/{}'.format(ROOT, F)",
"u''.join(build_output)) # Build failed return (build_status[0], build_status[1]) except: if build_progress:",
"# *** ERROR CHECK if u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking",
"during installation'), u'\\n'.join(err_details), __name__ ) return ## TODO: Doxygen def",
"of error before dialogs created save_dia = None prebuild_progress =",
"no error is thrown if self: # Set summary when",
"Installed-Size into control file control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size))",
"files_total = GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count') file_count = u'{}:",
"for better fit pb_size = prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1])",
"packages') save_dia = wx.FileDialog(self, GT(u'Save'), os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package,",
"#lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5)",
"-*- coding: utf-8 -*- ## \\package wizbin.build # MIT licensing",
"is missing: {}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if",
"should be after 'md5sums' # 'build' should be after 'control'",
"(dbrerrno.ECNCLD, None) # Create final control file UpdateProgress(progress, GT(u'Creating control",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None):",
"control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress += 1 if",
"= ConcatPaths((stage_dir, u'DEBIAN')) # Make a fresh build tree os.makedirs(DIR_debian)",
"task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT, DIRS, FILES in os.walk(stage_dir):",
"� (0xFFFD). build_output = list(build_status[1]) # String & unicode string",
"return (dbrerrno.ECNCLD, None) # *** Copyright *** # if create_copyright:",
"# This might be changed later to set a custom",
"tags file is missing: {}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file,",
"selected overrides'))) for T in lint_tags: if T in self.lint_overrides:",
"= u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0 task_msg = GT(u'Preparing build",
"from wiz.wizard import WizardPage ## Build page class Page(WizardPage): ##",
"quotes to avoid whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename)))",
"as class member? ExecuteCommand(GetExecutable(u'strip'), F) progress += 1 if build_progress.WasCancelled():",
"{}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src) and",
"other mandatory tasks for T in mandatory_tasks: task_list[T] = None",
"# Characters that should not be in filenames invalid_chars =",
"from ui.progress import PD_DEFAULT_STYLE from ui.progress import ProgressDialog from ui.progress",
"RemoveEmptyLines from globals.strings import TextIsEmpty from globals.system import PY_VER_MAJ from",
"# FIXME: Should check for working fakeroot & dpkg-deb executables",
"if u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking package for errors')) #",
"FILES in os.walk(stage_dir): #@UnusedVariable for F in FILES: # Don't",
"(dbrerrno.ECNCLD, None) # *** Copyright *** # if create_copyright: UpdateProgress(progress,",
"from wiz.helper import GetField from wiz.helper import GetMainWindow from wiz.helper",
"spaces in path os.chdir(working_dir) # HACK to fix file/dir permissions",
"= u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog",
"fld_email, ) # Menu launcher page pg_launcher = GetPage(pgid.MENU) #",
"IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if GetExecutable(u'lintian'): try:",
"from globals.system import PY_VER_MAJ from globals.tooltips import SetPageToolTips from input.toggle",
"Path to package to be installed def InstallPackage(self, package): system_installer",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Scripts",
"file without .deb extension # \\return # \\b \\e dbrerror",
"btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self,",
"script_text = scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text)",
"# If changelog will be installed to default directory changelog_target",
"\\e unicode|str : Directory where .deb will be output #",
"except IndexError: pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass",
"package installer: # gdebi if available or dpkg # #",
"= source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual files progress",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Control file",
"failed with unknown error')) return if build_prep: ShowErrorDialog(GT(u'Build preparation failed'),",
"non-decodable characters with � (0xFFFD). build_output = list(build_status[1]) # String",
"err_details = ( GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u'",
"= GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL) fields_control = (",
"pg_control.GetName() if item not in fields_control: page_name = pg_launcher.GetName() return",
"GT(u'Stripping binaries')) for ROOT, DIRS, FILES in os.walk(stage_dir): #@UnusedVariable for",
"Method that builds the actual Debian package # # \\param",
"an # error dialog. # \\param package # \\b \\e",
"if source_file[-1] == u'*': exe = True source_file = source_file[:-1]",
"*** Menu launcher *** # if u'launcher' in task_list: UpdateProgress(progress,",
"prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path, filename)) except: if save_dia: save_dia.Destroy()",
"chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0 #",
"Installing the package if FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return if",
"no newline at end of file control_data = u'\\n'.join(control_data).strip(u'\\n') #",
"\\e dbrerror : SUCCESS if build completed successfully def Build(self,",
"# Remove asteriks from exectuables exe = False if source_file[-1]",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) package = GetField(pg_control, inputid.PACKAGE).GetValue() #",
"if DebugEnabled(): task_msg = GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__,",
"\\b \\e unicode|str : Path to package to be installed",
"u'{}\\n{}.lintian'.format(e1, e2), errors).ShowModal() progress += 1 # Close progress dialog",
"wrapped in quotes to avoid whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod",
"UpdateProgress(current_task, message=None): task_eval = u'{} / {}'.format(current_task, task_count) if message:",
"progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides'))) for T in lint_tags:",
"= GT(u'Scripts') if len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s, u', '.join(scripts_to_make))",
"inputid.ARCH).GetStringSelection() # Dialog for save destination ttype = GT(u'Debian packages')",
"Python 3 appears to have follow_symlinks option for shutil.copy #",
"(dbrerrno.ECNCLD, None) # *** Strip files ***# # FIXME: Needs",
"_copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual files progress += 1",
"Use string names in project file but retain # compatibility",
"added to this list page_checks = ( (pgid.FILES, u'files'), (pgid.SCRIPTS,",
"wx.Yield() # Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'),",
"= CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col =",
"f_tgt) else: if exe: Logger.Debug(__name__, u'Adding executable to stage: {}'.format(f_tgt))",
"list(build_status[1]) # String & unicode string incompatibilities index = 0",
"module def _copy(f_src, f_tgt, exe=False): # NOTE: Python 3 appears",
"# Display log dsp_log = OutputLog(self) SetPageToolTips(self) # *** Event",
"row = prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS,",
"a fresh build tree os.makedirs(DIR_debian) progress += 1 if build_progress.WasCancelled():",
"os.chmod(F, 0o0644) # FIXME: Should check for working fakeroot &",
"FILE.split(u' -> ') source_file = file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2],",
"DEBUG: Start if DebugEnabled() and len(lint_tags) > 50: print(u' Reducing",
"CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum') # The",
"be set as class member? ExecuteCommand(GetExecutable(u'strip'), F) progress += 1",
"fld_version.GetValue() # Remove whitespace version = version.strip(u' \\t') version =",
"with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col =",
"See: docs/LICENSE.txt import commands, os, shutil, subprocess, traceback, wx from",
"GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure that the directory is available",
"if installed. Otherwise shows an # error dialog. # \\param",
"task_list, build_path, filename = build_prep # Actual build ret_code, result",
"required # Perhaps because string is not null terminated??? control_data",
"deb on the system self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package",
"check files in DEBIAN directory if ROOT != DIR_debian: F",
"after 'control' other_checks = ( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage,",
"FLAGS = lyt.PAD_LR if CHK.col: row = prev_row FLAGS =",
"== u'STANDARD': changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target = ConcatPaths((stage_dir,",
"# Build failed return (build_status[0], build_status[1]) except: if build_progress: build_progress.Destroy()",
"u'build', 64) # Display log dsp_log = OutputLog(self) SetPageToolTips(self) #",
"from dbr.functions import FileUnstripped from dbr.language import GT from dbr.log",
"lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')),",
"self.chk_lint.col = 0 # Installs the deb on the system",
"u'Adding executable to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding file to",
"u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]:",
"= GT(u'File Count') file_count = u'{}: {}'.format(f, files_total) # Scripts",
"title=GT(u'Warning')) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** md5sums file",
"processed mandatory_tasks = ( u'stage', u'install_size', u'control', u'build', ) #",
"md5sums')) if not WriteMD5(stage_dir, parent=build_progress): # Couldn't call md5sum command",
"save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO:",
"*** Scripts *** # if u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating",
"in lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom",
"pnl_options = BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'),",
"dbr.md5 import WriteMD5 from fileio.fileio import ReadFile from fileio.fileio import",
"class Page(WizardPage): ## Constructor # # \\param parent # Parent",
"1 build_status = (build_status[0], u''.join(build_output)) # Build failed return (build_status[0],",
"Install step is not added to this list # 'control'",
"tags'))) progress.Start() wx.Yield() # Create the dialog overrides_dialog = CheckListDialog(GetMainWindow(),",
"startup.tests import UsingTest from ui.button import CreateButton from ui.checklist import",
"= GetField(pg_control, inputid.EMAIL) fields_control = ( fld_package, fld_version, fld_maint, fld_email,",
"pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name)) # Get information",
"the system's package installer: # gdebi if available or dpkg",
"the control is disabled self.chk_md5.tt_name = u'md5»' self.chk_md5.col = 0",
"build_path, filename)) except: if save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return",
"in path os.chdir(working_dir) # HACK to fix file/dir permissions for",
"field_name)) # Get information from control page for default filename",
"better fit pb_size = prebuild_progress.GetSizeTuple() pb_size = (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size)",
"# Menu launcher page pg_launcher = GetPage(pgid.MENU) # Check to",
"work if os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding directory",
"unknown error')) return if build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep) else:",
"*** ERROR CHECK if u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking package",
"invalid_chars = (u' ', u'/') # *** Menu launcher ***",
"file UpdateProgress(progress, GT(u'Creating control file')) # dpkg fails if there",
"u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file is missing:",
"from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from globals.errorcodes",
"stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError:",
"ConcatPaths from globals.paths import PATH_app from globals.strings import GS from",
"be very first task task_list = {} # Control page",
"= CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs progress dialog",
"a file functions module def _copy(f_src, f_tgt, exe=False): # NOTE:",
"containing Return code & build details def BuildPrep(self): # Declare",
"5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method that builds the actual",
"## TODO: Doxygen def GetSaveData(self): build_list = [] options =",
"from dbr.md5 import WriteMD5 from fileio.fileio import ReadFile from fileio.fileio",
"in pnl_options.Children: row = next_row FLAGS = lyt.PAD_LR if CHK.col:",
"u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not save_dia.ShowModal() == wx.ID_OK:",
"Constructor # # \\param parent # Parent <b><i>wx.Window</i></b> instance def",
"tasks that will be processed mandatory_tasks = ( u'stage', u'install_size',",
"name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col = 0 #",
"# -*- coding: utf-8 -*- ## \\package wizbin.build # MIT",
"FIXME: Should be set as class memeber? CMD_lintian = GetExecutable(u'lintian')",
"lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags set')",
"in required: if TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name = pg_control.GetName()",
"name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col = 0 # Deletes the temporary",
"saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION,",
"= GetExecutable(u'lintian') errors = commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors !=",
"ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) # FIXME:",
"try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not free stage directory: {}').format(stage_dir),",
"if ret_code == dbrerrno.ECNCLD: return if ret_code == dbrerrno.FEMPTY: err_dia",
"= 0 prev_row = next_row for CHK in pnl_options.Children: row",
"to this list page_checks = ( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'),",
"FieldEnabled(self.chk_install) and self.chk_install.GetValue(): self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package build failed'),",
"task_list: UpdateProgress(progress, GT(u'Copying files')) no_follow_link = GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO:",
"# Add other mandatory tasks for T in mandatory_tasks: task_list[T]",
"u'-'.join(package.split(u' ')) version = fld_version.GetValue() # Remove whitespace version =",
"= pg_launcher.GetName() return (dbrerrno.FEMPTY, u'{} ➜ {}'.format(page_name, field_name)) # Get",
"None) build_path = os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu,",
"the required fields is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return if",
"TextIsEmpty(item.GetValue()): field_name = GT(item.GetName().title()) page_name = pg_control.GetName() if item not",
"build_data) ## TODO: Doxygen def SetSummary(self, event=None): pg_scripts = GetPage(pgid.SCRIPTS)",
"import GetMainWindow from wiz.helper import GetPage from wiz.wizard import WizardPage",
"wx.Yield() prebuild_progress.Update(progress) prebuild_progress.Destroy() return (dbrerrno.SUCCESS, (task_list, build_path, filename)) except: if",
"= GetField(GetPage(pgid.FILES), chkid.SYMLINK).IsChecked() # TODO: move this into a file",
"package)) else: changelog_target = ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target)",
"values. def Set(self, data): # ???: Redundant self.Reset() build_data =",
"{}'.format(CMD_lintian, deb))) if errors != wx.EmptyString: e1 = GT(u'Lintian found",
"Logger.Debug(__name__, GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__,",
"changelog')) c = u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status =",
"task_list[id_string] = wizard_page.Get() progress += 1 for task_check, id_string in",
"+ len(other_checks) progress = 0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing",
"fileio.fileio import WriteFile from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import",
"for updating progress dialog if u'scripts' in task_list: task_count +=",
"pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm', pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script in",
"sure scipt path is wrapped in quotes to avoid whitespace",
"task_check, id_string in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing for: {}').format(task_check.GetLabel())) if",
"the dialog overrides_dialog = CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME:",
"commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col = 0 # ***",
"# Get the file count files_total = GetPage(pgid.FILES).GetFileCount() f =",
"custom tags'), len(self.lint_overrides))) # Remaining tags should be custom entries",
"lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file",
"the page is not destroyed so no error is thrown",
"fakeroot & dpkg-deb executables build_status = commands.getstatusoutput((u'{} {} -b \"{}\"",
"need for re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...'))",
"scipt path is wrapped in quotes to avoid whitespace errors",
"ui.button import CreateButton from ui.checklist import CheckListDialog from ui.dialog import",
"## Method that builds the actual Debian package # #",
"task_count) if message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message)",
"IndexError: pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip')",
"to lintian check box Logger.Info(__name__, u'Enabling alpha feature \"lintian overrides\"",
"else: Logger.Debug(__name__, u'Adding directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt,",
"\"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"os.makedirs(doc_dir) # *** Changelog *** # if create_changelog: UpdateProgress(progress, GT(u'Creating",
"os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding",
"task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts = task_list[u'scripts'] for SCRIPT in",
"entries # FIXME: if self.lint_overrides: for T in self.lint_overrides: overrides_dialog.AddItem(T,",
"from wiz.helper import GetMainWindow from wiz.helper import GetPage from wiz.wizard",
"path os.chdir(working_dir) # HACK to fix file/dir permissions for ROOT,",
"have problems with spaces in path os.chdir(working_dir) # HACK to",
"in which to place documentation if create_changelog or create_copyright: doc_dir",
"+= 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) package =",
"Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) # FIXME: Strip command should be",
"set as class memeber? CMD_lintian = GetExecutable(u'lintian') errors = commands.getoutput((u'{}",
"UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT,",
"Continue')) return (dbrerrno.EEXIST, None) # Actual path to new .deb",
"set') # DEBUG: Start if DebugEnabled() and len(lint_tags) > 50:",
"= GetField(pg_control, inputid.PACKAGE).GetValue() # Make sure that the directory is",
"working directory becuase dpkg seems to have problems with spaces",
"self.chk_install = CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after build'), name=u'INSTALL', commands=(u'gdebi-gtk',",
"ROOT, DIRS, FILES in os.walk(stage_dir): for D in DIRS: D",
"SetPageToolTips from input.toggle import CheckBox from input.toggle import CheckBoxESS from",
"lyt from wiz.helper import FieldEnabled from wiz.helper import GetField from",
"installer: # gdebi if available or dpkg # # Shows",
"save destination ttype = GT(u'Debian packages') save_dia = wx.FileDialog(self, GT(u'Save'),",
"dsp_log = OutputLog(self) SetPageToolTips(self) # *** Event Handling *** #",
"pg_control = GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename)",
"GT(u'Check package for errors with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name",
") # Add other mandatory tasks for T in mandatory_tasks:",
"data # \\param build_path # \\b \\e unicode|str : Directory",
"# Entire file task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"= ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip",
"to package to be installed def InstallPackage(self, package): system_installer =",
"build process # 'stage' should be very first task task_list",
"save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen",
"*** # if u'launcher' in task_list: UpdateProgress(progress, GT(u'Creating menu launcher'))",
"into a file functions module def _copy(f_src, f_tgt, exe=False): #",
"# compatibility with older projects that use # integer values.",
"progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: # Remove old overrides self.lint_overrides",
"(dbrerrno.ECNCLD, None) # *** Scripts *** # if u'scripts' in",
"= GT(u'Lintian found some issues with the package.') e2 =",
"'files' step is used if u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping",
"data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1]))",
"GetProgressMessage(message, count=tag_count): return u'{} ({} {})'.format(message, count, GT(u'tags')) progress =",
") # Menu launcher page pg_launcher = GetPage(pgid.MENU) # Check",
"## Build page class Page(WizardPage): ## Constructor # # \\param",
"field_name = GT(item.GetName().title()) page_name = pg_control.GetName() if item not in",
"# if create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress",
"progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) package",
"import BoxSizer from ui.output import OutputLog from ui.panel import BorderedPanel",
"traceback, wx from dbr.functions import FileUnstripped from dbr.language import GT",
"newline at end of file control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure",
"build_output: try: GS(C) except UnicodeDecodeError: build_output[index] = u'�' index +=",
"f = GT(u'File Count') file_count = u'{}: {}'.format(f, files_total) #",
"import WriteMD5 from fileio.fileio import ReadFile from fileio.fileio import WriteFile",
"to stage: {}'.format(f_tgt)) shutil.copy(f_src, f_tgt) # Set FILE permissions if",
"= GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir)",
"lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout()",
"ROOT, DIRS, FILES in os.walk(stage_dir): #@UnusedVariable for F in FILES:",
"chkid.MD5, GT(u'Create md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum') # The »",
"len(task_list[u'files']) # Add each script for updating progress dialog if",
"from ui.button import CreateButton from ui.checklist import CheckListDialog from ui.dialog",
".deb will be output # \\param filename # \\b \\e",
"tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for T in task_list:",
"GT(u'Could not install package: {}'), GT(u'An unknown error occurred'), __name__",
"installation'), u'\\n'.join(err_details), __name__ ) return ## TODO: Doxygen def OnBuild(self,",
"= os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, & build pages not added",
"import GetField from wiz.helper import GetMainWindow from wiz.helper import GetPage",
"u'lintian'), ) prep_task_count = len(page_checks) + len(other_checks) progress = 0",
"practice to create hashes before populating DEBIAN directory if u'md5sums'",
"!= DIR_debian: F = ConcatPaths((ROOT, F)) if FileUnstripped(F): Logger.Debug(__name__, u'Unstripped",
"TODO: Doxygen def OnBuild(self, event=None): # Build preparation ret_code, build_prep",
"# # Shows a success dialog if installed. Otherwise shows",
"so no error is thrown if self: # Set summary",
"def UpdateProgress(current_task, message=None): task_eval = u'{} / {}'.format(current_task, task_count) if",
"the file count files_total = GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count')",
"Build(self, task_list, build_path, filename): # Declare this here in case",
"CheckBox(pnl_options, chkid.INSTALL, GT(u'Install package after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name",
"prev_row FLAGS = wx.RIGHT lyt_options.Add(CHK, (row, CHK.col), flag=FLAGS, border=5) if",
"be output # \\param filename # \\b \\e unicode|str :",
"permissions for ROOT, DIRS, FILES in os.walk(stage_dir): for D in",
"overrides self.lint_overrides = [] for L in overrides_dialog.GetCheckedLabels(): Logger.Debug(__name__, GT(u'Adding",
"directory'), name=u'RMSTAGE', defaultValue=True) self.chk_rmstage.col = 0 # Checks the output",
"no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src),",
"FieldEnabled from wiz.helper import GetField from wiz.helper import GetMainWindow from",
"Checks the output .deb for errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT,",
"overrides_dialog.ShowModal() == wx.ID_OK: # Remove old overrides self.lint_overrides = []",
"next_row for CHK in pnl_options.Children: row = next_row FLAGS =",
"from globals.strings import TextIsEmpty from globals.system import PY_VER_MAJ from globals.tooltips",
"wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not save_dia.ShowModal() == wx.ID_OK: return",
"with {}').format(system_installer)) install_cmd = (system_installer, package,) wx.Yield() # FIXME: Use",
"clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1],",
"incompatibilities index = 0 for C in build_output: try: GS(C)",
"OutputLog(self) SetPageToolTips(self) # *** Event Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild)",
"in files_data: file_defs = FILE.split(u' -> ') source_file = file_defs[0]",
"UpdateProgress(progress, GT(u'Getting installed size')) # Get installed-size installed_size = os.popen((u'du",
"not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item in required: if",
"built .deb package onto the system # # Uses the",
"0, wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0,",
"ShowErrorDialog( GT(u'An error occurred during installation'), u'\\n'.join(err_details), __name__ ) return",
"installed to default directory changelog_target = task_list[u'changelog'][0] if changelog_target ==",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) package = GetField(pg_control,",
"Logger.Debug(__name__, u'Adding directory symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt)",
"commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col = 0 # Installs the",
"0 # Checks the output .deb for errors self.chk_lint =",
"# # Uses the system's package installer: # gdebi if",
"\"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress += 1 if build_progress.WasCancelled():",
"# Installs the deb on the system self.chk_install = CheckBox(pnl_options,",
"from ui.panel import BorderedPanel from ui.progress import PD_DEFAULT_STYLE from ui.progress",
"wx.Yield() # FIXME: Use ExecuteCommand here install_output = subprocess.Popen(install_cmd) #",
"# \\return # \\b \\e dbrerror : SUCCESS if build",
"in filenames invalid_chars = (u' ', u'/') # *** Menu",
"os, shutil, subprocess, traceback, wx from dbr.functions import FileUnstripped from",
"import DetailedMessageDialog from ui.dialog import ShowErrorDialog from ui.layout import BoxSizer",
"u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'Could not",
"\"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size = installed_size[0] # Insert Installed-Size",
"CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides) btn_build = CreateButton(self, btnid.BUILD, GT(u'Build'),",
"mandatory_tasks = ( u'stage', u'install_size', u'control', u'build', ) # Add",
"Make a fresh build tree os.makedirs(DIR_debian) progress += 1 if",
"# # TODO: Show warning dialog that this could take",
"other_checks = ( (self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint,",
"new .deb deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress = 0 task_msg",
"& build details def BuildPrep(self): # Declare these here in",
"wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress += 1 for task_check, id_string",
"log dsp_log = OutputLog(self) SetPageToolTips(self) # *** Event Handling ***",
"= len(task_list) # Add each file for updating progress dialog",
"script_name)) WriteFile(script_filename, script_text) # Make sure scipt path is wrapped",
"= menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher'])",
"Insert Installed-Size into control file control_data = pg_control.Get().split(u'\\n') control_data.insert(2, u'Installed-Size:",
"u'Unstripped file: {}'.format(F)) # FIXME: Strip command should be set",
"globals.tooltips import SetPageToolTips from input.toggle import CheckBox from input.toggle import",
"menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() # Remove invalid characters",
"if wx.MAJOR_VERSION < 3: # Resize dialog for better fit",
"Remove invalid characters from filename for char in invalid_chars: menu_filename",
"task_msg)) for T in task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog' in",
"True source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual",
"maximum=prep_task_count) if wx.MAJOR_VERSION < 3: # Resize dialog for better",
"task_list: print(u'\\t{}'.format(T)) create_changelog = u'changelog' in task_list create_copyright = u'copyright'",
"exe) # Individual files progress += 1 UpdateProgress(progress) # Entire",
"= u'md5»' self.chk_md5.col = 0 # Option to strip binaries",
"package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog *** #",
"correctly if install_output == None: ShowErrorDialog( GT(u'Could not install package:",
"allow_custom=True) # FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags)) progress.SetMessage(GetProgressMessage(GT(u'Setting selected overrides')))",
"os.path.isdir(changelog_target): os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress,",
"import FileUnstripped from dbr.language import GT from dbr.log import DebugEnabled",
"else: ShowErrorDialog(GT(u'Build preparation failed with unknown error')) ## TODO: Doxygen",
"# FIXME: copying nested symbolic link may not work if",
"if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except",
"lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self,",
"0o0755) for F in FILES: F = u'{}/{}'.format(ROOT, F) if",
"in task_list: UpdateProgress(progress, GT(u'Removing temp directory')) try: shutil.rmtree(stage_dir) except OSError:",
"u'�' index += 1 build_status = (build_status[0], u''.join(build_output)) # Build",
"T in lint_tags: if T in self.lint_overrides: overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding",
"= GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if",
"characters with � (0xFFFD). build_output = list(build_status[1]) # String &",
"Dialog for save destination ttype = GT(u'Debian packages') save_dia =",
"step is used if u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping binaries'))",
"commands=u'strip') self.chk_strip.col = 0 # Deletes the temporary build tree",
"if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c = u'{} -n --best",
"be custom entries # FIXME: if self.lint_overrides: for T in",
"# MIT licensing # See: docs/LICENSE.txt import commands, os, shutil,",
"CHK.col), flag=FLAGS, border=5) if not CHK.col: prev_row = next_row next_row",
"len(other_checks) progress = 0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to",
"package after build'), name=u'INSTALL', commands=(u'gdebi-gtk', u'gdebi-kde',)) self.chk_install.tt_name = u'install»' self.chk_install.col",
"the directory is available in which to place documentation if",
"gdebi if available or dpkg # # Shows a success",
"# \\b \\e unicode|str : Basename of output file without",
"*** # if u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing temp directory'))",
"u'\\n'.join(control_data).strip(u'\\n') # Ensure there is only one empty trailing newline",
"if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self, label=GT(u'Lintian overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0,",
"sure that the directory is available in which to place",
"Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd = (system_installer, package,) wx.Yield() #",
"f_tgt) # Set FILE permissions if exe: os.chmod(f_tgt, 0o0755) else:",
"of the required fields is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return",
"be found on the system'), __name__, warn=True ) return Logger.Info(__name__,",
"a while # TODO: Add cancel option to progress dialog",
"created build_progress = None try: # Other mandatory tasks that",
"Logger.Debug(__name__, task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'), task_msg, maximum=task_count, style=PD_DEFAULT_STYLE|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_CAN_ABORT)",
"flag=FLAGS, border=5) if not CHK.col: prev_row = next_row next_row +=",
"that all required fields have values required = list(fields_control) if",
"next to lintian check box Logger.Info(__name__, u'Enabling alpha feature \"lintian",
"BorderedPanel from ui.progress import PD_DEFAULT_STYLE from ui.progress import ProgressDialog from",
"if available or dpkg # # Shows a success dialog",
"+x \"{}\"'.format(script_filename))) # Individual scripts progress += 1 UpdateProgress(progress) #",
"wx.EmptyString: e1 = GT(u'Lintian found some issues with the package.')",
"script_text) # Make sure scipt path is wrapped in quotes",
"Scripts *** # if u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating scripts'))",
"source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir, os.path.basename(source_file)), exe) # Individual files progress +=",
"len(self.lint_overrides))) # Remaining tags should be custom entries # FIXME:",
"lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method",
"wizard_page = GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress +=",
"if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding directory symbolic link to",
"to not have been executed correctly if install_output == None:",
"error occurred during installation'), u'\\n'.join(err_details), __name__ ) return ## TODO:",
"result = self.Build(task_list, build_path, filename) # FIXME: Check .deb package",
"self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data) ##",
"GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() # Create the dialog overrides_dialog",
"# Perhaps because string is not null terminated??? control_data =",
"GT(u'An error occurred during installation'), u'\\n'.join(err_details), __name__ ) return ##",
"& dpkg-deb executables build_status = commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'),",
"overrides_dialog.SetItemCheckedByLabel(T) self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining tags should",
"# ???: Redundant self.Reset() build_data = data.split(u'\\n') if GetExecutable(u'md5sum'): try:",
"u'\\n'.join(err_details), __name__ ) return ## TODO: Doxygen def OnBuild(self, event=None):",
"build_output[index] = u'�' index += 1 build_status = (build_status[0], u''.join(build_output))",
"Extra Options pnl_options = BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create",
"GT(u'Creating scripts')) scripts = task_list[u'scripts'] for SCRIPT in scripts: script_name",
"self.lint_overrides = [] btn_lint_overrides = CreateButton(self, label=GT(u'Lintian overrides')) btn_lint_overrides.Bind(wx.EVT_BUTTON, self.OnSetLintOverrides)",
"issues with the package.') e2 = GT(u'Details saved to {}').format(filename)",
"os.getcwd(), wx.EmptyString, u'{}|*.deb'.format(ttype), wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT|wx.FD_CHANGE_DIR) save_dia.SetFilename(u'{}_{}_{}.deb'.format(package, version, arch)) if not save_dia.ShowModal()",
"string incompatibilities index = 0 for C in build_output: try:",
"file')) # dpkg fails if there is no newline at",
"preparation ret_code, build_prep = self.BuildPrep() if ret_code == dbrerrno.ECNCLD: return",
"WriteMD5(stage_dir, parent=build_progress): # Couldn't call md5sum command build_progress.Cancel() progress +=",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Scripts ***",
"task_msg = GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg)) for",
"CreateButton from ui.checklist import CheckListDialog from ui.dialog import DetailedMessageDialog from",
"file/dir permissions for ROOT, DIRS, FILES in os.walk(stage_dir): for D",
"= DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required fields",
"compatible package manager could not be found on the system'),",
"# FIXME: Needs only be run if 'files' step is",
"menu_filename = menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename),",
"count=tag_count): return u'{} ({} {})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(),",
"scripts_to_make = [] scripts = ((u'preinst', pg_scripts.chk_preinst), (u'postinst', pg_scripts.chk_postinst), (u'prerm',",
"*** # # Good practice to create hashes before populating",
"GT(u'Cannot install package'), GT(u'A compatible package manager could not be",
"overrides')), 0, wx.LEFT, 5) lyt_main.Add(btn_lint_overrides, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons,",
"# # \\return # \\b \\e tuple containing Return code",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # Characters that should not",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Strip",
"NOTE: Python 3 appears to have follow_symlinks option for shutil.copy",
"# Insert Installed-Size into control file control_data = pg_control.Get().split(u'\\n') control_data.insert(2,",
"self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True, commands=u'strip') self.chk_strip.col",
"event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not",
"fields_control = ( fld_package, fld_version, fld_maint, fld_email, ) # Menu",
"should be set as class member? ExecuteCommand(GetExecutable(u'strip'), F) progress +=",
"try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error occurred when trying to",
"version = fld_version.GetValue() # Remove whitespace version = version.strip(u' \\t')",
"= (pb_size[0]+200, pb_size[1]) prebuild_progress.SetSize(pb_size) prebuild_progress.CenterOnParent() for PID, id_string in page_checks:",
"not be in filenames invalid_chars = (u' ', u'/') #",
"T in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK:",
"try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except",
"= os.path.split(save_dia.GetPath())[0] filename = os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, & build",
"*** # UpdateProgress(progress, GT(u'Running dpkg')) working_dir = os.path.split(stage_dir)[0] c_tree =",
"Show warning dialog that this could take a while #",
"stage: {}'.format(f_tgt)) shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src)",
"list page_checks = ( (pgid.FILES, u'files'), (pgid.SCRIPTS, u'scripts'), (pgid.CHANGELOG, u'changelog'),",
"file functions module def _copy(f_src, f_tgt, exe=False): # NOTE: Python",
"be installed to default directory changelog_target = task_list[u'changelog'][0] if changelog_target",
"directory *** # if u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing temp",
"Lintian Overrides *** # if UsingTest(u'alpha'): # FIXME: Move next",
"pgid from globals.paths import ConcatPaths from globals.paths import PATH_app from",
"errors != wx.EmptyString: e1 = GT(u'Lintian found some issues with",
"# \\b \\e tuple containing Return code & build details",
"True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: # Remove old overrides",
"after 'md5sums' # 'build' should be after 'control' other_checks =",
"# Two '\\n' to show physical empty line, but not",
"be shown if the control is disabled self.chk_md5.tt_name = u'md5»'",
"def GetSaveData(self): build_list = [] options = ( self.chk_md5, self.chk_rmstage,",
"SUCCESS if build completed successfully def Build(self, task_list, build_path, filename):",
"= commands.getoutput((u'{} {}'.format(CMD_lintian, deb))) if errors != wx.EmptyString: e1 =",
"lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5)",
"stage directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None) # Actual",
"copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"# error dialog. # \\param package # \\b \\e unicode|str",
"launcher page pg_launcher = GetPage(pgid.MENU) # Check to make sure",
"UpdateProgress(progress, GT(u'Checking package for errors')) # FIXME: Should be set",
"# Remove whitespace version = version.strip(u' \\t') version = u''.join(version.split())",
"if u'strip' in task_list: UpdateProgress(progress, GT(u'Stripping binaries')) for ROOT, DIRS,",
"UpdateProgress(progress, GT(u'Creating control file')) # dpkg fails if there is",
"= file_defs[0] target_file = u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file)",
"u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir)",
"version, arch)) if not save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD, None)",
"the build tree'), parent=build_progress) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"# non-decodable characters with � (0xFFFD). build_output = list(build_status[1]) #",
"u'Lintian tags file is missing: {}'.format(lintian_tags_file)) return False lint_tags =",
"not build_status[0]: return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <= 2: #",
"GT(u'Build'), u'build', 64) # Display log dsp_log = OutputLog(self) SetPageToolTips(self)",
"dbr.functions import FileUnstripped from dbr.language import GT from dbr.log import",
"return (dbrerrno.ECNCLD, None) # *** Delete staged directory *** #",
"pnl_options.Children: row = next_row FLAGS = lyt.PAD_LR if CHK.col: row",
"WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog'))",
"file symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: if",
"+= 1 for task_check, id_string in other_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Testing",
"(dbrerrno.ECNCLD, None) # *** ERROR CHECK if u'lintian' in task_list:",
"in self.lint_overrides: overrides_dialog.AddItem(T, True) progress.Stop() if overrides_dialog.ShowModal() == wx.ID_OK: #",
"# Add each script for updating progress dialog if u'scripts'",
"Get the file count files_total = GetPage(pgid.FILES).GetFileCount() f = GT(u'File",
"\\e unicode|str : Path to package to be installed def",
"= (system_installer, package,) wx.Yield() # FIXME: Use ExecuteCommand here install_output",
"if save_dia: save_dia.Destroy() if prebuild_progress: prebuild_progress.Destroy() return (dbrerrno.EUNKNOWN, traceback.format_exc()) ##",
"in DIRS: D = u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for F",
"self.chk_install.GetValue(): self.InstallPackage(result) return if result: ShowErrorDialog(GT(u'Package build failed'), result) else:",
"= pg_control.GetName() if item not in fields_control: page_name = pg_launcher.GetName()",
"C in build_output: try: GS(C) except UnicodeDecodeError: build_output[index] = u'�'",
"build completed successfully def Build(self, task_list, build_path, filename): # Declare",
"staged directory *** # if u'rmstage' in task_list: UpdateProgress(progress, GT(u'Removing",
"GT(u'Process returned code {}').format(install_output.returncode), GT(u'Command executed: {}').format(u' '.join(install_cmd)), ) ShowErrorDialog(",
"{}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__,",
"(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen def GetSaveData(self): build_list = []",
"RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags set') # DEBUG:",
"def _copy(f_src, f_tgt, exe=False): # NOTE: Python 3 appears to",
"task_list: UpdateProgress(progress, GT(u'Checking package for errors')) # FIXME: Should be",
"u'Adding file symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else:",
"menu_filename = pg_menu.GetOutputFilename() # Remove invalid characters from filename for",
"has trouble with certain characters. Replace any # non-decodable characters",
"appears to not have been executed correctly if install_output ==",
"not have been executed correctly if install_output == None: ShowErrorDialog(",
"FileUnstripped(F): Logger.Debug(__name__, u'Unstripped file: {}'.format(F)) # FIXME: Strip command should",
"exe: Logger.Debug(__name__, u'Adding executable to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__, u'Adding",
"if not os.path.isfile(lintian_tags_file): Logger.Error(__name__, u'Lintian tags file is missing: {}'.format(lintian_tags_file))",
"commands.getstatusoutput(c.encode(u'utf-8')) if clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1], warn=True, title=GT(u'Warning'))",
"version = version.strip(u' \\t') version = u''.join(version.split()) arch = GetField(pg_control,",
"command should be set as class member? ExecuteCommand(GetExecutable(u'strip'), F) progress",
"empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy() return if ret_code == dbrerrno.SUCCESS: task_list,",
"Remove old overrides self.lint_overrides = [] for L in overrides_dialog.GetCheckedLabels():",
"## \\package wizbin.build # MIT licensing # See: docs/LICENSE.txt import",
"installed-size installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size",
"= installed_size[0].split(u'\\t') installed_size = installed_size[0] # Insert Installed-Size into control",
"return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen # # \\return # \\b",
"len(lint_tags) > 50: print(u' Reducing tag count to 200 ...')",
"changed later to set a custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir)",
"check for working fakeroot & dpkg-deb executables build_status = commands.getstatusoutput((u'{}",
"= ( fld_package, fld_version, fld_maint, fld_email, ) # Menu launcher",
"ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() # Installing the package if FieldEnabled(self.chk_install)",
"commands=u'md5sum') # The » character denotes that an alternate tooltip",
"GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file): Logger.Error(__name__,",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Copyright *** #",
"f_tgt, exe=False): # NOTE: Python 3 appears to have follow_symlinks",
"u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir), control_data, noStrip=u'\\n') progress += 1 if build_progress.WasCancelled(): build_progress.Destroy()",
"# Install step is not added to this list #",
"(dbrerrno.SUCCESS, (task_list, build_path, filename)) except: if save_dia: save_dia.Destroy() if prebuild_progress:",
"pg_scripts = GetPage(pgid.SCRIPTS) # Make sure the page is not",
"<b><i>wx.Window</i></b> instance def __init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD) # -----",
"BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10) lyt_main.Add(wx.StaticText(self, label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0,",
"0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count) if",
"ShowErrorDialog from ui.layout import BoxSizer from ui.output import OutputLog from",
"newline # Two '\\n' to show physical empty line, but",
"progress = 0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(), GT(u'Preparing to build'),",
"border=5) if not CHK.col: prev_row = next_row next_row += 1",
"## Constructor # # \\param parent # Parent <b><i>wx.Window</i></b> instance",
"in task_list pg_control = GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir =",
"noStrip=u'\\n') progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None)",
"len(page_checks) + len(other_checks) progress = 0 wx.Yield() prebuild_progress = ProgressDialog(GetMainWindow(),",
"progress += 1 UpdateProgress(progress) # Entire script task progress +=",
"+= 1 UpdateProgress(progress) # Entire file task progress += 1",
"O in options: if O.GetValue(): build_list.append(u'1') else: build_list.append(u'0') if self.chk_strip.GetValue():",
"of output file without .deb extension # \\return # \\b",
"build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Copyright *** # if",
"return (dbrerrno.ECNCLD, None) # *** ERROR CHECK if u'lintian' in",
"directory: {}').format(stage_dir), title=GT(u'Cannot Continue')) return (dbrerrno.EEXIST, None) # Actual path",
"# Add each file for updating progress dialog if u'files'",
"directory becuase dpkg seems to have problems with spaces in",
"or dpkg # # Shows a success dialog if installed.",
"# See: docs/LICENSE.txt import commands, os, shutil, subprocess, traceback, wx",
"for working fakeroot & dpkg-deb executables build_status = commands.getstatusoutput((u'{} {}",
"result) else: ShowErrorDialog(GT(u'Package build failed with unknown error')) return if",
"\\return # \\b \\e tuple containing Return code & build",
"if not save_dia.ShowModal() == wx.ID_OK: return (dbrerrno.ECNCLD, None) build_path =",
"(self.chk_md5, u'md5sums'), (self.chk_strip, u'strip'), (self.chk_rmstage, u'rmstage'), (self.chk_lint, u'lintian'), ) prep_task_count",
"page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID) if wizard_page.IsOkay():",
"= subprocess.Popen(install_cmd) # Command appears to not have been executed",
"if not os.path.isdir(target_dir): os.makedirs(target_dir) # Remove asteriks from exectuables exe",
"# Set summary when \"Build\" page is shown # Get",
"split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian tags set') # DEBUG: Start",
"output .deb for errors self.chk_lint = CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package",
"= list(fields_control) if pg_launcher.IsOkay(): task_list[u'launcher'] = pg_launcher.Get() required.append(GetField(pg_launcher, inputid.NAME)) if",
"if os.access(F, os.X_OK): os.chmod(F, 0o0755) else: os.chmod(F, 0o0644) # FIXME:",
"the temporary build tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged",
"DetailedMessageDialog(GetMainWindow(), GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() # Installing the package",
"wiz.helper import FieldEnabled from wiz.helper import GetField from wiz.helper import",
"build'), maximum=prep_task_count) if wx.MAJOR_VERSION < 3: # Resize dialog for",
"0, wx.LEFT, 5) lyt_main.AddSpacer(5) lyt_main.Add(lyt_buttons, 0, lyt.ALGN_C) lyt_main.Add(dsp_log, 2, wx.EXPAND|lyt.PAD_LRB,",
"else: ShowErrorDialog(GT(u'Package build failed with unknown error')) return if build_prep:",
"= os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t') installed_size = installed_size[0]",
"documentation if create_changelog or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if",
"(dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <= 2: # Unicode decoder has",
"from fileio.fileio import WriteFile from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps",
"# gdebi if available or dpkg # # Shows a",
"the working directory becuase dpkg seems to have problems with",
"= GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c = u'{}",
"so no need for re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting",
"= GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control,",
"in mandatory_tasks: task_list[T] = None task_count = len(task_list) # Add",
"os.path.split(save_dia.GetPath())[1].split(u'.deb')[0] # Control, menu, & build pages not added to",
"if message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message) return",
"filename # \\b \\e unicode|str : Basename of output file",
"to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian Errors'), ICON_INFORMATION, u'{}\\n{}.lintian'.format(e1,",
"if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) def UpdateProgress(current_task, message=None): task_eval",
"for SCRIPT in scripts: script_name = SCRIPT script_text = scripts[SCRIPT]",
"0 for C in build_output: try: GS(C) except UnicodeDecodeError: build_output[index]",
"permissions if exe: os.chmod(f_tgt, 0o0755) else: os.chmod(f_tgt, 0o0644) files_data =",
"for D in DIRS: D = u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755)",
"GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try: self.chk_rmstage.SetValue(int(build_data[1])) except IndexError:",
"chkid.SYMLINK).IsChecked() # TODO: move this into a file functions module",
"directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename = pg_menu.GetOutputFilename() # Remove invalid",
"for ROOT, DIRS, FILES in os.walk(stage_dir): for D in DIRS:",
"D in DIRS: D = u'{}/{}'.format(ROOT, D) os.chmod(D, 0o0755) for",
"UpdateProgress(progress, GT(u'Creating changelog')) # If changelog will be installed to",
"installed size')) # Get installed-size installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines()",
"# Remove old overrides self.lint_overrides = [] for L in",
"tasks for build process # 'stage' should be very first",
"for re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file",
"self.chk_md5 = CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum')",
"u'{} ➜ {}'.format(page_name, field_name)) # Get information from control page",
"'stage' should be very first task task_list = {} #",
"= ( u'stage', u'install_size', u'control', u'build', ) # Add other",
"*** Copyright *** # if create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir,",
"to set a custom directory menu_dir = u'{}/usr/share/applications'.format(stage_dir) menu_filename =",
"lyt_options = wx.GridBagSizer() next_row = 0 prev_row = next_row for",
"to install package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd =",
"build_data = data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass",
"with unknown error')) return if build_prep: ShowErrorDialog(GT(u'Build preparation failed'), build_prep)",
"self.BuildPrep() if ret_code == dbrerrno.ECNCLD: return if ret_code == dbrerrno.FEMPTY:",
"# FIXME: Move next to lintian check box Logger.Info(__name__, u'Enabling",
"filename): # Declare this here in case of error before",
"certain characters. Replace any # non-decodable characters with � (0xFFFD).",
"Basename of output file without .deb extension # \\return #",
"+= len(task_list[u'scripts']) if DebugEnabled(): task_msg = GT(u'Total tasks: {}').format(task_count) print(u'DEBUG:",
"build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen # # \\return",
"= GetPage(pgid.MENU) # Check to make sure that all required",
"SetPageToolTips(self) # *** Event Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) #",
"build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen # # \\return #",
"an alternate tooltip should be shown if the control is",
"each file for updating progress dialog if u'files' in task_list:",
"errors with lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col",
"self.lint_overrides.remove(T) progress.SetMessage(GetProgressMessage(GT(u'Adding custom tags'), len(self.lint_overrides))) # Remaining tags should be",
"page pg_control = GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE) fld_version =",
"line, but not required # Perhaps because string is not",
": SUCCESS if build completed successfully def Build(self, task_list, build_path,",
"if build_progress: build_progress.Destroy() return(dbrerrno.EUNKNOWN, traceback.format_exc()) ## TODO: Doxygen # #",
"will be processed mandatory_tasks = ( u'stage', u'install_size', u'control', u'build',",
"os.chdir(working_dir) # HACK to fix file/dir permissions for ROOT, DIRS,",
"run if 'files' step is used if u'strip' in task_list:",
"= CheckBoxESS(pnl_options, chkid.MD5, GT(u'Create md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum') #",
"file count files_total = GetPage(pgid.FILES).GetFileCount() f = GT(u'File Count') file_count",
"build_path, filename = build_prep # Actual build ret_code, result =",
"# *** Strip files ***# # FIXME: Needs only be",
"ERROR CHECK if u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking package for",
"# FIXME: Use ExecuteCommand here install_output = subprocess.Popen(install_cmd) # Command",
"GT(u'A compatible package manager could not be found on the",
"empty trailing newline # Two '\\n' to show physical empty",
"re-scanning def OnSetLintOverrides(self, event=None): Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file =",
"older projects that use # integer values. def Set(self, data):",
"import GetSystemInstaller from globals.ident import btnid from globals.ident import chkid",
"in case of error before progress dialog created build_progress =",
"that use # integer values. def Set(self, data): # ???:",
"trying to delete the build tree'), parent=build_progress) progress += 1",
"OnBuild(self, event=None): # Build preparation ret_code, build_prep = self.BuildPrep() if",
"1 UpdateProgress(progress) # Entire script task progress += 1 if",
"if ROOT != DIR_debian: F = ConcatPaths((ROOT, F)) if FileUnstripped(F):",
"= u'{}.deb'.format(filename) # Move the working directory becuase dpkg seems",
"copying nested symbolic link may not work if os.path.isdir(f_src): if",
"for default filename package = fld_package.GetValue() # Remove whitespace package",
"on the system'), __name__, warn=True ) return Logger.Info(__name__, GT(u'Attempting to",
"Add cancel option to progress dialog # FIXME: List should",
"WriteFile(script_filename, script_text) # Make sure scipt path is wrapped in",
"u'install»' self.chk_install.col = 0 # *** Lintian Overrides *** #",
"page for default filename package = fld_package.GetValue() # Remove whitespace",
"from dbr.language import GT from dbr.log import DebugEnabled from dbr.log",
"Should check for working fakeroot & dpkg-deb executables build_status =",
"os.makedirs(target_dir) # Remove asteriks from exectuables exe = False if",
"if result: ShowErrorDialog(GT(u'Package build failed'), result) else: ShowErrorDialog(GT(u'Package build failed",
"have follow_symlinks option for shutil.copy # FIXME: copying nested symbolic",
"wx.EXPAND|lyt.PAD_LRB, 5) self.SetAutoLayout(True) self.SetSizer(lyt_main) self.Layout() ## Method that builds the",
"for ROOT, DIRS, FILES in os.walk(stage_dir): #@UnusedVariable for F in",
"= len(page_checks) + len(other_checks) progress = 0 wx.Yield() prebuild_progress =",
"link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding directory",
"e2), errors).ShowModal() progress += 1 # Close progress dialog wx.Yield()",
"be processed mandatory_tasks = ( u'stage', u'install_size', u'control', u'build', )",
"lint_tags: Logger.Debug(__name__, u'Lintian tags set') # DEBUG: Start if DebugEnabled()",
"dialog if u'scripts' in task_list: task_count += len(task_list[u'scripts']) if DebugEnabled():",
"shutil.copytree(f_src, f_tgt) os.chmod(f_tgt, 0o0755) elif os.path.isfile(f_src): if os.path.islink(f_src) and no_follow_link:",
"GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in",
"if install_output == None: ShowErrorDialog( GT(u'Could not install package: {}'),",
"script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name)) WriteFile(script_filename, script_text) # Make sure",
"ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the required fields is empty:'), build_prep)) err_dia.ShowModal()",
"task_list pg_control = GetPage(pgid.CONTROL) pg_menu = GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path,",
"filename) # FIXME: Check .deb package timestamp to confirm build",
"+= 1 # Close progress dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() #",
"scripts_to_make.append(script[0]) s = GT(u'Scripts') if len(scripts_to_make): scripts_to_make = u'{}: {}'.format(s,",
"if not os.path.isdir(doc_dir): os.makedirs(doc_dir) # *** Changelog *** # if",
"source_file[-1] == u'*': exe = True source_file = source_file[:-1] _copy(source_file,",
"__name__ ) return ## TODO: Doxygen def OnBuild(self, event=None): #",
"mandatory tasks that will be processed mandatory_tasks = ( u'stage',",
"when trying to delete the build tree'), parent=build_progress) progress +=",
"u'DEBIAN')) # Make a fresh build tree os.makedirs(DIR_debian) progress +=",
"import CreateButton from ui.checklist import CheckListDialog from ui.dialog import DetailedMessageDialog",
"u'scripts' in task_list: UpdateProgress(progress, GT(u'Creating scripts')) scripts = task_list[u'scripts'] for",
"GetSystemInstaller() if not system_installer: ShowErrorDialog( GT(u'Cannot install package'), GT(u'A compatible",
"file_count = u'{}: {}'.format(f, files_total) # Scripts to make scripts_to_make",
"# Build preparation ret_code, build_prep = self.BuildPrep() if ret_code ==",
"➜ {}'.format(page_name, field_name)) # Get information from control page for",
"*** Event Handling *** # btn_build.Bind(wx.EVT_BUTTON, self.OnBuild) # *** Layout",
"+= 1 pnl_options.SetSizer(lyt_options) pnl_options.SetAutoLayout(True) pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1)",
"= SCRIPT script_text = scripts[SCRIPT] script_filename = ConcatPaths((stage_dir, u'DEBIAN', script_name))",
"List'), GetProgressMessage(GT(u'Scanning default tags'))) progress.Start() wx.Yield() # Create the dialog",
"globals.bitmaps import ICON_INFORMATION from globals.errorcodes import dbrerrno from globals.execute import",
"Logger.Debug(__name__, GT(u'Setting Lintian overrides...')) lintian_tags_file = u'{}/data/lintian/tags'.format(PATH_app) if not os.path.isfile(lintian_tags_file):",
"if u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if not WriteMD5(stage_dir,",
"prebuild_progress = None try: # List of tasks for build",
"did not return success code if install_output.returncode: err_details = (",
"message: Logger.Debug(__name__, u'{} ({})'.format(message, task_eval)) wx.Yield() build_progress.Update(current_task, message) return wx.Yield()",
"control file')) # dpkg fails if there is no newline",
"package: {}').format(package)) Logger.Info(__name__, GT(u'Installing with {}').format(system_installer)) install_cmd = (system_installer, package,)",
"take a while # TODO: Add cancel option to progress",
"clog_status[0]: ShowErrorDialog(GT(u'Could not compress changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress +=",
"place documentation if create_changelog or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package)",
"= u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status = commands.getstatusoutput(c.encode(u'utf-8')) if",
"if exe: Logger.Debug(__name__, u'Adding executable to stage: {}'.format(f_tgt)) else: Logger.Debug(__name__,",
"-b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree, deb_package))) progress += 1 if",
"failed') return False ## TODO: Doxygen # # TODO: Use",
"actual Debian package # # \\param task_list # \\b \\e",
"list # 'control' should be after 'md5sums' # 'build' should",
"self.Reset() build_data = data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError:",
"Control, menu, & build pages not added to this list",
"dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One of the",
"Shows a success dialog if installed. Otherwise shows an #",
"success dialog if installed. Otherwise shows an # error dialog.",
"build_path, filename): # Declare this here in case of error",
"# Check to make sure that all required fields have",
"MIT licensing # See: docs/LICENSE.txt import commands, os, shutil, subprocess,",
"text=GT(u'Package created successfully')).ShowModal() # Installing the package if FieldEnabled(self.chk_install) and",
"GetPage(pgid.MENU) stage_dir = u'{}/{}__dbp__'.format(build_path, filename) if os.path.isdir(u'{}/DEBIAN'.format(stage_dir)): try: shutil.rmtree(stage_dir) except",
"but not required # Perhaps because string is not null",
"CheckBoxESS from startup.tests import UsingTest from ui.button import CreateButton from",
"dbrerrno.ECNCLD: return if ret_code == dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot",
"self.chk_md5, self.chk_rmstage, self.chk_lint, ) for O in options: if O.GetValue():",
"subprocess, traceback, wx from dbr.functions import FileUnstripped from dbr.language import",
"= GT(u'Details saved to {}').format(filename) WriteFile(u'{}/{}.lintian'.format(build_path, filename), errors) DetailedMessageDialog(build_progress, GT(u'Lintian",
"self.chk_rmstage.SetValue(int(build_data[1])) except IndexError: pass if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError:",
"failed with unknown error')) ## TODO: Doxygen # # TODO:",
"create_copyright: UpdateProgress(progress, GT(u'Creating copyright')) WriteFile(u'{}/usr/share/doc/{}/copyright'.format(stage_dir, package), task_list[u'copyright']) progress += 1",
"be installed def InstallPackage(self, package): system_installer = GetSystemInstaller() if not",
"self.Build(task_list, build_path, filename) # FIXME: Check .deb package timestamp to",
"executables build_status = commands.getstatusoutput((u'{} {} -b \"{}\" \"{}\"'.format(GetExecutable(u'fakeroot'), GetExecutable(u'dpkg-deb'), c_tree,",
"package # \\b \\e unicode|str : Path to package to",
"# Control page pg_control = GetPage(pgid.CONTROL) fld_package = GetField(pg_control, inputid.PACKAGE)",
"return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags: Logger.Debug(__name__, u'Lintian",
"integer values. def Set(self, data): # ???: Redundant self.Reset() build_data",
"custom entries # FIXME: if self.lint_overrides: for T in self.lint_overrides:",
"if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__, u'Adding file symbolic link to",
"# *** Control file *** # UpdateProgress(progress, GT(u'Getting installed size'))",
"file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file) if not os.path.isdir(target_dir): os.makedirs(target_dir) #",
"changelog will be installed to default directory changelog_target = task_list[u'changelog'][0]",
"the built .deb package onto the system # # Uses",
"Unicode decoder has trouble with certain characters. Replace any #",
"dialog wx.Yield() build_progress.Update(progress) build_progress.Destroy() # Build completed successfullly if not",
"ret_code == dbrerrno.ECNCLD: return if ret_code == dbrerrno.FEMPTY: err_dia =",
"= ProgressDialog(GetMainWindow(), GT(u'Preparing to build'), maximum=prep_task_count) if wx.MAJOR_VERSION < 3:",
"*** # if UsingTest(u'alpha'): # FIXME: Move next to lintian",
"= 0 for C in build_output: try: GS(C) except UnicodeDecodeError:",
"text=u'{}\\n{}'.format(GT(u'One of the required fields is empty:'), build_prep)) err_dia.ShowModal() err_dia.Destroy()",
"GetExecutable from globals.execute import GetSystemInstaller from globals.ident import btnid from",
"menu_filename.replace(char, u'_') if not os.path.isdir(menu_dir): os.makedirs(menu_dir) WriteFile(u'{}/{}.desktop'.format(menu_dir, menu_filename), task_list[u'launcher']) progress",
"Entire file task progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"for C in build_output: try: GS(C) except UnicodeDecodeError: build_output[index] =",
"(pgid.CHANGELOG, u'changelog'), (pgid.COPYRIGHT, u'copyright'), ) # Install step is not",
"if self: # Set summary when \"Build\" page is shown",
"{}'.format(s, u', '.join(scripts_to_make)) else: scripts_to_make = u'{}: 0'.format(s) self.summary.SetValue(u'\\n'.join((file_count, scripts_to_make)))",
"completed successfully def Build(self, task_list, build_path, filename): # Declare this",
"control_data.insert(2, u'Installed-Size: {}'.format(installed_size)) progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return",
"any # non-decodable characters with � (0xFFFD). build_output = list(build_status[1])",
"= GetPage(PID) if wizard_page.IsOkay(): task_list[id_string] = wizard_page.Get() progress += 1",
"preparation failed'), build_prep) else: ShowErrorDialog(GT(u'Build preparation failed with unknown error'))",
"None) # *** Copyright *** # if create_copyright: UpdateProgress(progress, GT(u'Creating",
"created successfully')).ShowModal() # Installing the package if FieldEnabled(self.chk_install) and self.chk_install.GetValue():",
"task_eval = u'{} / {}'.format(current_task, task_count) if message: Logger.Debug(__name__, u'{}",
"# ----- Extra Options pnl_options = BorderedPanel(self) self.chk_md5 = CheckBoxESS(pnl_options,",
"task_msg = GT(u'Preparing build tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress =",
"missing: {}'.format(lintian_tags_file)) return False lint_tags = RemoveEmptyLines(ReadFile(lintian_tags_file, split=True)) if lint_tags:",
"progress += 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) def",
"pg_scripts.chk_prerm), (u'postrm', pg_scripts.chk_postrm)) for script in scripts: if script[1].IsChecked(): scripts_to_make.append(script[0])",
"u'scripts' in task_list: task_count += len(task_list[u'scripts']) if DebugEnabled(): task_msg =",
"to create hashes before populating DEBIAN directory if u'md5sums' in",
"D) os.chmod(D, 0o0755) for F in FILES: F = u'{}/{}'.format(ROOT,",
"tags failed') return False ## TODO: Doxygen # # TODO:",
"build ret_code, result = self.Build(task_list, build_path, filename) # FIXME: Check",
"strip binaries self.chk_strip = CheckBoxESS(pnl_options, chkid.STRIP, GT(u'Strip binaries'), name=u'strip»', defaultValue=True,",
"ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target = ConcatPaths((stage_dir, changelog_target)) if not os.path.isdir(changelog_target):",
"CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing changelog')) c =",
"Otherwise shows an # error dialog. # \\param package #",
"== u'*': exe = True source_file = source_file[:-1] _copy(source_file, u'{}/{}'.format(target_dir,",
"FILES: F = u'{}/{}'.format(ROOT, F) if os.access(F, os.X_OK): os.chmod(F, 0o0755)",
"changelog_target = ConcatPaths((u'{}/usr/share/doc'.format(stage_dir), package)) else: changelog_target = ConcatPaths((stage_dir, changelog_target)) if",
"temporary build tree self.chk_rmstage = CheckBoxESS(pnl_options, chkid.DELETE, GT(u'Delete staged directory'),",
"= u'-'.join(package.split(u' ')) version = fld_version.GetValue() # Remove whitespace version",
"for F in FILES: F = u'{}/{}'.format(ROOT, F) if os.access(F,",
"import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from globals.errorcodes import dbrerrno",
": Task string IDs & page data # \\param build_path",
"= 0 # Installs the deb on the system self.chk_install",
"if not build_status[0]: return (dbrerrno.SUCCESS, deb_package) if PY_VER_MAJ <= 2:",
"None prebuild_progress = None try: # List of tasks for",
"0 # Deletes the temporary build tree self.chk_rmstage = CheckBoxESS(pnl_options,",
"u'control', u'build', ) # Add other mandatory tasks for T",
"not required # Perhaps because string is not null terminated???",
"for shutil.copy # FIXME: copying nested symbolic link may not",
"0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) # Individual scripts progress += 1",
"GT(u'Lintian found some issues with the package.') e2 = GT(u'Details",
"occurred when trying to delete the build tree'), parent=build_progress) progress",
"compress changelog'), clog_status[1], warn=True, title=GT(u'Warning')) progress += 1 if build_progress.WasCancelled():",
"GT(u'Success'), ICON_INFORMATION, text=GT(u'Package created successfully')).ShowModal() # Installing the package if",
"CheckBoxESS(pnl_options, chkid.LINT, GT(u'Check package for errors with lintian'), name=u'LINTIAN', defaultValue=True,",
"of tasks for build process # 'stage' should be very",
"occurred'), __name__ ) return # Command executed but did not",
"show physical empty line, but not required # Perhaps because",
"GetSaveData(self): build_list = [] options = ( self.chk_md5, self.chk_rmstage, self.chk_lint,",
"1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** Copyright",
"package,) wx.Yield() # FIXME: Use ExecuteCommand here install_output = subprocess.Popen(install_cmd)",
"but did not return success code if install_output.returncode: err_details =",
"Directory where .deb will be output # \\param filename #",
"to avoid whitespace errors os.chmod(script_filename, 0755) os.system((u'chmod +x \"{}\"'.format(script_filename))) #",
"def __init__(self, parent): WizardPage.__init__(self, parent, pgid.BUILD) # ----- Extra Options",
"lintian'), name=u'LINTIAN', defaultValue=True, commands=u'lintian') self.chk_lint.tt_name = u'lintian»' self.chk_lint.col = 0",
"u'{}: {}'.format(f, files_total) # Scripts to make scripts_to_make = []",
"if u'files' in task_list: task_count += len(task_list[u'files']) # Add each",
"menu launcher')) # This might be changed later to set",
"GT(u'Create md5sums file'), name=u'MD5', defaultValue=True, commands=u'md5sum') # The » character",
"The » character denotes that an alternate tooltip should be",
"{})'.format(message, count, GT(u'tags')) progress = TimedProgressDialog(GetMainWindow(), GT(u'Building Tag List'), GetProgressMessage(GT(u'Scanning",
"build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # *** ERROR CHECK if",
"return False ## TODO: Doxygen # # TODO: Use string",
"import OutputLog from ui.panel import BorderedPanel from ui.progress import PD_DEFAULT_STYLE",
"label=GT(u'Extra Options')), 0, lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5)",
"installed. Otherwise shows an # error dialog. # \\param package",
"tuple containing Return code & build details def BuildPrep(self): #",
"if GetExecutable(u'lintian'): try: self.chk_lint.SetValue(int(build_data[2])) except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip'",
"unicode string incompatibilities index = 0 for C in build_output:",
"= data.split(u'\\n') if GetExecutable(u'md5sum'): try: self.chk_md5.SetValue(int(build_data[0])) except IndexError: pass try:",
"GS from globals.strings import RemoveEmptyLines from globals.strings import TextIsEmpty from",
"return (dbrerrno.ECNCLD, None) # *** md5sums file *** # #",
"id_string in page_checks: wx.Yield() prebuild_progress.Update(progress, GT(u'Checking {}').format(id_string)) wizard_page = GetPage(PID)",
"may not work if os.path.isdir(f_src): if os.path.islink(f_src) and no_follow_link: Logger.Debug(__name__,",
"FIXME: List should be cached so no need for re-scanning",
"for save destination ttype = GT(u'Debian packages') save_dia = wx.FileDialog(self,",
"nested symbolic link may not work if os.path.isdir(f_src): if os.path.islink(f_src)",
"very first task task_list = {} # Control page pg_control",
"tags should be custom entries # FIXME: if self.lint_overrides: for",
"to build'), maximum=prep_task_count) if wx.MAJOR_VERSION < 3: # Resize dialog",
"file control_data = u'\\n'.join(control_data).strip(u'\\n') # Ensure there is only one",
"globals.strings import TextIsEmpty from globals.system import PY_VER_MAJ from globals.tooltips import",
"CheckListDialog(GetMainWindow(), title=GT(u'Lintian Overrides'), allow_custom=True) # FIXME: Needs progress dialog overrides_dialog.InitCheckList(tuple(lint_tags))",
"Move next to lintian check box Logger.Info(__name__, u'Enabling alpha feature",
"project file but retain # compatibility with older projects that",
"# \\param build_path # \\b \\e unicode|str : Directory where",
"(row, CHK.col), flag=FLAGS, border=5) if not CHK.col: prev_row = next_row",
"pnl_options.Layout() lyt_buttons = BoxSizer(wx.HORIZONTAL) lyt_buttons.Add(btn_build, 1) lyt_main = BoxSizer(wx.VERTICAL) lyt_main.AddSpacer(10)",
"filenames invalid_chars = (u' ', u'/') # *** Menu launcher",
"Logger.Debug(__name__, u'Adding file symbolic link to stage: {}'.format(f_tgt)) os.symlink(os.readlink(f_src), f_tgt)",
"trouble with certain characters. Replace any # non-decodable characters with",
"inputid.NAME)) if not GetField(pg_launcher, chkid.FNAME).GetValue(): required.append(GetField(pg_launcher, inputid.FNAME)) for item in",
"GT(u'Compressing changelog')) c = u'{} -n --best \"{}/changelog\"'.format(CMD_gzip, changelog_target) clog_status",
"lyt.ALGN_LB|wx.LEFT, 5) lyt_main.Add(pnl_options, 0, wx.LEFT, 5) lyt_main.AddSpacer(5) if UsingTest(u'alpha'): #lyt_main.Add(wx.StaticText(self,",
"UnicodeDecodeError: build_output[index] = u'�' index += 1 build_status = (build_status[0],",
"'\\n' to show physical empty line, but not required #",
"BoxSizer from ui.output import OutputLog from ui.panel import BorderedPanel from",
"fld_maint = GetField(pg_control, inputid.MAINTAINER) fld_email = GetField(pg_control, inputid.EMAIL) fields_control =",
"CHECK if u'lintian' in task_list: UpdateProgress(progress, GT(u'Checking package for errors'))",
"os.symlink(os.readlink(f_src), f_tgt) else: Logger.Debug(__name__, u'Adding directory to stage: {}'.format(f_tgt)) shutil.copytree(f_src,",
"onto the system # # Uses the system's package installer:",
"self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data) ## TODO: Doxygen def SetSummary(self,",
"path to new .deb deb = u'\"{}/{}.deb\"'.format(build_path, filename) progress =",
"because string is not null terminated??? control_data = u'{}\\n\\n'.format(control_data) WriteFile(u'{}/DEBIAN/control'.format(stage_dir),",
"Get installed-size installed_size = os.popen((u'du -hsk \"{}\"'.format(stage_dir))).readlines() installed_size = installed_size[0].split(u'\\t')",
"from globals.ident import chkid from globals.ident import inputid from globals.ident",
"self.Layout() ## Method that builds the actual Debian package #",
"move this into a file functions module def _copy(f_src, f_tgt,",
"import SetPageToolTips from input.toggle import CheckBox from input.toggle import CheckBoxESS",
"build_output = list(build_status[1]) # String & unicode string incompatibilities index",
"build pages not added to this list page_checks = (",
"ret_code == dbrerrno.FEMPTY: err_dia = DetailedMessageDialog(GetMainWindow(), GT(u'Cannot Continue'), ICON_EXCLAMATION, text=u'{}\\n{}'.format(GT(u'One",
"F in FILES: # Don't check files in DEBIAN directory",
"control file UpdateProgress(progress, GT(u'Creating control file')) # dpkg fails if",
"= GetField(pg_control, inputid.PACKAGE) fld_version = GetField(pg_control, inputid.VERSION) fld_maint = GetField(pg_control,",
"Build completed successfullly if not build_status[0]: return (dbrerrno.SUCCESS, deb_package) if",
"ui.dialog import DetailedMessageDialog from ui.dialog import ShowErrorDialog from ui.layout import",
"Doxygen # # TODO: Show warning dialog that this could",
"or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if not os.path.isdir(doc_dir): os.makedirs(doc_dir)",
"None) # *** Strip files ***# # FIXME: Needs only",
"GT(u'Adding Lintian override: {}').format(L)) self.lint_overrides.append(L) return True else: Logger.Debug(__name__, u'Setting",
"# if create_changelog: UpdateProgress(progress, GT(u'Creating changelog')) # If changelog will",
"+= 1 if build_progress.WasCancelled(): build_progress.Destroy() return (dbrerrno.ECNCLD, None) # ***",
"be changed later to set a custom directory menu_dir =",
"if create_changelog or create_copyright: doc_dir = u'{}/usr/share/doc/{}'.format(stage_dir, package) if not",
"traceback.format_exc()) ## TODO: Doxygen # # \\return # \\b \\e",
"fld_email = GetField(pg_control, inputid.EMAIL) fields_control = ( fld_package, fld_version, fld_maint,",
"Make sure the page is not destroyed so no error",
"page class Page(WizardPage): ## Constructor # # \\param parent #",
"DebugEnabled(): task_msg = GT(u'Total tasks: {}').format(task_count) print(u'DEBUG: [{}] {}'.format(__name__, task_msg))",
"GT(u'Preparing build tree') Logger.Debug(__name__, task_msg) wx.Yield() build_progress = ProgressDialog(GetMainWindow(), GT(u'Building'),",
"import CheckBoxESS from startup.tests import UsingTest from ui.button import CreateButton",
"= GetPage(pgid.SCRIPTS) # Make sure the page is not destroyed",
"PY_VER_MAJ <= 2: # Unicode decoder has trouble with certain",
"= u'{} / {}'.format(current_task, task_count) if message: Logger.Debug(__name__, u'{} ({})'.format(message,",
"{}').format(system_installer)) install_cmd = (system_installer, package,) wx.Yield() # FIXME: Use ExecuteCommand",
"UpdateProgress(progress) # Entire script task progress += 1 if build_progress.WasCancelled():",
"= u'{}{}/{}'.format(stage_dir, file_defs[2], file_defs[1]) target_dir = os.path.dirname(target_file) if not os.path.isdir(target_dir):",
"directory')) try: shutil.rmtree(stage_dir) except OSError: ShowErrorDialog(GT(u'An error occurred when trying",
"u'md5»' self.chk_md5.col = 0 # Option to strip binaries self.chk_strip",
"os.makedirs(changelog_target) WriteFile(u'{}/changelog'.format(changelog_target), task_list[u'changelog'][1]) CMD_gzip = GetExecutable(u'gzip') if CMD_gzip: UpdateProgress(progress, GT(u'Compressing",
"except IndexError: pass self.chk_strip.SetValue(GetExecutable(u'strip') and u'strip' in build_data) ## TODO:",
"Remove asteriks from exectuables exe = False if source_file[-1] ==",
"package'), GT(u'A compatible package manager could not be found on",
"option for shutil.copy # FIXME: copying nested symbolic link may",
"DEBIAN directory if u'md5sums' in task_list: UpdateProgress(progress, GT(u'Creating md5sums')) if"
] |
[
"if __name__ == '__main__': #file director gui = Gui.Gui() \"\"\"",
"= Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the type",
"tempCommunityType) \"\"\" print('the type of', repositoryName, 'is', tempCommunityType, '\\n\"check .\\YoshiViz\\output\"')",
"report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the type of', repositoryName, 'is',",
"Gui if __name__ == '__main__': #file director gui = Gui.Gui()",
"== '__main__': #file director gui = Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory,",
"gui = Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the",
"\"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the type of', repositoryName,",
"from YoshiViz import Gui if __name__ == '__main__': #file director",
"YoshiViz import Gui if __name__ == '__main__': #file director gui",
"'__main__': #file director gui = Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName,",
"import Gui if __name__ == '__main__': #file director gui =",
"generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the type of', repositoryName, 'is', tempCommunityType,",
"repositoryName, tempCommunityType) \"\"\" print('the type of', repositoryName, 'is', tempCommunityType, '\\n\"check",
"__name__ == '__main__': #file director gui = Gui.Gui() \"\"\" report_generator.\\",
"Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\" print('the type of',",
"director gui = Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) \"\"\"",
"#file director gui = Gui.Gui() \"\"\" report_generator.\\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType)"
] |
[
"new_init(self, *args): for name, value in zip(arg_names[1:], args): setattr(self, name,",
"https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import wraps def lazy_init(init): '''",
"arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init) def new_init(self, *args):",
"annotation to assign all the parameters to a self. variable.",
"that I don't have to assign all the parameters to",
"''' arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init) def new_init(self,",
"def lazy_init(init): ''' Create an annotation to assign all the",
"all the parameters to a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments",
"self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import",
"__init__ function so that I don't have to assign all",
"''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import wraps def",
"from functools import wraps def lazy_init(init): ''' Create an annotation",
"Create an annotation to assign all the parameters to a",
"so that I don't have to assign all the parameters",
"self. variable. ''' arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init)",
"a self. variable. ''' arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101",
"value in zip(arg_names[1:], args): setattr(self, name, value) init(self, *args) return",
"assign all the parameters to a self. variable. ''' #",
"lazy_init(init): ''' Create an annotation to assign all the parameters",
"# https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import wraps def lazy_init(init):",
"disable=E1101 @wraps(init) def new_init(self, *args): for name, value in zip(arg_names[1:],",
"parameters to a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect",
"all the parameters to a self. variable. ''' arg_names =",
"an __init__ function so that I don't have to assign",
"name, value in zip(arg_names[1:], args): setattr(self, name, value) init(self, *args)",
"I don't have to assign all the parameters to a",
"the parameters to a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import",
"import inspect from functools import wraps def lazy_init(init): ''' Create",
"inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init) def new_init(self, *args): for name,",
"wraps def lazy_init(init): ''' Create an annotation to assign all",
"variable. ''' arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init) def",
"parameters to a self. variable. ''' arg_names = inspect.getfullargspec(init)[0] #",
"function so that I don't have to assign all the",
"inspect from functools import wraps def lazy_init(init): ''' Create an",
"the parameters to a self. variable. ''' arg_names = inspect.getfullargspec(init)[0]",
"to a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from",
"variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import wraps",
"= inspect.getfullargspec(init)[0] # pylint: disable=E1101 @wraps(init) def new_init(self, *args): for",
"to assign all the parameters to a self. variable. '''",
"to a self. variable. ''' arg_names = inspect.getfullargspec(init)[0] # pylint:",
"@wraps(init) def new_init(self, *args): for name, value in zip(arg_names[1:], args):",
"# pylint: disable=E1101 @wraps(init) def new_init(self, *args): for name, value",
"an annotation to assign all the parameters to a self.",
"functools import wraps def lazy_init(init): ''' Create an annotation to",
"''' Create an annotation to assign all the parameters to",
"*args): for name, value in zip(arg_names[1:], args): setattr(self, name, value)",
"Wrap an __init__ function so that I don't have to",
"''' Wrap an __init__ function so that I don't have",
"import wraps def lazy_init(init): ''' Create an annotation to assign",
"pylint: disable=E1101 @wraps(init) def new_init(self, *args): for name, value in",
"in zip(arg_names[1:], args): setattr(self, name, value) init(self, *args) return new_init",
"don't have to assign all the parameters to a self.",
"assign all the parameters to a self. variable. ''' arg_names",
"def new_init(self, *args): for name, value in zip(arg_names[1:], args): setattr(self,",
"a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools",
"have to assign all the parameters to a self. variable.",
"for name, value in zip(arg_names[1:], args): setattr(self, name, value) init(self,"
] |
[
"'/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter = 0",
"ret, frame = cam.read() if not ret: print(\"failed to grab",
"cam.read() if not ret: print(\"failed to grab frame\") break else:",
"27: # ESC pressed print(\"Escape hit, closing...\") break elif k%256",
"ESC pressed print(\"Escape hit, closing...\") break elif k%256 == 32:",
"32: # SPACE pressed # img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name +",
"cv2.imshow(\"test\", frame) k = cv2.waitKey(1) if k%256 == 27: #",
"frame) k = cv2.waitKey(1) if k%256 == 27: # ESC",
"== 32: # SPACE pressed # img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name",
"frame) # print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\") img_counter += 1",
"= cv2.waitKey(1) if k%256 == 27: # ESC pressed print(\"Escape",
"cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter = 0 while True: ret,",
"= \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame) # print(\"{} written!\".format(img_name)) print(\"Image",
"True: ret, frame = cam.read() if not ret: print(\"failed to",
"hit, closing...\") break elif k%256 == 32: # SPACE pressed",
"ret: print(\"failed to grab frame\") break else: cv2.imshow(\"test\", frame) k",
"print(\"Escape hit, closing...\") break elif k%256 == 32: # SPACE",
"\"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame) # print(\"{} written!\".format(img_name)) print(\"Image Captured!",
"cv2.namedWindow(\"test\") img_counter = 0 while True: ret, frame = cam.read()",
"= cam.read() if not ret: print(\"failed to grab frame\") break",
"cv2.waitKey(1) if k%256 == 27: # ESC pressed print(\"Escape hit,",
"def register_feed(): import os import cv2 path = '/UserImage' cam",
"import cv2 path = '/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name: \")",
"= cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter = 0 while True:",
"import os import cv2 path = '/UserImage' cam = cv2.VideoCapture(0)",
"closing...\") break elif k%256 == 32: # SPACE pressed #",
"== 27: # ESC pressed print(\"Escape hit, closing...\") break elif",
"# ESC pressed print(\"Escape hit, closing...\") break elif k%256 ==",
"not ret: print(\"failed to grab frame\") break else: cv2.imshow(\"test\", frame)",
"frame = cam.read() if not ret: print(\"failed to grab frame\")",
"\".jpg\", frame) # print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\") img_counter +=",
"pressed # img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame) #",
"# SPACE pressed # img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\",",
"if not ret: print(\"failed to grab frame\") break else: cv2.imshow(\"test\",",
"path = '/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter",
"pressed print(\"Escape hit, closing...\") break elif k%256 == 32: #",
"SPACE pressed # img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame)",
"# def register_feed(): import os import cv2 path = '/UserImage'",
"+ \".jpg\", frame) # print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\") img_counter",
"grab frame\") break else: cv2.imshow(\"test\", frame) k = cv2.waitKey(1) if",
"= 0 while True: ret, frame = cam.read() if not",
"cv2 path = '/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\")",
"while True: ret, frame = cam.read() if not ret: print(\"failed",
"break elif k%256 == 32: # SPACE pressed # img_name",
"cam = cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter = 0 while",
"img_counter = 0 while True: ret, frame = cam.read() if",
"elif k%256 == 32: # SPACE pressed # img_name =",
"= '/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter =",
"# print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\") img_counter += 1 cam.release()",
"0 while True: ret, frame = cam.read() if not ret:",
"else: cv2.imshow(\"test\", frame) k = cv2.waitKey(1) if k%256 == 27:",
"k%256 == 32: # SPACE pressed # img_name = \"opencv_frame_{}.png\".format(img_counter)",
"print(\"failed to grab frame\") break else: cv2.imshow(\"test\", frame) k =",
"register_feed(): import os import cv2 path = '/UserImage' cam =",
"k%256 == 27: # ESC pressed print(\"Escape hit, closing...\") break",
"cv2.imwrite(name + \".jpg\", frame) # print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\")",
"os import cv2 path = '/UserImage' cam = cv2.VideoCapture(0) name=input(\"Name:",
"frame\") break else: cv2.imshow(\"test\", frame) k = cv2.waitKey(1) if k%256",
"k = cv2.waitKey(1) if k%256 == 27: # ESC pressed",
"name=input(\"Name: \") cv2.namedWindow(\"test\") img_counter = 0 while True: ret, frame",
"break else: cv2.imshow(\"test\", frame) k = cv2.waitKey(1) if k%256 ==",
"if k%256 == 27: # ESC pressed print(\"Escape hit, closing...\")",
"to grab frame\") break else: cv2.imshow(\"test\", frame) k = cv2.waitKey(1)",
"# img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame) # print(\"{}",
"\") cv2.namedWindow(\"test\") img_counter = 0 while True: ret, frame =",
"img_name = \"opencv_frame_{}.png\".format(img_counter) cv2.imwrite(name + \".jpg\", frame) # print(\"{} written!\".format(img_name))",
"print(\"{} written!\".format(img_name)) print(\"Image Captured! Proceed...\") img_counter += 1 cam.release() cv2.destroyAllWindows()"
] |
[
"''' @Author : lance @Email : <EMAIL> ''' import time",
"# bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) # # except Exception",
"as e: # print(e) # try: # print(\"inceptionv3\") # inceptionv3(classes,",
"if __name__==\"__main__\": classes = 1 epochs = 100 steps_per_epoch =",
"# print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) #",
"steps_per_epoch, validation_steps, (100,100)) except Exception as e: print(e) end =",
"model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import",
"try: print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as",
"shape) # except Exception as e: # print(e) try: print(\"nasnet\")",
"# mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as",
"Exception as e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps,",
"epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionresnet(classes, epochs, steps_per_epoch,",
"model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import densenet from model_cx.nasnet import",
"Exception as e: # print(e) try: print(\"merge\") merge(classes, epochs, steps_per_epoch,",
"# except Exception as e: # print(e) try: print(\"nasnet\") nasnet(classes,",
"classes = 1 epochs = 100 steps_per_epoch = 113 validation_steps",
"vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e)",
"senet if __name__==\"__main__\": classes = 1 epochs = 100 steps_per_epoch",
"print(e) # try: # print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps,",
"# try: # print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299,",
"except Exception as e: print(e) end = time.time() print(\"ETA:\", (end",
"print(e) try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception",
"# try: # print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299,",
"Exception as e: # print(e) # try: # print(\"inceptionv3\") #",
"nasnet from model_cx.merge import merge from model_cx.bcnn import bilinearnet from",
"# print(e) # try: # print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch,",
"steps_per_epoch, validation_steps, (299, 299)) # # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps,",
"validation_steps, (299, 299)) # # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape)",
"import bilinearnet from model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import mobilenetv2",
"# print(e) try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except",
"# try: # print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape)",
"print(e) end = time.time() print(\"ETA:\", (end - start) / 3600)",
"time.time() # # try: # print(\"densenet\") # densenet(classes, epochs, steps_per_epoch,",
"import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import densenet",
"model_cx.merge import merge from model_cx.bcnn import bilinearnet from model_cx.resnet import",
"-*- encoding: utf-8 -*- ''' @Author : lance @Email :",
"Exception as e: # print(e) # try: # print(\"bcnn\") #",
"except Exception as e: # print(e) # try: # print(\"mobilenetv2\")",
"mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e:",
"(299, 299)) # # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"# ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as",
"e: print(e) # try: # print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch,",
"100 steps_per_epoch = 113 validation_steps = 48 shape=(224,224) print(\"开始训练...\") start",
"e: # print(e) # try: # print(\"inceptionv3\") # inceptionv3(classes, epochs,",
"epochs = 100 steps_per_epoch = 113 validation_steps = 48 shape=(224,224)",
"ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e:",
"from model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet",
"e: # print(e) try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape)",
"1 epochs = 100 steps_per_epoch = 113 validation_steps = 48",
"from model_cx.nasnet import nasnet from model_cx.merge import merge from model_cx.bcnn",
"from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet",
"from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import senet if __name__==\"__main__\":",
"steps_per_epoch = 113 validation_steps = 48 shape=(224,224) print(\"开始训练...\") start =",
"except Exception as e: # print(e) # try: # print(\"bcnn\")",
"as e: print(e) end = time.time() print(\"ETA:\", (end - start)",
"print(e) try: print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception",
"model_cx.bcnn import bilinearnet from model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import",
"e: # print(e) # try: # print(\"resnet\") # ResNet50(classes, epochs,",
"299)) # # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) # except",
"e: # print(e) try: print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps, shape)",
"from model_cx.senet import senet if __name__==\"__main__\": classes = 1 epochs",
"import mobilenetv2 from model_cx.senet import senet if __name__==\"__main__\": classes =",
"= time.time() # # try: # print(\"densenet\") # densenet(classes, epochs,",
"# # try: # print(\"densenet\") # densenet(classes, epochs, steps_per_epoch, validation_steps,",
"# try: # print(\"densenet\") # densenet(classes, epochs, steps_per_epoch, validation_steps, shape)",
"lance @Email : <EMAIL> ''' import time from model_cx.inceptionresnet import",
"model_cx.senet import senet if __name__==\"__main__\": classes = 1 epochs =",
"as e: # print(e) try: print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps,",
"try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as",
"print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) # # except",
"import time from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import vgg19_all_lr",
"# inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as",
"as e: print(e) # try: # print(\"ince_res\") # inceptionresnet(classes, epochs,",
"ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import senet if",
"try: # print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"48 shape=(224,224) print(\"开始训练...\") start = time.time() # # try: #",
"shape) except Exception as e: print(e) # try: # print(\"ince_res\")",
"299)) # # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) # except",
"steps_per_epoch, validation_steps, shape) except Exception as e: print(e) try: print(\"senet\")",
"# try: # print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape)",
"as e: print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100))",
"vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import densenet from",
"as e: # print(e) # try: # print(\"resnet\") # ResNet50(classes,",
"bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) # # except Exception as",
"start = time.time() # # try: # print(\"densenet\") # densenet(classes,",
"validation_steps, shape) except Exception as e: print(e) try: print(\"senet\") vgg19_all_lr(classes,",
"# inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as",
"from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import densenet from model_cx.nasnet",
"shape) except Exception as e: print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs,",
"# -*- encoding: utf-8 -*- ''' @Author : lance @Email",
"# print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) # except",
"except Exception as e: # print(e) try: print(\"merge\") merge(classes, epochs,",
"model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import",
"# print(e) # try: # print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch,",
": lance @Email : <EMAIL> ''' import time from model_cx.inceptionresnet",
"shape) except Exception as e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs,",
"shape=(224,224) print(\"开始训练...\") start = time.time() # # try: # print(\"densenet\")",
"# print(e) try: print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps, shape) except",
"Exception as e: # print(e) try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch,",
"validation_steps, shape) # # except Exception as e: # print(e)",
"time from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import vgg19_all_lr from",
"Exception as e: print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps,",
"inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e:",
"try: # print(\"densenet\") # densenet(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"print(e) # try: # print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps,",
"from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3",
"from model_cx.bcnn import bilinearnet from model_cx.resnet import ResNet50 from model_cx.mobilenetv2",
"print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception",
"Exception as e: # print(e) # try: # print(\"mobilenetv2\") #",
"epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e) #",
"validation_steps, shape) except Exception as e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes,",
"densenet from model_cx.nasnet import nasnet from model_cx.merge import merge from",
"epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: #",
"steps_per_epoch, validation_steps, (299, 299)) # # inceptionv3(classes, epochs, steps_per_epoch, validation_steps,",
"@Author : lance @Email : <EMAIL> ''' import time from",
"import densenet from model_cx.nasnet import nasnet from model_cx.merge import merge",
"except Exception as e: print(e) # try: # print(\"ince_res\") #",
"print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e:",
"as e: # print(e) # try: # print(\"bcnn\") # bilinearnet(classes,",
"e: # print(e) # try: # print(\"bcnn\") # bilinearnet(classes, epochs,",
"try: # print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception",
"<EMAIL> ''' import time from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two",
"from model_cx.merge import merge from model_cx.bcnn import bilinearnet from model_cx.resnet",
"# print(e) # try: # print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch,",
"steps_per_epoch, validation_steps, shape) except Exception as e: print(e) # try:",
"steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e)",
"inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e:",
"# print(e) # try: # print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch,",
"inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionv3(classes, epochs,",
"e: print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except",
"(299, 299)) # # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"''' import time from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import",
"# inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionv3(classes,",
"except Exception as e: print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch,",
"bilinearnet from model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from",
"validation_steps = 48 shape=(224,224) print(\"开始训练...\") start = time.time() # #",
"inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionresnet(classes, epochs,",
"# # except Exception as e: # print(e) # try:",
"# # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception",
"inceptionresnet from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from",
"try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except Exception as",
"# inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionresnet(classes,",
"shape) # except Exception as e: # print(e) try: print(\"merge\")",
"as e: # print(e) # try: # print(\"mobilenetv2\") # mobilenetv2(classes,",
"nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e)",
"import inceptionresnet from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3",
"shape) # # except Exception as e: # print(e) #",
"as e: # print(e) try: print(\"nasnet\") nasnet(classes, epochs, steps_per_epoch, validation_steps,",
"# try: # print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape)",
"-*- ''' @Author : lance @Email : <EMAIL> ''' import",
"# print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) # #",
"validation_steps, shape) except Exception as e: print(e) # try: #",
"shape) # except Exception as e: # print(e) # try:",
"print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except Exception as e:",
"print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # #",
"validation_steps, (299, 299)) # # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape)",
"epochs, steps_per_epoch, validation_steps, shape) # # except Exception as e:",
"steps_per_epoch, validation_steps, shape) except Exception as e: print(e) try: print(\"vgg19two\")",
"= 1 epochs = 100 steps_per_epoch = 113 validation_steps =",
"# # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception",
"Exception as e: print(e) end = time.time() print(\"ETA:\", (end -",
"validation_steps, shape) # except Exception as e: # print(e) #",
"try: # print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299))",
"print(e) # try: # print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps,",
"__name__==\"__main__\": classes = 1 epochs = 100 steps_per_epoch = 113",
"epochs, steps_per_epoch, validation_steps, (100,100)) except Exception as e: print(e) end",
"Exception as e: print(e) # try: # print(\"ince_res\") # inceptionresnet(classes,",
"@Email : <EMAIL> ''' import time from model_cx.inceptionresnet import inceptionresnet",
"# print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) # except",
"= 113 validation_steps = 48 shape=(224,224) print(\"开始训练...\") start = time.time()",
"(100,100)) except Exception as e: print(e) end = time.time() print(\"ETA:\",",
"merge(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e)",
"validation_steps, (100,100)) except Exception as e: print(e) end = time.time()",
"except Exception as e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch,",
"vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except Exception as e: print(e)",
"# except Exception as e: # print(e) # try: #",
"steps_per_epoch, validation_steps, shape) # # except Exception as e: #",
"model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import",
"from model_cx.densenet import densenet from model_cx.nasnet import nasnet from model_cx.merge",
"inceptionv3 from model_cx.densenet import densenet from model_cx.nasnet import nasnet from",
"mobilenetv2 from model_cx.senet import senet if __name__==\"__main__\": classes = 1",
"except Exception as e: # print(e) try: print(\"nasnet\") nasnet(classes, epochs,",
"e: print(e) end = time.time() print(\"ETA:\", (end - start) /",
"113 validation_steps = 48 shape=(224,224) print(\"开始训练...\") start = time.time() #",
"try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as",
"e: # print(e) # try: # print(\"mobilenetv2\") # mobilenetv2(classes, epochs,",
"Exception as e: # print(e) # try: # print(\"resnet\") #",
"import ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import senet",
"print(\"开始训练...\") start = time.time() # # try: # print(\"densenet\") #",
"try: # print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299))",
"print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception",
"print(\"merge\") merge(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e:",
"densenet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e:",
"# densenet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as",
"model_cx.densenet import densenet from model_cx.nasnet import nasnet from model_cx.merge import",
"import inceptionv3 from model_cx.densenet import densenet from model_cx.nasnet import nasnet",
": <EMAIL> ''' import time from model_cx.inceptionresnet import inceptionresnet from",
"# except Exception as e: # print(e) try: print(\"merge\") merge(classes,",
"validation_steps, shape) # except Exception as e: # print(e) try:",
"print(\"ince_res\") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # #",
"model_cx.nasnet import nasnet from model_cx.merge import merge from model_cx.bcnn import",
"import merge from model_cx.bcnn import bilinearnet from model_cx.resnet import ResNet50",
"merge from model_cx.bcnn import bilinearnet from model_cx.resnet import ResNet50 from",
"except Exception as e: # print(e) # try: # print(\"resnet\")",
"e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except",
"print(e) try: print(\"senet\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except Exception",
"= 100 steps_per_epoch = 113 validation_steps = 48 shape=(224,224) print(\"开始训练...\")",
"encoding: utf-8 -*- ''' @Author : lance @Email : <EMAIL>",
"print(e) # try: # print(\"mobilenetv2\") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps,",
"try: # print(\"bcnn\") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) #",
"epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e) try:",
"epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionv3(classes, epochs, steps_per_epoch,",
"model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import senet if __name__==\"__main__\": classes",
"except Exception as e: # print(e) # try: # print(\"inceptionv3\")",
"print(\"densenet\") # densenet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception",
"as e: print(e) try: print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape)",
"print(\"vgg19two\") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e:",
"= 48 shape=(224,224) print(\"开始训练...\") start = time.time() # # try:",
"# print(\"densenet\") # densenet(classes, epochs, steps_per_epoch, validation_steps, shape) # except",
"print(e) # try: # print(\"resnet\") # ResNet50(classes, epochs, steps_per_epoch, validation_steps,",
"utf-8 -*- ''' @Author : lance @Email : <EMAIL> '''",
"# print(\"inceptionv3\") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) #",
"import nasnet from model_cx.merge import merge from model_cx.bcnn import bilinearnet",
"import senet if __name__==\"__main__\": classes = 1 epochs = 100"
] |
[
"the derivatives), but better for ODE filtering and smoothing. Used",
"self.powers / self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), )",
"smoothing steps more numerically stable. \"\"\" @abc.abstractmethod def __call__(self, step)",
"new_mean = precon @ rv.mean new_cov_cholesky = precon @ rv.cov_cholesky",
"they are resolved, this function here will hopefully be superfluous.",
"A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) ->",
"import cached_property import numpy as np import scipy.special # for",
"makes the filtering and smoothing steps more numerically stable. \"\"\"",
"randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as preconditioners",
"= dimension @classmethod def from_order(cls, order, dimension): # used to",
"is needed, add them into the signature in the future",
"and #329. # When they are resolved, this function here",
"if more than step is needed, add them into the",
"and scales of the inverse # are better read off",
"are better read off than inverted self.powers = powers self.scales",
"change transformations as preconditioners in state space models. For some",
"# public (because it is needed in some integrator implementations),",
"scipy.special # for vectorised factorial from probnum import config, linops,",
"abc try: # cached_property is only available in Python >=3.8",
"algorithms here, # which implies additional cost. # See Issues",
"#329. # When they are resolved, this function here will",
"@cached_property def inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0 /",
"exposed to the 'randprocs' namespace # (i.e. not imported in",
"from_order(cls, order, dimension): # used to conveniently initialise in the",
"this is valid new_cov = new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean,",
"update the Cholesky factor for non-square-root algorithms here, # which",
"Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as preconditioners in state space models.",
"inverse # are better read off than inverted self.powers =",
"factor for non-square-root algorithms here, # which implies additional cost.",
"-> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0 / self.scales, dimension=self.dimension, )",
"some models, this makes the filtering and smoothing steps more",
"def apply_precon(precon, rv): # public (because it is needed in",
"dimension): # Clean way of assembling these coordinates cheaply, #",
"in Python >=3.8 from functools import cached_property except ImportError: from",
"ODE filtering and smoothing. Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`.",
"# are better read off than inverted self.powers = powers",
"rv.mean new_cov_cholesky = precon @ rv.cov_cholesky # precon is diagonal,",
"not. # Therefore, since we need to update the Cholesky",
"# precon is diagonal, so this is valid new_cov =",
"try: # cached_property is only available in Python >=3.8 from",
"filtering and smoothing steps more numerically stable. \"\"\" @abc.abstractmethod def",
"this makes the filtering and smoothing steps more numerically stable.",
"self.powers = powers self.scales = scales self.dimension = dimension @classmethod",
"0.5, scales=scales, dimension=dimension, ) def __call__(self, step): scaling_vector = np.abs(step)",
"= np.abs(step) ** self.powers / self.scales if config.matrix_free: return linops.Kronecker(",
"the signature in the future raise NotImplementedError @cached_property def inverse(self)",
"See Issues #319 and #329. # When they are resolved,",
"= scales self.dimension = dimension @classmethod def from_order(cls, order, dimension):",
"of checking whether `rv` has its Cholesky factor computed already",
"will hopefully be superfluous. new_mean = precon @ rv.mean new_cov_cholesky",
"some integrator implementations), # but not exposed to the 'randprocs'",
"Taylor coefficients instead of the derivatives), but better for ODE",
"def __init__(self, powers, scales, dimension): # Clean way of assembling",
"assembling these coordinates cheaply, # because the powers and scales",
"them into the signature in the future raise NotImplementedError @cached_property",
"need to update the Cholesky factor for square-root filtering, #",
"resolved, this function here will hopefully be superfluous. new_mean =",
"Clean way of assembling these coordinates cheaply, # because the",
"@ rv.mean new_cov_cholesky = precon @ rv.cov_cholesky # precon is",
"powers=powers + 0.5, scales=scales, dimension=dimension, ) def __call__(self, step): scaling_vector",
"# When they are resolved, this function here will hopefully",
"state space models.\"\"\" import abc try: # cached_property is only",
"namespace # (i.e. not imported in any __init__.py). # There",
"def __call__(self, step) -> np.ndarray: # if more than step",
"self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension),",
"since we need to update the Cholesky factor for square-root",
"B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) -> \"NordsieckLikeCoordinates\":",
"function here will hopefully be superfluous. new_mean = precon @",
"beginning powers = np.arange(order, -1, -1) scales = scipy.special.factorial(powers) return",
"the powers and scales of the inverse # are better",
"these coordinates cheaply, # because the powers and scales of",
"more than step is needed, add them into the signature",
"rv): # public (because it is needed in some integrator",
"Python >=3.8 from functools import cached_property except ImportError: from cached_property",
"__init__.py). # There is no way of checking whether `rv`",
"this function here will hopefully be superfluous. new_mean = precon",
"NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to Nordsieck coordinates (which store the",
"numpy as np import scipy.special # for vectorised factorial from",
"because the powers and scales of the inverse # are",
"space models.\"\"\" import abc try: # cached_property is only available",
"imported in any __init__.py). # There is no way of",
"more numerically stable. \"\"\" @abc.abstractmethod def __call__(self, step) -> np.ndarray:",
"@ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change",
"in some integrator implementations), # but not exposed to the",
"\"\"\"Coordinate change transformations as preconditioners in state space models. For",
"config, linops, randvars def apply_precon(precon, rv): # public (because it",
"cached_property import numpy as np import scipy.special # for vectorised",
"'randprocs' namespace # (i.e. not imported in any __init__.py). #",
"# (i.e. not imported in any __init__.py). # There is",
"if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector))",
"e.g. in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers, scales, dimension): #",
"dimension=dimension, ) def __call__(self, step): scaling_vector = np.abs(step) ** self.powers",
"the filtering and smoothing steps more numerically stable. \"\"\" @abc.abstractmethod",
"valid new_cov = new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky)",
"from cached_property import cached_property import numpy as np import scipy.special",
"models.\"\"\" import abc try: # cached_property is only available in",
"for square-root filtering, # we also update the Cholesky factor",
"the inverse # are better read off than inverted self.powers",
"cached_property is only available in Python >=3.8 from functools import",
"Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers,",
"coordinates cheaply, # because the powers and scales of the",
"#319 and #329. # When they are resolved, this function",
"config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property",
"to Nordsieck coordinates (which store the Taylor coefficients instead of",
"# There is no way of checking whether `rv` has",
"= new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC):",
"-> np.ndarray: # if more than step is needed, add",
"def inverse(self) -> \"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates.",
"coordinates (which store the Taylor coefficients instead of the derivatives),",
"not exposed to the 'randprocs' namespace # (i.e. not imported",
"for ODE filtering and smoothing. Used in integrator-transitions, e.g. in",
"initialise in the beginning powers = np.arange(order, -1, -1) scales",
"np.abs(step) ** self.powers / self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension),",
"also update the Cholesky factor for non-square-root algorithms here, #",
"transformations as preconditioners in state space models. For some models,",
"filtering and smoothing. Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\"",
"cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as preconditioners in state",
"inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0 / self.scales, dimension=self.dimension,",
"to conveniently initialise in the beginning powers = np.arange(order, -1,",
"-> \"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to",
"# but not exposed to the 'randprocs' namespace # (i.e.",
"dimension): # used to conveniently initialise in the beginning powers",
"the 'randprocs' namespace # (i.e. not imported in any __init__.py).",
"coefficients instead of the derivatives), but better for ODE filtering",
"public (because it is needed in some integrator implementations), #",
"is needed in some integrator implementations), # but not exposed",
"inverse(self) -> \"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar",
"implies additional cost. # See Issues #319 and #329. #",
"self.scales = scales self.dimension = dimension @classmethod def from_order(cls, order,",
"than inverted self.powers = powers self.scales = scales self.dimension =",
"np.arange(order, -1, -1) scales = scipy.special.factorial(powers) return cls( powers=powers +",
"be superfluous. new_mean = precon @ rv.mean new_cov_cholesky = precon",
"hopefully be superfluous. new_mean = precon @ rv.mean new_cov_cholesky =",
"is no way of checking whether `rv` has its Cholesky",
"of the inverse # are better read off than inverted",
"in any __init__.py). # There is no way of checking",
"it is needed in some integrator implementations), # but not",
"import abc try: # cached_property is only available in Python",
"diagonal, so this is valid new_cov = new_cov_cholesky @ new_cov_cholesky.T",
"off than inverted self.powers = powers self.scales = scales self.dimension",
">=3.8 from functools import cached_property except ImportError: from cached_property import",
"scales=scales, dimension=dimension, ) def __call__(self, step): scaling_vector = np.abs(step) **",
"= precon @ rv.mean new_cov_cholesky = precon @ rv.cov_cholesky #",
"import scipy.special # for vectorised factorial from probnum import config,",
"needed, add them into the signature in the future raise",
"# if more than step is needed, add them into",
"NotImplementedError @cached_property def inverse(self) -> \"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner):",
"numerically stable. \"\"\" @abc.abstractmethod def __call__(self, step) -> np.ndarray: #",
"is only available in Python >=3.8 from functools import cached_property",
"precon is diagonal, so this is valid new_cov = new_cov_cholesky",
"has its Cholesky factor computed already or not. # Therefore,",
"superfluous. new_mean = precon @ rv.mean new_cov_cholesky = precon @",
"or not. # Therefore, since we need to update the",
"class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as preconditioners in state space",
"needed in some integrator implementations), # but not exposed to",
"@classmethod def from_order(cls, order, dimension): # used to conveniently initialise",
"apply_precon(precon, rv): # public (because it is needed in some",
"models. For some models, this makes the filtering and smoothing",
"already or not. # Therefore, since we need to update",
"For some models, this makes the filtering and smoothing steps",
"\"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to Nordsieck",
"future raise NotImplementedError @cached_property def inverse(self) -> \"Preconditioner\": raise NotImplementedError",
"cls( powers=powers + 0.5, scales=scales, dimension=dimension, ) def __call__(self, step):",
"any __init__.py). # There is no way of checking whether",
"# which implies additional cost. # See Issues #319 and",
"np import scipy.special # for vectorised factorial from probnum import",
"we need to update the Cholesky factor for square-root filtering,",
"instead of the derivatives), but better for ODE filtering and",
"return cls( powers=powers + 0.5, scales=scales, dimension=dimension, ) def __call__(self,",
") def __call__(self, step): scaling_vector = np.abs(step) ** self.powers /",
"\"\"\"Coordinate changes in state space models.\"\"\" import abc try: #",
"+ 0.5, scales=scales, dimension=dimension, ) def __call__(self, step): scaling_vector =",
"cached_property except ImportError: from cached_property import cached_property import numpy as",
"available in Python >=3.8 from functools import cached_property except ImportError:",
"which implies additional cost. # See Issues #319 and #329.",
"conveniently initialise in the beginning powers = np.arange(order, -1, -1)",
"inverted self.powers = powers self.scales = scales self.dimension = dimension",
"import config, linops, randvars def apply_precon(precon, rv): # public (because",
"precon @ rv.mean new_cov_cholesky = precon @ rv.cov_cholesky # precon",
"way of checking whether `rv` has its Cholesky factor computed",
"in the beginning powers = np.arange(order, -1, -1) scales =",
"only available in Python >=3.8 from functools import cached_property except",
"@abc.abstractmethod def __call__(self, step) -> np.ndarray: # if more than",
"no way of checking whether `rv` has its Cholesky factor",
"Therefore, since we need to update the Cholesky factor for",
"self.dimension = dimension @classmethod def from_order(cls, order, dimension): # used",
"precon @ rv.cov_cholesky # precon is diagonal, so this is",
"better read off than inverted self.powers = powers self.scales =",
"raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to Nordsieck coordinates",
"square-root filtering, # we also update the Cholesky factor for",
"of assembling these coordinates cheaply, # because the powers and",
"powers and scales of the inverse # are better read",
"read off than inverted self.powers = powers self.scales = scales",
"in state space models.\"\"\" import abc try: # cached_property is",
"powers self.scales = scales self.dimension = dimension @classmethod def from_order(cls,",
"# Clean way of assembling these coordinates cheaply, # because",
"\"\"\" @abc.abstractmethod def __call__(self, step) -> np.ndarray: # if more",
"checking whether `rv` has its Cholesky factor computed already or",
"from probnum import config, linops, randvars def apply_precon(precon, rv): #",
"linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self)",
"non-square-root algorithms here, # which implies additional cost. # See",
"__init__(self, powers, scales, dimension): # Clean way of assembling these",
"we also update the Cholesky factor for non-square-root algorithms here,",
"new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate",
"** self.powers / self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector),",
"step): scaling_vector = np.abs(step) ** self.powers / self.scales if config.matrix_free:",
"space models. For some models, this makes the filtering and",
"step is needed, add them into the signature in the",
"cost. # See Issues #319 and #329. # When they",
"@ rv.cov_cholesky # precon is diagonal, so this is valid",
"here, # which implies additional cost. # See Issues #319",
"is valid new_cov = new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov,",
"scales of the inverse # are better read off than",
"from functools import cached_property except ImportError: from cached_property import cached_property",
"# we also update the Cholesky factor for non-square-root algorithms",
"new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as preconditioners in",
"the Cholesky factor for non-square-root algorithms here, # which implies",
"implementations), # but not exposed to the 'randprocs' namespace #",
"There is no way of checking whether `rv` has its",
"is diagonal, so this is valid new_cov = new_cov_cholesky @",
"# Therefore, since we need to update the Cholesky factor",
"better for ODE filtering and smoothing. Used in integrator-transitions, e.g.",
"def inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0 / self.scales,",
"cached_property import cached_property import numpy as np import scipy.special #",
"NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to Nordsieck coordinates (which",
"return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def",
"computed already or not. # Therefore, since we need to",
"# cached_property is only available in Python >=3.8 from functools",
"@cached_property def inverse(self) -> \"Preconditioner\": raise NotImplementedError class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like",
"-1, -1) scales = scipy.special.factorial(powers) return cls( powers=powers + 0.5,",
"new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations",
"return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates(",
"dimension @classmethod def from_order(cls, order, dimension): # used to conveniently",
"rv.cov_cholesky # precon is diagonal, so this is valid new_cov",
"\"\"\" def __init__(self, powers, scales, dimension): # Clean way of",
"Cholesky factor for non-square-root algorithms here, # which implies additional",
"return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class Preconditioner(abc.ABC): \"\"\"Coordinate change transformations as",
"but better for ODE filtering and smoothing. Used in integrator-transitions,",
"so this is valid new_cov = new_cov_cholesky @ new_cov_cholesky.T return",
"steps more numerically stable. \"\"\" @abc.abstractmethod def __call__(self, step) ->",
"models, this makes the filtering and smoothing steps more numerically",
"When they are resolved, this function here will hopefully be",
"= precon @ rv.cov_cholesky # precon is diagonal, so this",
"Issues #319 and #329. # When they are resolved, this",
"(which store the Taylor coefficients instead of the derivatives), but",
"class NordsieckLikeCoordinates(Preconditioner): \"\"\"Nordsieck-like coordinates. Similar to Nordsieck coordinates (which store",
"import numpy as np import scipy.special # for vectorised factorial",
"-1) scales = scipy.special.factorial(powers) return cls( powers=powers + 0.5, scales=scales,",
"scales self.dimension = dimension @classmethod def from_order(cls, order, dimension): #",
"not imported in any __init__.py). # There is no way",
"`rv` has its Cholesky factor computed already or not. #",
"coordinates. Similar to Nordsieck coordinates (which store the Taylor coefficients",
"in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers, scales,",
"as np import scipy.special # for vectorised factorial from probnum",
"than step is needed, add them into the signature in",
"functools import cached_property except ImportError: from cached_property import cached_property import",
"its Cholesky factor computed already or not. # Therefore, since",
"order, dimension): # used to conveniently initialise in the beginning",
"the beginning powers = np.arange(order, -1, -1) scales = scipy.special.factorial(powers)",
"whether `rv` has its Cholesky factor computed already or not.",
"and smoothing steps more numerically stable. \"\"\" @abc.abstractmethod def __call__(self,",
"state space models. For some models, this makes the filtering",
"derivatives), but better for ODE filtering and smoothing. Used in",
"= np.arange(order, -1, -1) scales = scipy.special.factorial(powers) return cls( powers=powers",
"__call__(self, step): scaling_vector = np.abs(step) ** self.powers / self.scales if",
"powers, scales, dimension): # Clean way of assembling these coordinates",
"used to conveniently initialise in the beginning powers = np.arange(order,",
"step) -> np.ndarray: # if more than step is needed,",
"and smoothing. Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\" def",
"scipy.special.factorial(powers) return cls( powers=powers + 0.5, scales=scales, dimension=dimension, ) def",
"the Taylor coefficients instead of the derivatives), but better for",
"# because the powers and scales of the inverse #",
"factor for square-root filtering, # we also update the Cholesky",
"the Cholesky factor for square-root filtering, # we also update",
"update the Cholesky factor for square-root filtering, # we also",
"scaling_vector = np.abs(step) ** self.powers / self.scales if config.matrix_free: return",
"probnum import config, linops, randvars def apply_precon(precon, rv): # public",
"Nordsieck coordinates (which store the Taylor coefficients instead of the",
"preconditioners in state space models. For some models, this makes",
"to the 'randprocs' namespace # (i.e. not imported in any",
"additional cost. # See Issues #319 and #329. # When",
"into the signature in the future raise NotImplementedError @cached_property def",
"Cholesky factor for square-root filtering, # we also update the",
"as preconditioners in state space models. For some models, this",
"powers = np.arange(order, -1, -1) scales = scipy.special.factorial(powers) return cls(",
"np.diag(scaling_vector)) @cached_property def inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers, scales=1.0",
"to update the Cholesky factor for square-root filtering, # we",
"np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) -> \"NordsieckLikeCoordinates\": return NordsieckLikeCoordinates( powers=-self.powers,",
"scales, dimension): # Clean way of assembling these coordinates cheaply,",
"scales = scipy.special.factorial(powers) return cls( powers=powers + 0.5, scales=scales, dimension=dimension,",
"import cached_property except ImportError: from cached_property import cached_property import numpy",
"here will hopefully be superfluous. new_mean = precon @ rv.mean",
":class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers, scales, dimension): # Clean way",
"store the Taylor coefficients instead of the derivatives), but better",
"new_cov_cholesky = precon @ rv.cov_cholesky # precon is diagonal, so",
"Cholesky factor computed already or not. # Therefore, since we",
"cheaply, # because the powers and scales of the inverse",
"new_cov = new_cov_cholesky @ new_cov_cholesky.T return randvars.Normal(new_mean, new_cov, cov_cholesky=new_cov_cholesky) class",
"= powers self.scales = scales self.dimension = dimension @classmethod def",
"# used to conveniently initialise in the beginning powers =",
"= scipy.special.factorial(powers) return cls( powers=powers + 0.5, scales=scales, dimension=dimension, )",
"add them into the signature in the future raise NotImplementedError",
"in the future raise NotImplementedError @cached_property def inverse(self) -> \"Preconditioner\":",
"signature in the future raise NotImplementedError @cached_property def inverse(self) ->",
"filtering, # we also update the Cholesky factor for non-square-root",
"randvars def apply_precon(precon, rv): # public (because it is needed",
"ImportError: from cached_property import cached_property import numpy as np import",
"in state space models. For some models, this makes the",
"smoothing. Used in integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self,",
"factor computed already or not. # Therefore, since we need",
"__call__(self, step) -> np.ndarray: # if more than step is",
"linops, randvars def apply_precon(precon, rv): # public (because it is",
"def from_order(cls, order, dimension): # used to conveniently initialise in",
"but not exposed to the 'randprocs' namespace # (i.e. not",
"np.ndarray: # if more than step is needed, add them",
"in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers, scales, dimension): # Clean",
"except ImportError: from cached_property import cached_property import numpy as np",
"(because it is needed in some integrator implementations), # but",
"\"\"\"Nordsieck-like coordinates. Similar to Nordsieck coordinates (which store the Taylor",
"for vectorised factorial from probnum import config, linops, randvars def",
"# See Issues #319 and #329. # When they are",
"# for vectorised factorial from probnum import config, linops, randvars",
"vectorised factorial from probnum import config, linops, randvars def apply_precon(precon,",
"the future raise NotImplementedError @cached_property def inverse(self) -> \"Preconditioner\": raise",
"def __call__(self, step): scaling_vector = np.abs(step) ** self.powers / self.scales",
"for non-square-root algorithms here, # which implies additional cost. #",
") return np.kron(np.eye(self.dimension), np.diag(scaling_vector)) @cached_property def inverse(self) -> \"NordsieckLikeCoordinates\": return",
"factorial from probnum import config, linops, randvars def apply_precon(precon, rv):",
"(i.e. not imported in any __init__.py). # There is no",
"raise NotImplementedError @cached_property def inverse(self) -> \"Preconditioner\": raise NotImplementedError class",
"/ self.scales if config.matrix_free: return linops.Kronecker( A=linops.Identity(self.dimension), B=linops.Scaling(factors=scaling_vector), ) return",
"changes in state space models.\"\"\" import abc try: # cached_property",
"are resolved, this function here will hopefully be superfluous. new_mean",
"Similar to Nordsieck coordinates (which store the Taylor coefficients instead",
"stable. \"\"\" @abc.abstractmethod def __call__(self, step) -> np.ndarray: # if",
"integrator-transitions, e.g. in :class:`IntegratedWienerTransition`. \"\"\" def __init__(self, powers, scales, dimension):",
"way of assembling these coordinates cheaply, # because the powers",
"of the derivatives), but better for ODE filtering and smoothing.",
"integrator implementations), # but not exposed to the 'randprocs' namespace"
] |
[
"self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def extract_uid(self, data): return data['id'] def",
"class LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try",
"= self.account.extra_data.get('last-name', None) if first_name and last_name: name = first_name",
"None) last_name = self.account.extra_data.get('last-name', None) if first_name and last_name: name",
"just return the # low res pass return self.account.extra_data.get('picture-url') def",
"name = first_name + ' ' + last_name return name",
"picture-urls::(original) first try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get(",
"can't get higher res for any reason, we'll just return",
"'picture-url') except: # if we can't get higher res for",
"' + last_name return name class LinkedInProvider(OAuthProvider): id = 'linkedin'",
"from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount):",
"first_name and last_name: name = first_name + ' ' +",
"from allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url')",
"get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try to return the",
"providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from",
"def get_profile_fields(self): default_fields = ['id', 'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)',",
"dflt = super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name', dflt) first_name =",
"+ last_name return name class LinkedInProvider(OAuthProvider): id = 'linkedin' name",
"[] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def get_profile_fields(self): default_fields =",
"if we can't get higher res for any reason, we'll",
"self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: # if",
"data): return data['id'] def extract_common_fields(self, data): return dict(email=data.get('email-address'), first_name=data.get('first-name'), last_name=data.get('last-name'))",
"{}).get( 'picture-url') except: # if we can't get higher res",
"return self.account.extra_data.get('picture-url') def to_str(self): dflt = super(LinkedInAccount, self).to_str() name =",
"get_profile_fields(self): default_fields = ['id', 'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', #",
"LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try to",
"app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): #",
"get_avatar_url(self): # try to return the higher res picture-urls::(original) first",
"low res pass return self.account.extra_data.get('picture-url') def to_str(self): dflt = super(LinkedInAccount,",
"= super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name',",
"last_name = self.account.extra_data.get('last-name', None) if first_name and last_name: name =",
"res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def extract_uid(self,",
"allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import",
"higher res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def",
"picture-urls::(original) is higher res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return",
"try to return the higher res picture-urls::(original) first try: if",
"name class LinkedInProvider(OAuthProvider): id = 'linkedin' name = 'LinkedIn' account_class",
"return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try to return the higher",
"get higher res for any reason, we'll just return the",
"# picture-urls::(original) is higher res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields)",
"= self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name',",
"None) if first_name and last_name: name = first_name + '",
"to return the higher res picture-urls::(original) first try: if self.account.extra_data.get('picture-urls',",
"OAuthProvider from allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self): return",
"dflt) first_name = self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name', None) if",
"fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def extract_uid(self, data): return",
"# try to return the higher res picture-urls::(original) first try:",
"from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider",
"['id', 'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original) is higher",
"return the # low res pass return self.account.extra_data.get('picture-url') def to_str(self):",
"'LinkedIn' account_class = LinkedInAccount def get_default_scope(self): scope = [] if",
"we can't get higher res for any reason, we'll just",
"return name class LinkedInProvider(OAuthProvider): id = 'linkedin' name = 'LinkedIn'",
"higher res picture-urls::(original) first try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return",
"ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import app_settings class",
"import app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self):",
"= LinkedInAccount def get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress')",
"LinkedInProvider(OAuthProvider): id = 'linkedin' name = 'LinkedIn' account_class = LinkedInAccount",
"# low res pass return self.account.extra_data.get('picture-url') def to_str(self): dflt =",
"name = self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name', None) last_name =",
"last_name: name = first_name + ' ' + last_name return",
"'picture-url', 'picture-urls::(original)', # picture-urls::(original) is higher res 'public-profile-url'] fields =",
"def get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope",
"get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def",
"if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: #",
"return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: # if we can't get",
"reason, we'll just return the # low res pass return",
"any reason, we'll just return the # low res pass",
"self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try to return the higher res",
"to_str(self): dflt = super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name', dflt) first_name",
"= 'LinkedIn' account_class = LinkedInAccount def get_default_scope(self): scope = []",
"'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original) is higher res",
"= ['id', 'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original) is",
"from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount",
"fields def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return",
"self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name', None) if first_name and last_name:",
"'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original) is higher res 'public-profile-url']",
"def to_str(self): dflt = super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name', dflt)",
"first_name + ' ' + last_name return name class LinkedInProvider(OAuthProvider):",
"higher res for any reason, we'll just return the #",
"self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: # if we can't get higher",
"self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name', None)",
"= first_name + ' ' + last_name return name class",
"' ' + last_name return name class LinkedInProvider(OAuthProvider): id =",
"we'll just return the # low res pass return self.account.extra_data.get('picture-url')",
"{}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: # if we",
"res for any reason, we'll just return the # low",
"= 'linkedin' name = 'LinkedIn' account_class = LinkedInAccount def get_default_scope(self):",
"def get_avatar_url(self): # try to return the higher res picture-urls::(original)",
"'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original) is higher res 'public-profile-url'] fields",
"name = 'LinkedIn' account_class = LinkedInAccount def get_default_scope(self): scope =",
"extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(email=data.get('email-address'), first_name=data.get('first-name'),",
"is higher res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return fields",
"'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except: # if we can't",
"scope.append('r_emailaddress') return scope def get_profile_fields(self): default_fields = ['id', 'first-name', 'last-name',",
"res picture-urls::(original) first try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls',",
"class LinkedInProvider(OAuthProvider): id = 'linkedin' name = 'LinkedIn' account_class =",
"def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def get_avatar_url(self): # try to return",
"return the higher res picture-urls::(original) first try: if self.account.extra_data.get('picture-urls', {}).get(",
"+ ' ' + last_name return name class LinkedInProvider(OAuthProvider): id",
"'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def extract_uid(self, data):",
"def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(email=data.get('email-address'),",
"LinkedInAccount def get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return",
"if first_name and last_name: name = first_name + ' '",
"return fields def extract_uid(self, data): return data['id'] def extract_common_fields(self, data):",
"'picture-urls::(original)', # picture-urls::(original) is higher res 'public-profile-url'] fields = self.get_settings().get('PROFILE_FIELDS',",
"self.account.extra_data.get('picture-url') def to_str(self): dflt = super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name',",
"= self.get_settings().get('PROFILE_FIELDS', default_fields) return fields def extract_uid(self, data): return data['id']",
"first try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url')",
"id = 'linkedin' name = 'LinkedIn' account_class = LinkedInAccount def",
"import OAuthProvider from allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self):",
"for any reason, we'll just return the # low res",
"= [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def get_profile_fields(self): default_fields",
"except: # if we can't get higher res for any",
"import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider",
"'linkedin' name = 'LinkedIn' account_class = LinkedInAccount def get_default_scope(self): scope",
"scope def get_profile_fields(self): default_fields = ['id', 'first-name', 'last-name', 'email-address', 'picture-url',",
"last_name return name class LinkedInProvider(OAuthProvider): id = 'linkedin' name =",
"self.account.extra_data.get('last-name', None) if first_name and last_name: name = first_name +",
"return scope def get_profile_fields(self): default_fields = ['id', 'first-name', 'last-name', 'email-address',",
"import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import app_settings",
"allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('public-profile-url') def",
"pass return self.account.extra_data.get('picture-url') def to_str(self): dflt = super(LinkedInAccount, self).to_str() name",
"allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import app_settings class LinkedInAccount(ProviderAccount): def",
"the # low res pass return self.account.extra_data.get('picture-url') def to_str(self): dflt",
"first_name = self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name', None) if first_name",
"scope = [] if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def get_profile_fields(self):",
"default_fields) return fields def extract_uid(self, data): return data['id'] def extract_common_fields(self,",
"<filename>allauth/socialaccount/providers/linkedin/provider.py from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from",
"= self.account.extra_data.get('first-name', None) last_name = self.account.extra_data.get('last-name', None) if first_name and",
"# if we can't get higher res for any reason,",
"default_fields = ['id', 'first-name', 'last-name', 'email-address', 'picture-url', 'picture-urls::(original)', # picture-urls::(original)",
"the higher res picture-urls::(original) first try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'):",
"allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import",
"account_class = LinkedInAccount def get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL:",
"and last_name: name = first_name + ' ' + last_name",
"res pass return self.account.extra_data.get('picture-url') def to_str(self): dflt = super(LinkedInAccount, self).to_str()",
"if app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def get_profile_fields(self): default_fields = ['id',",
"self).to_str() name = self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name', None) last_name",
"app_settings.QUERY_EMAIL: scope.append('r_emailaddress') return scope def get_profile_fields(self): default_fields = ['id', 'first-name',",
"try: if self.account.extra_data.get('picture-urls', {}).get( 'picture-url'): return self.account.extra_data.get('picture-urls', {}).get( 'picture-url') except:",
"super(LinkedInAccount, self).to_str() name = self.account.extra_data.get('name', dflt) first_name = self.account.extra_data.get('first-name', None)",
"return data['id'] def extract_common_fields(self, data): return dict(email=data.get('email-address'), first_name=data.get('first-name'), last_name=data.get('last-name')) providers.registry.register(LinkedInProvider)"
] |
[
"test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) #",
"= nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4,",
"= optim.Adam(model.parameters(), lr = 0.001) def train(epoch): for batch_idx, (data,",
"padding=0 ) self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32)",
"0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx",
"Epoch: {} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx * len(data),",
"kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC",
"128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4",
"= torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset =",
"= model(data) loss = F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx",
"train_test_split import time import pandas as pd import numpy as",
"= self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4)",
"batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda()",
"torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in)",
"= torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # ) batch_size =",
"batch_size=batch_size, # shuffle=False # ) batch_size = 128 NUM_EPOCHS =",
"X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1)",
"import torch.optim as optim from torchvision import datasets from torch.autograd",
"shuffle=False # ) batch_size = 128 NUM_EPOCHS = 30 LR",
"X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test",
"self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1,",
"= data/11.0 optimizer.zero_grad() output = model(data) loss = F.cross_entropy(output, target)",
"# 转置后拼接 X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X",
"self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape =",
"#------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train",
"len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_'",
"as nn import torch.nn.functional as F import torch.optim as optim",
"self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape",
"sklearn.model_selection import train_test_split import time import pandas as pd import",
") self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0",
"np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X",
"= X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y",
"shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False",
"Y = np.int64(direction_data) model = CCRNN() model = model.cuda() optimizer",
"[{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100.",
"= self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape",
"data/11.0 optimizer.zero_grad() output = model(data) loss = F.cross_entropy(output, target) loss.backward()",
"= self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data",
"= np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) model",
"pandas as pd import numpy as np import csv batch_size",
") self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC",
"for batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data).cuda(),",
"Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X,",
"# batch_size=batch_size, # shuffle=False # ) batch_size = 128 NUM_EPOCHS",
"TIME_STEP = 4 class CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN,",
"= self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape =",
"= 0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv')",
"Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test)",
"= torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader",
"A = csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X)",
"import torch import torch.nn as nn import torch.nn.functional as F",
"Variable from sklearn.model_selection import train_test_split import time import pandas as",
"= csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X",
"NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 #------------------读入数据-----------------------------",
"np import csv batch_size = 128 NUM_EPOCHS = 30 LR",
"torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl') if __name__ == '__main__':",
"= pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data",
"+ '.pkl') if __name__ == '__main__': for epoch in range(0,",
"torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train)",
"XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16]",
"(data, target) in enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda() data",
"super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True",
"= train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test)",
"batch_size = 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP",
"{} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset),",
"import numpy as np import csv batch_size = 128 NUM_EPOCHS",
"torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True",
"np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train,",
"torch.nn.functional as F import torch.optim as optim from torchvision import",
"from torchvision import datasets from torch.autograd import Variable from sklearn.model_selection",
"def forward(self, x): LSTM_out, (h_n, c_n) = self.ccLSTM(x, None) CNN_in",
"= torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X = np.reshape(X,",
"train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train",
"== 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch,",
"csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X =",
"len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' +",
"LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC,",
"torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # ) batch_size = 128",
"Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train =",
"= model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001) def train(epoch):",
"if __name__ == '__main__': for epoch in range(0, NUM_EPOCHS): train(epoch)",
"import torch.nn as nn import torch.nn.functional as F import torch.optim",
"= np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape)",
"as pd import numpy as np import csv batch_size =",
"output = model(data) loss = F.cross_entropy(output, target) loss.backward() optimizer.step() if",
"hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1,",
"32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut",
"= csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test",
"import train_test_split import time import pandas as pd import numpy",
"print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx *",
"= nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14 =",
"# 继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4,",
"self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data =",
"nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4) def forward(self, x): LSTM_out,",
"F import torch.optim as optim from torchvision import datasets from",
"4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC =",
"kernel_size=2, stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1,",
"4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A",
"data = data/11.0 optimizer.zero_grad() output = model(data) loss = F.cross_entropy(output,",
"import datasets from torch.autograd import Variable from sklearn.model_selection import train_test_split",
"X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train)",
"= 30 LR = 0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data",
"in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d(",
"4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape)",
"= np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接",
"= 0.001) def train(epoch): for batch_idx, (data, target) in enumerate(train_loader):",
"CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC",
":]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out =",
"print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test,",
"stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1),",
"= nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC",
"import torch.nn.functional as F import torch.optim as optim from torchvision",
"= 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values",
"self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0 )",
"nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32)",
"/ len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl') if",
"num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2,",
"= CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC",
"F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx % 50 == 0:",
"target) loss.backward() optimizer.step() if batch_idx % 50 == 0: print('Train",
"= np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X, Y,",
"padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1,",
"torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return out",
"30 LR = 0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data =",
"bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2,",
"= F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx % 50 ==",
"self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14",
"nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128)",
"X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) #",
"__init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128,",
"train(epoch): for batch_idx, (data, target) in enumerate(train_loader): data, target =",
"= nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256,",
"test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # ) batch_size",
"CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM)",
"= 4 class CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN, self).__init__()",
"np.int64(direction_data) model = CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(),",
"'.pkl') if __name__ == '__main__': for epoch in range(0, NUM_EPOCHS):",
"'rnn_model_' + str(epoch) + '.pkl') if __name__ == '__main__': for",
"np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data",
") batch_size = 128 NUM_EPOCHS = 30 LR = 0.001",
"out_channels=1, kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1,",
"csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X =",
"x): LSTM_out, (h_n, c_n) = self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:,",
"0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data",
"CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC",
"model(data) loss = F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx %",
"torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test)",
"forward(self, x): LSTM_out, (h_n, c_n) = self.ccLSTM(x, None) CNN_in =",
"model = model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001) def",
"= np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) #-------------------------------------------------------",
"in enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda() data = data/11.0",
"out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A",
"loss = F.cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx % 50",
"Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx",
"test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train)",
"lr = 0.001) def train(epoch): for batch_idx, (data, target) in",
"# X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data)",
"1) out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My",
"time import pandas as pd import numpy as np import",
"batch_idx % 50 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t",
"class CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM =",
"LR = 0.001 TIME_STEP = 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My",
"np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False)",
"None) CNN_in = torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in)",
"# test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # )",
"csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X =",
"len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl') if __name__",
"4 class CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM",
"CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001)",
"0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14",
"0.001 TIME_STEP = 4 class CCRNN(nn.Module): def __init__(self): # 继承RNN",
"direction_data = csv_data[:,16] Y = np.int64(direction_data) model = CCRNN() model",
"optimizer.zero_grad() output = model(data) loss = F.cross_entropy(output, target) loss.backward() optimizer.step()",
"optimizer = optim.Adam(model.parameters(), lr = 0.001) def train(epoch): for batch_idx,",
"self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22",
"Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output = model(data) loss",
"= 30 LR = 0.001 TIME_STEP = 4 class CCRNN(nn.Module):",
"= csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X",
"4), stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4,",
"torchvision import datasets from torch.autograd import Variable from sklearn.model_selection import",
"as np import csv batch_size = 128 NUM_EPOCHS = 30",
"= self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC),",
"32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4) def",
"Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16]",
"1), stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC =",
"train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset,",
"X = torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X =",
"= CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1,",
"CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1,",
"target) in enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda() data =",
"#------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A =",
"as F import torch.optim as optim from torchvision import datasets",
"CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC =",
"X = np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4)) XT",
"4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC",
"= torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return",
"= self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22",
"c_n) = self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4, :], 1)",
"torch.optim as optim from torchvision import datasets from torch.autograd import",
"pd import numpy as np import csv batch_size = 128",
"Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test",
"self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True )",
"data, target = Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output",
"import csv batch_size = 128 NUM_EPOCHS = 30 LR =",
"* len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) torch.save(self.model,",
"csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] #",
"model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001) def train(epoch): for",
"% 50 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t Loss:",
"X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset",
"= 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP =",
"CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM =",
"torch.autograd import Variable from sklearn.model_selection import train_test_split import time import",
"torch.nn as nn import torch.nn.functional as F import torch.optim as",
"enumerate(train_loader): data, target = Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad()",
"X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y =",
"csv_data[:,16] Y = np.int64(direction_data) model = CCRNN() model = model.cuda()",
"batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item()))",
"self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC =",
"batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl')",
"csv batch_size = 128 NUM_EPOCHS = 30 LR = 0.001",
"print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) model = CCRNN()",
"self.FCtoOut = nn.Linear(256, 4) def forward(self, x): LSTM_out, (h_n, c_n)",
"1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in)",
"CCRNN(nn.Module): def __init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM(",
"CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape",
"out_channels=1, kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4, 64)",
"board_data = csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data)",
"nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d(",
"self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 =",
"= torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader",
"batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, #",
"(-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data =",
"= torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, #",
"= torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test =",
"TIME_STEP = 4 #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data =",
"torch.FloatTensor(board_data) X = np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4))",
"= CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape)",
"= Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output = model(data)",
"str(epoch) + '.pkl') if __name__ == '__main__': for epoch in",
"train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset,",
"= csv_data[:,16] Y = np.int64(direction_data) model = CCRNN() model =",
"= nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 =",
"numpy as np import csv batch_size = 128 NUM_EPOCHS =",
"input_size=4, hidden_size=128, num_layers=4, bidirectional=True, batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1,",
"CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 = self.ccCNN14(CNN_in) CNN22_reshape = CNN_out22.view(-1, 4)",
"CNN41toFC, CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据-----------------------------",
"Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) #",
"in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4,",
"target = Variable(data).cuda(), Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output =",
"self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:,",
"return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values",
"= torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset",
"LSTM_out, (h_n, c_n) = self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4,",
"CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4)",
"np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) model =",
"stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4),",
"= np.int64(direction_data) model = CCRNN() model = model.cuda() optimizer =",
"optimizer.step() if batch_idx % 50 == 0: print('Train Epoch: {}",
"loss.backward() optimizer.step() if batch_idx % 50 == 0: print('Train Epoch:",
"* batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) +",
"csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test =",
"CNN22_reshape = CNN_out22.view(-1, 4) CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape =",
"out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1,",
"import pandas as pd import numpy as np import csv",
"4) def forward(self, x): LSTM_out, (h_n, c_n) = self.ccLSTM(x, None)",
"30 LR = 0.001 TIME_STEP = 4 class CCRNN(nn.Module): def",
"= self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :])",
"optim.Adam(model.parameters(), lr = 0.001) def train(epoch): for batch_idx, (data, target)",
"CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC = self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape)",
"nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d(",
"self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC,",
"datasets from torch.autograd import Variable from sklearn.model_selection import train_test_split import",
"继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4, hidden_size=128, num_layers=4, bidirectional=True,",
"model = CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(), lr",
"+ str(epoch) + '.pkl') if __name__ == '__main__': for epoch",
"nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4)",
"100. * batch_idx / len(train_loader), loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch)",
"epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader),",
"= torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size,",
"X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train =",
"in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1,",
"kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41 = nn.Conv2d( in_channels=1, out_channels=1,",
"CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1,",
"NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 class",
"0.001) def train(epoch): for batch_idx, (data, target) in enumerate(train_loader): data,",
"import Variable from sklearn.model_selection import train_test_split import time import pandas",
"= self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC,",
"CNN_in = torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41",
"= nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4) def forward(self, x):",
"= self.CNN22toFC(CNN22_reshape) CNN14toFC = self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC =",
"padding=0 ) self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1,",
"self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC =",
"def __init__(self): # 继承RNN super(CCRNN, self).__init__() self.ccLSTM = nn.LSTM( input_size=4,",
"# shuffle=False # ) batch_size = 128 NUM_EPOCHS = 30",
"# ) batch_size = 128 NUM_EPOCHS = 30 LR =",
"({:.0f}%)]\\t Loss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. *",
"LR = 0.001 TIME_STEP = 4 class CCRNN(nn.Module): def __init__(self):",
"import time import pandas as pd import numpy as np",
"stride=1, padding=0 ) self.CNN22toFC = nn.Linear(4, 64) self.CNN41toFC = nn.Linear(4,",
"nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(4, 1), stride=1, padding=0 ) self.CNN22toFC =",
"as optim from torchvision import datasets from torch.autograd import Variable",
"转置后拼接 X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X =",
"= csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X",
"CNN14_reshape = CNN_out41.view(-1, 4) CNN41_reshape = CNN_out14.view(-1, 4) CNN22toFC =",
"= CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(), lr =",
") self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0",
"def train(epoch): for batch_idx, (data, target) in enumerate(train_loader): data, target",
"= nn.Linear(256, 4) def forward(self, x): LSTM_out, (h_n, c_n) =",
"out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv')",
"self.ccCNN14 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0 )",
"{:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx /",
"pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data =",
"torch import torch.nn as nn import torch.nn.functional as F import",
") self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0 )",
"from sklearn.model_selection import train_test_split import time import pandas as pd",
"self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut =",
"torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset =",
"-1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1) out",
"= torch.unsqueeze(x[:, 0:4, :], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 =",
"torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size,",
"50 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\t Loss: {:.6f}'.format(",
"Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test =",
"self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM = torch.cat((CNN22toFC, CNN41toFC, CNN14toFC, LSTMtoFC), 1)",
") # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False #",
"if batch_idx % 50 == 0: print('Train Epoch: {} [{}/{}",
"= 0.001 TIME_STEP = 4 class CCRNN(nn.Module): def __init__(self): #",
"torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader =",
"nn.Linear(256, 4) def forward(self, x): LSTM_out, (h_n, c_n) = self.ccLSTM(x,",
"batch_first=True ) self.ccCNN22 = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=2, stride=2, padding=0",
"from torch.autograd import Variable from sklearn.model_selection import train_test_split import time",
"64) self.CNN41toFC = nn.Linear(4, 32) self.CNN14toFC = nn.Linear(4, 32) self.LSTMtoFC",
"(h_n, c_n) = self.ccLSTM(x, None) CNN_in = torch.unsqueeze(x[:, 0:4, :],",
"torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader =",
"Variable(target).cuda() data = data/11.0 optimizer.zero_grad() output = model(data) loss =",
"CNN14toFC, LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data",
"# test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True )",
"= nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41",
"optim from torchvision import datasets from torch.autograd import Variable from",
"128) self.FCtoOut = nn.Linear(256, 4) def forward(self, x): LSTM_out, (h_n,",
"nn import torch.nn.functional as F import torch.optim as optim from",
"LSTMtoFC), 1) out = self.FCtoOut(CNNandLSTM) return out #------------------读入数据----------------------------- csv_data =",
"csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0]",
"= np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4)) XT =",
"direction_data = csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train,",
"self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut = nn.Linear(256, 4) def forward(self,",
"nn.Conv2d( in_channels=1, out_channels=1, kernel_size=(1, 4), stride=1, padding=0 ) self.ccCNN41 =",
":], 1) CNN_out22 = self.ccCNN22(CNN_in) CNN_out41 = self.ccCNN41(CNN_in) CNN_out14 =",
"= nn.Linear(4, 32) self.LSTMtoFC = nn.Linear(256, 128) self.FCtoOut = nn.Linear(256,",
"np.int64(board_data) # 转置后拼接 X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1)",
"self.CNN14toFC(CNN14_reshape) CNN41toFC = self.CNN41toFC(CNN41_reshape) LSTMtoFC = self.LSTMtoFC(LSTM_out[:, -1, :]) CNNandLSTM",
"X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data)",
"loss.item())) torch.save(self.model, 'rnn_model_' + str(epoch) + '.pkl') if __name__ =="
] |
[
"data. def insertTuple(self, relationName, tupleData): if relationName in self.relationMap: return",
"open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f: other = Database.unpack(f.read(), self.storage) self.fromOther(other)",
"self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema) self.checkpoint() else: raise ValueError(\"Relation '\"",
"storageEngine): (relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine,",
"+ \"' while inserting a tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId)",
"the storage layer methods. \"\"\" checkpointEncoding = \"latin1\" checkpointFile =",
"self.relationMap.keys() def hasRelation(self, relationName): return relationName in self.relationMap def relationSchema(self,",
"query(self): return PlanBuilder(db=self) # Returns an iterable for query results,",
"query results, after initializing the given plan. def processQuery(self, queryPlan):",
"primarily maintains a simple catalog, mapping relation names to schema",
"'\" + relationName + \"' found in database\") # DML",
"return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if __name__ == \"__main__\": import",
"os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack()) #",
"DBSchemaDecoder from Query.Plan import PlanBuilder from Storage.StorageEngine import StorageEngine class",
"Storage.StorageEngine import StorageEngine class Database: \"\"\" A top-level database engine",
"newly inserted data. def insertTuple(self, relationName, tupleData): if relationName in",
"methods. \"\"\" checkpointEncoding = \"latin1\" checkpointFile = \"db.catalog\" def __init__(self,",
"from an existing data directory. def restore(self): if self.storage: dbcPath",
"Catalog methods def relations(self): return self.relationMap.keys() def hasRelation(self, relationName): return",
"@classmethod def unpack(cls, buffer, storageEngine): (relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder)",
"DDL statements def createRelation(self, relationName, relationFields): if relationName not in",
"import StorageEngine class Database: \"\"\" A top-level database engine class.",
"if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding)",
"\"restore\" in kwargs if not restoring and checkpointFound: self.restore() def",
"def createRelation(self, relationName, relationFields): if relationName not in self.relationMap: schema",
"relationName in self.relationMap def relationSchema(self, relationName): if relationName in self.relationMap:",
"f: f.write(self.pack()) # Load relations and schema from an existing",
"catalog, mapping relation names to schema objects. Also, it provides",
"return self.storage def bufferPool(self): return self.storage.bufferPool if self.storage else None",
"class Database: \"\"\" A top-level database engine class. For now,",
"{}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound",
"if self.storage: self.storage.close() # Database internal components def storageEngine(self): return",
"self.storage def bufferPool(self): return self.storage.bufferPool if self.storage else None def",
"as wrapping the storage layer methods. \"\"\" checkpointEncoding = \"latin1\"",
"fromOther(self, other): self.relationMap = other.relationMap self.defaultPageSize = other.defaultPageSize self.storage =",
"return self.storage.fileMgr if self.storage else None # User API #",
"(relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True)",
"relations(self): return self.relationMap.keys() def hasRelation(self, relationName): return relationName in self.relationMap",
"layer methods. \"\"\" checkpointEncoding = \"latin1\" checkpointFile = \"db.catalog\" def",
"in self.relationMap: return self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown relation '\"",
"= other.defaultPageSize self.storage = other.storage def close(self): if self.storage: self.storage.close()",
"= kwargs.get(\"other\", None) if other: self.fromOther(other) else: storageArgs = {k:v",
"tupleData) # Queries # Returns an empty query builder that",
"return self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown relation '\" + relationName",
"self.storage.close() # Database internal components def storageEngine(self): return self.storage def",
"DBSchema(relationName, relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema) self.checkpoint() else: raise",
"+ \"' found in database\") # DML statements # Returns",
"simple catalog, mapping relation names to schema objects. Also, it",
"kwargs if not restoring and checkpointFound: self.restore() def fromOther(self, other):",
"createRelation(self, relationName, relationFields): if relationName not in self.relationMap: schema =",
"directory. def checkpoint(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with",
"= kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\",",
"# DML statements # Returns a tuple id for the",
"the database internals to the data directory. def checkpoint(self): if",
"else: storageArgs = {k:v for (k,v) in kwargs.items() \\ if",
"Load relations and schema from an existing data directory. def",
"found in database\") # DML statements # Returns a tuple",
"kwargs.items() \\ if k in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap",
"self.relationMap: return self.relationMap[relationName] # DDL statements def createRelation(self, relationName, relationFields):",
"checkpointFound: self.restore() def fromOther(self, other): self.relationMap = other.relationMap self.defaultPageSize =",
"= other.storage def close(self): if self.storage: self.storage.close() # Database internal",
"def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData)",
"relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema) self.checkpoint() else: raise ValueError(\"Relation",
"to construct query plan objects, as well as wrapping the",
"DBSchemaEncoder, DBSchemaDecoder from Query.Plan import PlanBuilder from Storage.StorageEngine import StorageEngine",
"return self.relationMap[relationName] # DDL statements def createRelation(self, relationName, relationFields): if",
"= Database.unpack(f.read(), self.storage) self.fromOther(other) # Database schema catalog serialization def",
"given plan. def processQuery(self, queryPlan): return queryPlan.prepare(self) # Save the",
"__init__(self, **kwargs): other = kwargs.get(\"other\", None) if other: self.fromOther(other) else:",
"if relationName in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise",
"self.fromOther(other) else: storageArgs = {k:v for (k,v) in kwargs.items() \\",
"relationName in self.relationMap: return self.relationMap[relationName] # DDL statements def createRelation(self,",
"checkpointFile = \"db.catalog\" def __init__(self, **kwargs): other = kwargs.get(\"other\", None)",
"in self.relationMap def relationSchema(self, relationName): if relationName in self.relationMap: return",
"# Queries # Returns an empty query builder that can",
"class. For now, this primarily maintains a simple catalog, mapping",
"relationName + \"' while inserting a tuple\") def deleteTuple(self, tupleId):",
"Returns an iterable for query results, after initializing the given",
"statements # Returns a tuple id for the newly inserted",
"cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer, storageEngine): (relationMap, pageSize) = json.loads(buffer,",
"pack(self): if self.relationMap is not None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder)",
"StorageEngine class Database: \"\"\" A top-level database engine class. For",
"relationName + \"' found in database\") # DML statements #",
"an iterable for query results, after initializing the given plan.",
"mapping relation names to schema objects. Also, it provides the",
"self.storage.bufferPool if self.storage else None def fileManager(self): return self.storage.fileMgr if",
"return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer, storageEngine): (relationMap,",
"that can access the current database. def query(self): return PlanBuilder(db=self)",
"relationName): if relationName in self.relationMap: return self.relationMap[relationName] # DDL statements",
"statements def createRelation(self, relationName, relationFields): if relationName not in self.relationMap:",
"= DBSchema(relationName, relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema) self.checkpoint() else:",
"relationName in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No",
"self.relationMap: return self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown relation '\" +",
"**kwargs): other = kwargs.get(\"other\", None) if other: self.fromOther(other) else: storageArgs",
"queryPlan): return queryPlan.prepare(self) # Save the database internals to the",
"while inserting a tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self,",
"fileManager(self): return self.storage.fileMgr if self.storage else None # User API",
"hasRelation(self, relationName): return relationName in self.relationMap def relationSchema(self, relationName): if",
"Database.checkpointFile)) restoring = \"restore\" in kwargs if not restoring and",
"\"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage",
"def processQuery(self, queryPlan): return queryPlan.prepare(self) # Save the database internals",
"schema catalog serialization def pack(self): if self.relationMap is not None:",
"import PlanBuilder from Storage.StorageEngine import StorageEngine class Database: \"\"\" A",
"from Query.Plan import PlanBuilder from Storage.StorageEngine import StorageEngine class Database:",
"self.defaultPageSize = other.defaultPageSize self.storage = other.storage def close(self): if self.storage:",
"Also, it provides the ability to construct query plan objects,",
"(k,v) in kwargs.items() \\ if k in [\"pageSize\", \"poolSize\", \"dataDir\",",
"User API # Catalog methods def relations(self): return self.relationMap.keys() def",
"del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No relation '\" +",
"insertTuple(self, relationName, tupleData): if relationName in self.relationMap: return self.storage.insertTuple(relationName, tupleData)",
"\"latin1\" checkpointFile = \"db.catalog\" def __init__(self, **kwargs): other = kwargs.get(\"other\",",
"query plan objects, as well as wrapping the storage layer",
"\"\"\" checkpointEncoding = \"latin1\" checkpointFile = \"db.catalog\" def __init__(self, **kwargs):",
"def __init__(self, **kwargs): other = kwargs.get(\"other\", None) if other: self.fromOther(other)",
"with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f: other = Database.unpack(f.read(), self.storage)",
"open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack()) # Load relations and",
"inserting a tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId,",
"bufferPool(self): return self.storage.bufferPool if self.storage else None def fileManager(self): return",
"\"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\",",
"an empty query builder that can access the current database.",
"else: raise ValueError(\"Relation '\" + relationName + \"' already exists\")",
"to the data directory. def checkpoint(self): if self.storage: dbcPath =",
"def relationSchema(self, relationName): if relationName in self.relationMap: return self.relationMap[relationName] #",
"raise ValueError(\"Unknown relation '\" + relationName + \"' while inserting",
"and schema from an existing data directory. def restore(self): if",
"import json, io, os, os.path from Catalog.Schema import DBSchema, DBSchemaEncoder,",
"self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No relation '\" + relationName",
"[\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize =",
"updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries # Returns an",
"else: raise ValueError(\"Unknown relation '\" + relationName + \"' while",
"checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\" in kwargs if",
"not None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer,",
"def hasRelation(self, relationName): return relationName in self.relationMap def relationSchema(self, relationName):",
"if relationName in self.relationMap: return self.relationMap[relationName] # DDL statements def",
"storage layer methods. \"\"\" checkpointEncoding = \"latin1\" checkpointFile = \"db.catalog\"",
"Returns an empty query builder that can access the current",
"data directory. def restore(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)",
"if self.storage else None # User API # Catalog methods",
"relationName in self.relationMap: return self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown relation",
"relationFields): if relationName not in self.relationMap: schema = DBSchema(relationName, relationFields)",
"if not restoring and checkpointFound: self.restore() def fromOther(self, other): self.relationMap",
"internal components def storageEngine(self): return self.storage def bufferPool(self): return self.storage.bufferPool",
"For now, this primarily maintains a simple catalog, mapping relation",
"dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f:",
"the newly inserted data. def insertTuple(self, relationName, tupleData): if relationName",
"plan objects, as well as wrapping the storage layer methods.",
"close(self): if self.storage: self.storage.close() # Database internal components def storageEngine(self):",
"maintains a simple catalog, mapping relation names to schema objects.",
"relations and schema from an existing data directory. def restore(self):",
"kwargs.get(\"other\", None) if other: self.fromOther(other) else: storageArgs = {k:v for",
"top-level database engine class. For now, this primarily maintains a",
"exists\") def removeRelation(self, relationName): if relationName in self.relationMap: del self.relationMap[relationName]",
"def bufferPool(self): return self.storage.bufferPool if self.storage else None def fileManager(self):",
"def fromOther(self, other): self.relationMap = other.relationMap self.defaultPageSize = other.defaultPageSize self.storage",
"else None def fileManager(self): return self.storage.fileMgr if self.storage else None",
"Database internal components def storageEngine(self): return self.storage def bufferPool(self): return",
"kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\" in",
"# Returns an empty query builder that can access the",
"self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown relation '\" + relationName +",
"'\" + relationName + \"' already exists\") def removeRelation(self, relationName):",
"= json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if __name__",
"os, os.path from Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan",
"cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if __name__ == \"__main__\": import doctest",
"for query results, after initializing the given plan. def processQuery(self,",
"json, io, os, os.path from Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder",
"None def fileManager(self): return self.storage.fileMgr if self.storage else None #",
"# Returns an iterable for query results, after initializing the",
"= \"restore\" in kwargs if not restoring and checkpointFound: self.restore()",
"schema = DBSchema(relationName, relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema) self.checkpoint()",
"directory. def restore(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with",
"deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) #",
"self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No relation '\"",
"catalog serialization def pack(self): if self.relationMap is not None: return",
"storageArgs = {k:v for (k,v) in kwargs.items() \\ if k",
"with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack()) # Load relations",
"already exists\") def removeRelation(self, relationName): if relationName in self.relationMap: del",
"\"' already exists\") def removeRelation(self, relationName): if relationName in self.relationMap:",
"tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries # Returns an empty query",
"Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan import PlanBuilder from",
"tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries # Returns an empty",
"# Database internal components def storageEngine(self): return self.storage def bufferPool(self):",
"and checkpointFound: self.restore() def fromOther(self, other): self.relationMap = other.relationMap self.defaultPageSize",
"def checkpoint(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath,",
"well as wrapping the storage layer methods. \"\"\" checkpointEncoding =",
"components def storageEngine(self): return self.storage def bufferPool(self): return self.storage.bufferPool if",
"storageEngine(self): return self.storage def bufferPool(self): return self.storage.bufferPool if self.storage else",
"engine class. For now, this primarily maintains a simple catalog,",
"def pack(self): if self.relationMap is not None: return json.dumps([self.relationMap, self.defaultPageSize],",
"if self.relationMap is not None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod",
"def relations(self): return self.relationMap.keys() def hasRelation(self, relationName): return relationName in",
"existing data directory. def restore(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir,",
"# Returns a tuple id for the newly inserted data.",
"= os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f: other",
"# Load relations and schema from an existing data directory.",
"\"\"\" A top-level database engine class. For now, this primarily",
"in self.relationMap: return self.relationMap[relationName] # DDL statements def createRelation(self, relationName,",
"in self.relationMap: schema = DBSchema(relationName, relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName,",
"current database. def query(self): return PlanBuilder(db=self) # Returns an iterable",
"Database schema catalog serialization def pack(self): if self.relationMap is not",
"if relationName in self.relationMap: return self.storage.insertTuple(relationName, tupleData) else: raise ValueError(\"Unknown",
"buffer, storageEngine): (relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize,",
"\\ if k in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap =",
"{k:v for (k,v) in kwargs.items() \\ if k in [\"pageSize\",",
"plan. def processQuery(self, queryPlan): return queryPlan.prepare(self) # Save the database",
"a tuple id for the newly inserted data. def insertTuple(self,",
"os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f: other =",
"from Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan import PlanBuilder",
"restoring = \"restore\" in kwargs if not restoring and checkpointFound:",
"self.relationMap def relationSchema(self, relationName): if relationName in self.relationMap: return self.relationMap[relationName]",
"schema objects. Also, it provides the ability to construct query",
"Save the database internals to the data directory. def checkpoint(self):",
"= schema self.storage.createRelation(relationName, schema) self.checkpoint() else: raise ValueError(\"Relation '\" +",
"raise ValueError(\"Relation '\" + relationName + \"' already exists\") def",
"\"' while inserting a tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def",
"Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack()) # Load",
"in kwargs if not restoring and checkpointFound: self.restore() def fromOther(self,",
"empty query builder that can access the current database. def",
"'\" + relationName + \"' while inserting a tuple\") def",
"other = Database.unpack(f.read(), self.storage) self.fromOther(other) # Database schema catalog serialization",
"database internals to the data directory. def checkpoint(self): if self.storage:",
"self.relationMap[relationName] # DDL statements def createRelation(self, relationName, relationFields): if relationName",
"ValueError(\"Unknown relation '\" + relationName + \"' while inserting a",
"def insertTuple(self, relationName, tupleData): if relationName in self.relationMap: return self.storage.insertTuple(relationName,",
"def unpack(cls, buffer, storageEngine): (relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return",
"Returns a tuple id for the newly inserted data. def",
"iterable for query results, after initializing the given plan. def",
"the data directory. def checkpoint(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir,",
"serialization def pack(self): if self.relationMap is not None: return json.dumps([self.relationMap,",
"query builder that can access the current database. def query(self):",
"def storageEngine(self): return self.storage def bufferPool(self): return self.storage.bufferPool if self.storage",
"= other.relationMap self.defaultPageSize = other.defaultPageSize self.storage = other.storage def close(self):",
"provides the ability to construct query plan objects, as well",
"else: raise ValueError(\"No relation '\" + relationName + \"' found",
"def fileManager(self): return self.storage.fileMgr if self.storage else None # User",
"the current database. def query(self): return PlanBuilder(db=self) # Returns an",
"PlanBuilder from Storage.StorageEngine import StorageEngine class Database: \"\"\" A top-level",
"database\") # DML statements # Returns a tuple id for",
"return PlanBuilder(db=self) # Returns an iterable for query results, after",
"self.restore() def fromOther(self, other): self.relationMap = other.relationMap self.defaultPageSize = other.defaultPageSize",
"self.relationMap = other.relationMap self.defaultPageSize = other.defaultPageSize self.storage = other.storage def",
"Database: \"\"\" A top-level database engine class. For now, this",
"a tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData):",
"as well as wrapping the storage layer methods. \"\"\" checkpointEncoding",
"database engine class. For now, this primarily maintains a simple",
"json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer, storageEngine): (relationMap, pageSize)",
"unpack(cls, buffer, storageEngine): (relationMap, pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap,",
"self.storage else None # User API # Catalog methods def",
"f: other = Database.unpack(f.read(), self.storage) self.fromOther(other) # Database schema catalog",
"removeRelation(self, relationName): if relationName in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint()",
"Database.unpack(f.read(), self.storage) self.fromOther(other) # Database schema catalog serialization def pack(self):",
"an existing data directory. def restore(self): if self.storage: dbcPath =",
"tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries",
"restore(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r',",
"k in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {})",
"os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\" in kwargs if not restoring",
"self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage =",
"raise ValueError(\"No relation '\" + relationName + \"' found in",
"self.relationMap is not None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def",
"io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring",
"StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\" in kwargs",
"not in self.relationMap: schema = DBSchema(relationName, relationFields) self.relationMap[relationName] = schema",
"\"' found in database\") # DML statements # Returns a",
"id for the newly inserted data. def insertTuple(self, relationName, tupleData):",
"in kwargs.items() \\ if k in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]}",
"None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer, storageEngine):",
"other = kwargs.get(\"other\", None) if other: self.fromOther(other) else: storageArgs =",
"= \"latin1\" checkpointFile = \"db.catalog\" def __init__(self, **kwargs): other =",
"return queryPlan.prepare(self) # Save the database internals to the data",
"in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No relation",
"tuple id for the newly inserted data. def insertTuple(self, relationName,",
"\"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE)",
"if self.storage else None def fileManager(self): return self.storage.fileMgr if self.storage",
"'r', encoding=Database.checkpointEncoding) as f: other = Database.unpack(f.read(), self.storage) self.fromOther(other) #",
"tupleData) else: raise ValueError(\"Unknown relation '\" + relationName + \"'",
"self.storage) self.fromOther(other) # Database schema catalog serialization def pack(self): if",
"self.fromOther(other) # Database schema catalog serialization def pack(self): if self.relationMap",
"can access the current database. def query(self): return PlanBuilder(db=self) #",
"construct query plan objects, as well as wrapping the storage",
"self.storage.updateTuple(tupleId, tupleData) # Queries # Returns an empty query builder",
"self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as",
"if k in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\",",
"= os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\" in kwargs if not",
"PlanBuilder(db=self) # Returns an iterable for query results, after initializing",
"self.relationMap: schema = DBSchema(relationName, relationFields) self.relationMap[relationName] = schema self.storage.createRelation(relationName, schema)",
"DML statements # Returns a tuple id for the newly",
"A top-level database engine class. For now, this primarily maintains",
"relationName): return relationName in self.relationMap def relationSchema(self, relationName): if relationName",
"relationName not in self.relationMap: schema = DBSchema(relationName, relationFields) self.relationMap[relationName] =",
"other.relationMap self.defaultPageSize = other.defaultPageSize self.storage = other.storage def close(self): if",
"kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile))",
"self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring =",
"= \"db.catalog\" def __init__(self, **kwargs): other = kwargs.get(\"other\", None) if",
"inserted data. def insertTuple(self, relationName, tupleData): if relationName in self.relationMap:",
"relationName, relationFields): if relationName not in self.relationMap: schema = DBSchema(relationName,",
"for the newly inserted data. def insertTuple(self, relationName, tupleData): if",
"the given plan. def processQuery(self, queryPlan): return queryPlan.prepare(self) # Save",
"if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding)",
"checkpointEncoding = \"latin1\" checkpointFile = \"db.catalog\" def __init__(self, **kwargs): other",
"API # Catalog methods def relations(self): return self.relationMap.keys() def hasRelation(self,",
"for (k,v) in kwargs.items() \\ if k in [\"pageSize\", \"poolSize\",",
"schema) self.checkpoint() else: raise ValueError(\"Relation '\" + relationName + \"'",
"to schema objects. Also, it provides the ability to construct",
"in database\") # DML statements # Returns a tuple id",
"else None # User API # Catalog methods def relations(self):",
"'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack()) # Load relations and schema",
"other: self.fromOther(other) else: storageArgs = {k:v for (k,v) in kwargs.items()",
"restoring and checkpointFound: self.restore() def fromOther(self, other): self.relationMap = other.relationMap",
"def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries # Returns",
"as f: other = Database.unpack(f.read(), self.storage) self.fromOther(other) # Database schema",
"pageSize=pageSize, storage=storageEngine, restore=True) if __name__ == \"__main__\": import doctest doctest.testmod()",
"other): self.relationMap = other.relationMap self.defaultPageSize = other.defaultPageSize self.storage = other.storage",
"self.storage.removeRelation(relationName) self.checkpoint() else: raise ValueError(\"No relation '\" + relationName +",
"+ relationName + \"' already exists\") def removeRelation(self, relationName): if",
"access the current database. def query(self): return PlanBuilder(db=self) # Returns",
"relationName): if relationName in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName) self.checkpoint() else:",
"builder that can access the current database. def query(self): return",
"+ \"' already exists\") def removeRelation(self, relationName): if relationName in",
"= os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f: f.write(self.pack())",
"tuple\") def deleteTuple(self, tupleId): self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId,",
"io, os, os.path from Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder from",
"from Storage.StorageEngine import StorageEngine class Database: \"\"\" A top-level database",
"if other: self.fromOther(other) else: storageArgs = {k:v for (k,v) in",
"self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound =",
"def close(self): if self.storage: self.storage.close() # Database internal components def",
"Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as f: other = Database.unpack(f.read(),",
"in [\"pageSize\", \"poolSize\", \"dataDir\", \"indexDir\"]} self.relationMap = kwargs.get(\"relations\", {}) self.defaultPageSize",
"self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls, buffer, storageEngine): (relationMap, pageSize) =",
"# Database schema catalog serialization def pack(self): if self.relationMap is",
"= kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)) restoring = \"restore\"",
"now, this primarily maintains a simple catalog, mapping relation names",
"= {k:v for (k,v) in kwargs.items() \\ if k in",
"+ relationName + \"' while inserting a tuple\") def deleteTuple(self,",
"relation names to schema objects. Also, it provides the ability",
"processQuery(self, queryPlan): return queryPlan.prepare(self) # Save the database internals to",
"relation '\" + relationName + \"' found in database\") #",
"database. def query(self): return PlanBuilder(db=self) # Returns an iterable for",
"results, after initializing the given plan. def processQuery(self, queryPlan): return",
"after initializing the given plan. def processQuery(self, queryPlan): return queryPlan.prepare(self)",
"encoding=Database.checkpointEncoding) as f: other = Database.unpack(f.read(), self.storage) self.fromOther(other) # Database",
"schema self.storage.createRelation(relationName, schema) self.checkpoint() else: raise ValueError(\"Relation '\" + relationName",
"self.storage.deleteTuple(tupleId) def updateTuple(self, tupleId, tupleData): self.storage.updateTuple(tupleId, tupleData) # Queries #",
"def query(self): return PlanBuilder(db=self) # Returns an iterable for query",
"return relationName in self.relationMap def relationSchema(self, relationName): if relationName in",
"ValueError(\"Relation '\" + relationName + \"' already exists\") def removeRelation(self,",
"encoding=Database.checkpointEncoding) as f: f.write(self.pack()) # Load relations and schema from",
"def removeRelation(self, relationName): if relationName in self.relationMap: del self.relationMap[relationName] self.storage.removeRelation(relationName)",
"dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w', encoding=Database.checkpointEncoding) as f:",
"the ability to construct query plan objects, as well as",
"initializing the given plan. def processQuery(self, queryPlan): return queryPlan.prepare(self) #",
"ValueError(\"No relation '\" + relationName + \"' found in database\")",
"self.storage = other.storage def close(self): if self.storage: self.storage.close() # Database",
"json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if __name__ ==",
"checkpoint(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'w',",
"self.checkpoint() else: raise ValueError(\"Relation '\" + relationName + \"' already",
"is not None: return json.dumps([self.relationMap, self.defaultPageSize], cls=DBSchemaEncoder) @classmethod def unpack(cls,",
"return self.relationMap.keys() def hasRelation(self, relationName): return relationName in self.relationMap def",
"ability to construct query plan objects, as well as wrapping",
"Queries # Returns an empty query builder that can access",
"self.checkpoint() else: raise ValueError(\"No relation '\" + relationName + \"'",
"self.storage.fileMgr if self.storage else None # User API # Catalog",
"not restoring and checkpointFound: self.restore() def fromOther(self, other): self.relationMap =",
"kwargs.get(\"relations\", {}) self.defaultPageSize = kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs))",
"return self.storage.bufferPool if self.storage else None def fileManager(self): return self.storage.fileMgr",
"this primarily maintains a simple catalog, mapping relation names to",
"None # User API # Catalog methods def relations(self): return",
"\"db.catalog\" def __init__(self, **kwargs): other = kwargs.get(\"other\", None) if other:",
"data directory. def checkpoint(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile)",
"wrapping the storage layer methods. \"\"\" checkpointEncoding = \"latin1\" checkpointFile",
"schema from an existing data directory. def restore(self): if self.storage:",
"def restore(self): if self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath,",
"relationName + \"' already exists\") def removeRelation(self, relationName): if relationName",
"Query.Plan import PlanBuilder from Storage.StorageEngine import StorageEngine class Database: \"\"\"",
"= kwargs.get(\"pageSize\", io.DEFAULT_BUFFER_SIZE) self.storage = kwargs.get(\"storage\", StorageEngine(**storageArgs)) checkpointFound = os.path.exists(os.path.join(self.storage.fileMgr.dataDir,",
"# Catalog methods def relations(self): return self.relationMap.keys() def hasRelation(self, relationName):",
"tupleData): if relationName in self.relationMap: return self.storage.insertTuple(relationName, tupleData) else: raise",
"a simple catalog, mapping relation names to schema objects. Also,",
"relationName, tupleData): if relationName in self.relationMap: return self.storage.insertTuple(relationName, tupleData) else:",
"other.defaultPageSize self.storage = other.storage def close(self): if self.storage: self.storage.close() #",
"relationSchema(self, relationName): if relationName in self.relationMap: return self.relationMap[relationName] # DDL",
"None) if other: self.fromOther(other) else: storageArgs = {k:v for (k,v)",
"self.storage.createRelation(relationName, schema) self.checkpoint() else: raise ValueError(\"Relation '\" + relationName +",
"names to schema objects. Also, it provides the ability to",
"# User API # Catalog methods def relations(self): return self.relationMap.keys()",
"DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan import PlanBuilder from Storage.StorageEngine import",
"f.write(self.pack()) # Load relations and schema from an existing data",
"pageSize) = json.loads(buffer, cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if",
"queryPlan.prepare(self) # Save the database internals to the data directory.",
"if relationName not in self.relationMap: schema = DBSchema(relationName, relationFields) self.relationMap[relationName]",
"cls=DBSchemaDecoder) return cls(relations=relationMap, pageSize=pageSize, storage=storageEngine, restore=True) if __name__ == \"__main__\":",
"other.storage def close(self): if self.storage: self.storage.close() # Database internal components",
"self.storage else None def fileManager(self): return self.storage.fileMgr if self.storage else",
"objects. Also, it provides the ability to construct query plan",
"internals to the data directory. def checkpoint(self): if self.storage: dbcPath",
"# Save the database internals to the data directory. def",
"+ relationName + \"' found in database\") # DML statements",
"methods def relations(self): return self.relationMap.keys() def hasRelation(self, relationName): return relationName",
"as f: f.write(self.pack()) # Load relations and schema from an",
"self.storage: self.storage.close() # Database internal components def storageEngine(self): return self.storage",
"objects, as well as wrapping the storage layer methods. \"\"\"",
"relation '\" + relationName + \"' while inserting a tuple\")",
"os.path from Catalog.Schema import DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan import",
"import DBSchema, DBSchemaEncoder, DBSchemaDecoder from Query.Plan import PlanBuilder from Storage.StorageEngine",
"it provides the ability to construct query plan objects, as",
"self.storage: dbcPath = os.path.join(self.storage.fileMgr.dataDir, Database.checkpointFile) with open(dbcPath, 'r', encoding=Database.checkpointEncoding) as",
"# DDL statements def createRelation(self, relationName, relationFields): if relationName not"
] |
[
"test_arr_add_value(): for _ in range(10): shape = np.random.randint(1, 10, size=np.random.randint(3,",
"numpy as np import mylib def test_arr_add_value(): for _ in",
"in range(10): shape = np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr =",
"= np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok =",
"shape = np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok",
"10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr +",
"= np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi) if",
"np import mylib def test_arr_add_value(): for _ in range(10): shape",
"import mylib def test_arr_add_value(): for _ in range(10): shape =",
"for _ in range(10): shape = np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist()",
"ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi) if not ok:",
"size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr",
"as np import mylib def test_arr_add_value(): for _ in range(10):",
"import numpy as np import mylib def test_arr_add_value(): for _",
"range(10): shape = np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double)",
"= np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi) if not ok: raise",
"in_arr = np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi)",
"np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi) if not",
"np.pi), in_arr + np.pi) if not ok: raise ValueError(\"incorrect result\")",
"<reponame>dboyliao/TaipeiPy-pybind11-buffer-array import numpy as np import mylib def test_arr_add_value(): for",
"def test_arr_add_value(): for _ in range(10): shape = np.random.randint(1, 10,",
"10, size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr, np.pi),",
"_ in range(10): shape = np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr",
"np.random.randint(1, 10, size=np.random.randint(3, 10)).tolist() in_arr = np.random.rand(*shape).astype(np.double) ok = np.allclose(mylib.array_add_value(in_arr,",
"np.allclose(mylib.array_add_value(in_arr, np.pi), in_arr + np.pi) if not ok: raise ValueError(\"incorrect",
"mylib def test_arr_add_value(): for _ in range(10): shape = np.random.randint(1,"
] |
[
"from moderngl_window.meta import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for requested data",
"= \"DATA_LOADERS\" def load(self, meta: DataDescription) -> Any: \"\"\"Load data",
"the configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns:",
"\"\"\" Registry general data files \"\"\" from typing import Any",
"Any: The loaded resource \"\"\" return super().load(meta) data = DataFiles()",
"for requested data files\"\"\" settings_attr = \"DATA_LOADERS\" def load(self, meta:",
"<reponame>DavideRuzza/moderngl-window \"\"\" Registry general data files \"\"\" from typing import",
"data files\"\"\" settings_attr = \"DATA_LOADERS\" def load(self, meta: DataDescription) ->",
"Registry general data files \"\"\" from typing import Any from",
"Returns: Any: The loaded resource \"\"\" return super().load(meta) data =",
"Any from moderngl_window.resources.base import BaseRegistry from moderngl_window.meta import DataDescription class",
"from typing import Any from moderngl_window.resources.base import BaseRegistry from moderngl_window.meta",
"def load(self, meta: DataDescription) -> Any: \"\"\"Load data file with",
"meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns: Any: The loaded resource",
"the resource description Returns: Any: The loaded resource \"\"\" return",
"data file with the configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the",
"DataDescription) -> Any: \"\"\"Load data file with the configured loaders.",
"class DataFiles(BaseRegistry): \"\"\"Registry for requested data files\"\"\" settings_attr = \"DATA_LOADERS\"",
"typing import Any from moderngl_window.resources.base import BaseRegistry from moderngl_window.meta import",
"load(self, meta: DataDescription) -> Any: \"\"\"Load data file with the",
"meta: DataDescription) -> Any: \"\"\"Load data file with the configured",
"import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for requested data files\"\"\" settings_attr",
"Any: \"\"\"Load data file with the configured loaders. Args: meta",
"files\"\"\" settings_attr = \"DATA_LOADERS\" def load(self, meta: DataDescription) -> Any:",
"with the configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description",
"DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for requested data files\"\"\" settings_attr =",
"moderngl_window.meta import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for requested data files\"\"\"",
"\"\"\"Registry for requested data files\"\"\" settings_attr = \"DATA_LOADERS\" def load(self,",
"DataFiles(BaseRegistry): \"\"\"Registry for requested data files\"\"\" settings_attr = \"DATA_LOADERS\" def",
"loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns: Any: The",
"data files \"\"\" from typing import Any from moderngl_window.resources.base import",
"\"\"\" from typing import Any from moderngl_window.resources.base import BaseRegistry from",
"\"DATA_LOADERS\" def load(self, meta: DataDescription) -> Any: \"\"\"Load data file",
"configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns: Any:",
"description Returns: Any: The loaded resource \"\"\" return super().load(meta) data",
"-> Any: \"\"\"Load data file with the configured loaders. Args:",
"\"\"\"Load data file with the configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`):",
"file with the configured loaders. Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource",
"BaseRegistry from moderngl_window.meta import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for requested",
"general data files \"\"\" from typing import Any from moderngl_window.resources.base",
"settings_attr = \"DATA_LOADERS\" def load(self, meta: DataDescription) -> Any: \"\"\"Load",
"from moderngl_window.resources.base import BaseRegistry from moderngl_window.meta import DataDescription class DataFiles(BaseRegistry):",
"resource description Returns: Any: The loaded resource \"\"\" return super().load(meta)",
"moderngl_window.resources.base import BaseRegistry from moderngl_window.meta import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry",
"Args: meta (:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns: Any: The loaded",
"files \"\"\" from typing import Any from moderngl_window.resources.base import BaseRegistry",
"(:py:class:`~moderngl_window.meta.data.DataDescription`): the resource description Returns: Any: The loaded resource \"\"\"",
"import Any from moderngl_window.resources.base import BaseRegistry from moderngl_window.meta import DataDescription",
"import BaseRegistry from moderngl_window.meta import DataDescription class DataFiles(BaseRegistry): \"\"\"Registry for",
"requested data files\"\"\" settings_attr = \"DATA_LOADERS\" def load(self, meta: DataDescription)"
] |
[
"m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show') expected",
"/{controller}/{action} entries /entries entry /entries/{id}\"\"\" for expected_line, actual_line in zip(expected.splitlines(),",
"for expected_line, actual_line in zip(expected.splitlines(), str(m).splitlines()): assert expected_line == actual_line.rstrip()",
"m = Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}',",
"import unittest from routes import Mapper class TestMapperStr(unittest.TestCase): def test_str(self):",
"import Mapper class TestMapperStr(unittest.TestCase): def test_str(self): m = Mapper() m.connect('/{controller}/{action}')",
"entry /entries/{id}\"\"\" for expected_line, actual_line in zip(expected.splitlines(), str(m).splitlines()): assert expected_line",
"controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show') expected = \"\"\"\\ Route",
"m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show') expected =",
"'/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show') expected = \"\"\"\\",
"unittest from routes import Mapper class TestMapperStr(unittest.TestCase): def test_str(self): m",
"m.connect('entry', '/entries/{id}', controller='entry', action='show') expected = \"\"\"\\ Route name Methods",
"/entries/{id}\"\"\" for expected_line, actual_line in zip(expected.splitlines(), str(m).splitlines()): assert expected_line ==",
"Route name Methods Path /{controller}/{action} entries /entries entry /entries/{id}\"\"\" for",
"Path /{controller}/{action} entries /entries entry /entries/{id}\"\"\" for expected_line, actual_line in",
"from routes import Mapper class TestMapperStr(unittest.TestCase): def test_str(self): m =",
"def test_str(self): m = Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index')",
"TestMapperStr(unittest.TestCase): def test_str(self): m = Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry',",
"/entries entry /entries/{id}\"\"\" for expected_line, actual_line in zip(expected.splitlines(), str(m).splitlines()): assert",
"expected = \"\"\"\\ Route name Methods Path /{controller}/{action} entries /entries",
"Mapper class TestMapperStr(unittest.TestCase): def test_str(self): m = Mapper() m.connect('/{controller}/{action}') m.connect('entries',",
"'/entries/{id}', controller='entry', action='show') expected = \"\"\"\\ Route name Methods Path",
"controller='entry', action='show') expected = \"\"\"\\ Route name Methods Path /{controller}/{action}",
"action='show') expected = \"\"\"\\ Route name Methods Path /{controller}/{action} entries",
"\"\"\"\\ Route name Methods Path /{controller}/{action} entries /entries entry /entries/{id}\"\"\"",
"Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show')",
"routes import Mapper class TestMapperStr(unittest.TestCase): def test_str(self): m = Mapper()",
"name Methods Path /{controller}/{action} entries /entries entry /entries/{id}\"\"\" for expected_line,",
"= Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry', '/entries/{id}', controller='entry',",
"class TestMapperStr(unittest.TestCase): def test_str(self): m = Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries',",
"Methods Path /{controller}/{action} entries /entries entry /entries/{id}\"\"\" for expected_line, actual_line",
"entries /entries entry /entries/{id}\"\"\" for expected_line, actual_line in zip(expected.splitlines(), str(m).splitlines()):",
"test_str(self): m = Mapper() m.connect('/{controller}/{action}') m.connect('entries', '/entries', controller='entry', action='index') m.connect('entry',",
"action='index') m.connect('entry', '/entries/{id}', controller='entry', action='show') expected = \"\"\"\\ Route name",
"= \"\"\"\\ Route name Methods Path /{controller}/{action} entries /entries entry"
] |
[
"in host_port_mapping.items(): for port in port_list: s = { \"HOST\":",
"substitute with updated slave config ############### with open(FILE, \"r+\") as",
"host_or_port.isdigit(): # host last_host = host_or_port else: # port host_port_mapping[last_host].append(host_or_port)",
"make sure number of slaves is power of 2 assert",
"# parse hosts and ports to form a slave list",
"last_host = host_or_port else: # port host_port_mapping[last_host].append(host_or_port) assert None not",
"% i, \"CHAIN_MASK_LIST\": [i | slave_num], } slave_servers.append(s) i +=",
"i += 1 ############### # read config file and substitute",
"in args.hostports: # type: str if not host_or_port.isdigit(): # host",
"slave config ############### with open(FILE, \"r+\") as f: parsed_config =",
"assert None not in host_port_mapping slave_num = sum(len(port_list) for port_list",
"usage: python config_slave.py <host1> <port1> <port2> <host2> <port3> ... \"\"\"",
"for host_or_port in args.hostports: # type: str if not host_or_port.isdigit():",
"port_list in host_port_mapping.values()) # make sure number of slaves is",
"port_list in host_port_mapping.items(): for port in port_list: s = {",
"os.chdir(dname) ############### # parse hosts and ports to form a",
"127.0.0.2 18999 18002 will generate 4 slave server configs accordingly.",
"<host2> <port3> ... \"\"\" import argparse import collections import json",
"38006 127.0.0.2 18999 18002 will generate 4 slave server configs",
"0 and (slave_num & (slave_num - 1) == 0) slave_servers,",
"4 slave server configs accordingly. will be used in deployment",
"argparse import collections import json import os FILE = \"../../testnet/2/cluster_config_template.json\"",
"= os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ############### # parse hosts",
"# read config file and substitute with updated slave config",
"if not host_or_port.isdigit(): # host last_host = host_or_port else: #",
"automation to configure a cluster. usage: python config_slave.py <host1> <port1>",
"config file and substitute with updated slave config ############### with",
"import json import os FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in",
"collections.defaultdict(list) last_host = None for host_or_port in args.hostports: # type:",
"18002 will generate 4 slave server configs accordingly. will be",
"generate 4 slave server configs accordingly. will be used in",
"i = [], 0 for host, port_list in host_port_mapping.items(): for",
"127.0.0.1 38000 38006 127.0.0.2 18999 18002 will generate 4 slave",
"parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4))",
"hosts and ports to form a slave list ############### host_port_mapping",
"is power of 2 assert slave_num > 0 and (slave_num",
"> 0 and (slave_num & (slave_num - 1) == 0)",
"slave_servers.append(s) i += 1 ############### # read config file and",
"+= 1 ############### # read config file and substitute with",
"of slaves is power of 2 assert slave_num > 0",
"= slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4)) if __name__ == \"__main__\":",
"} slave_servers.append(s) i += 1 ############### # read config file",
"json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4)) if __name__",
"None for host_or_port in args.hostports: # type: str if not",
"deployment automation to configure a cluster. usage: python config_slave.py <host1>",
"{ \"HOST\": host, \"PORT\": int(port), \"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\":",
"parse hosts and ports to form a slave list ###############",
"= None for host_or_port in args.hostports: # type: str if",
"\"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ: FILE = os.environ[\"QKC_CONFIG\"] def main():",
"\"CHAIN_MASK_LIST\": [i | slave_num], } slave_servers.append(s) i += 1 ###############",
"sure number of slaves is power of 2 assert slave_num",
"for port_list in host_port_mapping.values()) # make sure number of slaves",
"host, \"PORT\": int(port), \"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\": [i |",
"[i | slave_num], } slave_servers.append(s) i += 1 ############### #",
"config ############### with open(FILE, \"r+\") as f: parsed_config = json.load(f)",
"host_port_mapping slave_num = sum(len(port_list) for port_list in host_port_mapping.values()) # make",
"\"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and ports for slave config\", )",
"[], 0 for host, port_list in host_port_mapping.items(): for port in",
"help=\"Host and ports for slave config\", ) args = parser.parse_args()",
"abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ############### # parse",
"str if not host_or_port.isdigit(): # host last_host = host_or_port else:",
"<gh_stars>1-10 \"\"\" python config_slave.py 127.0.0.1 38000 38006 127.0.0.2 18999 18002",
"= sum(len(port_list) for port_list in host_port_mapping.values()) # make sure number",
"slave_num], } slave_servers.append(s) i += 1 ############### # read config",
"not in host_port_mapping slave_num = sum(len(port_list) for port_list in host_port_mapping.values())",
"file and substitute with updated slave config ############### with open(FILE,",
"0) slave_servers, i = [], 0 for host, port_list in",
"sum(len(port_list) for port_list in host_port_mapping.values()) # make sure number of",
"\"S%d\" % i, \"CHAIN_MASK_LIST\": [i | slave_num], } slave_servers.append(s) i",
"and ports for slave config\", ) args = parser.parse_args() abspath",
"port host_port_mapping[last_host].append(host_or_port) assert None not in host_port_mapping slave_num = sum(len(port_list)",
"config_slave.py <host1> <port1> <port2> <host2> <port3> ... \"\"\" import argparse",
"\"HOST\": host, \"PORT\": int(port), \"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\": [i",
"in host_port_mapping slave_num = sum(len(port_list) for port_list in host_port_mapping.values()) #",
"\"\"\" import argparse import collections import json import os FILE",
"import os FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ: FILE",
"in host_port_mapping.values()) # make sure number of slaves is power",
"accordingly. will be used in deployment automation to configure a",
"be used in deployment automation to configure a cluster. usage:",
"f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config,",
"for host, port_list in host_port_mapping.items(): for port in port_list: s",
"18999 18002 will generate 4 slave server configs accordingly. will",
"import collections import json import os FILE = \"../../testnet/2/cluster_config_template.json\" if",
"# host last_host = host_or_port else: # port host_port_mapping[last_host].append(host_or_port) assert",
"will generate 4 slave server configs accordingly. will be used",
"power of 2 assert slave_num > 0 and (slave_num &",
"= os.path.dirname(abspath) os.chdir(dname) ############### # parse hosts and ports to",
"port in port_list: s = { \"HOST\": host, \"PORT\": int(port),",
"main(): parser = argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and",
"config_slave.py 127.0.0.1 38000 38006 127.0.0.2 18999 18002 will generate 4",
"host_or_port in args.hostports: # type: str if not host_or_port.isdigit(): #",
"parser = argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and ports",
"in port_list: s = { \"HOST\": host, \"PORT\": int(port), \"ID\":",
"def main(): parser = argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host",
"1 ############### # read config file and substitute with updated",
"os.path.dirname(abspath) os.chdir(dname) ############### # parse hosts and ports to form",
"config\", ) args = parser.parse_args() abspath = os.path.abspath(__file__) dname =",
"38000 38006 127.0.0.2 18999 18002 will generate 4 slave server",
"slave_servers, i = [], 0 for host, port_list in host_port_mapping.items():",
"== 0) slave_servers, i = [], 0 for host, port_list",
"in os.environ: FILE = os.environ[\"QKC_CONFIG\"] def main(): parser = argparse.ArgumentParser()",
"<port1> <port2> <host2> <port3> ... \"\"\" import argparse import collections",
"server configs accordingly. will be used in deployment automation to",
"slave_num = sum(len(port_list) for port_list in host_port_mapping.values()) # make sure",
"slaves is power of 2 assert slave_num > 0 and",
"= [], 0 for host, port_list in host_port_mapping.items(): for port",
"if \"QKC_CONFIG\" in os.environ: FILE = os.environ[\"QKC_CONFIG\"] def main(): parser",
"= os.environ[\"QKC_CONFIG\"] def main(): parser = argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\",",
"os.environ: FILE = os.environ[\"QKC_CONFIG\"] def main(): parser = argparse.ArgumentParser() parser.add_argument(",
"argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and ports for slave",
"for port in port_list: s = { \"HOST\": host, \"PORT\":",
"############### with open(FILE, \"r+\") as f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"]",
"and ports to form a slave list ############### host_port_mapping =",
"= json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4)) if",
"... \"\"\" import argparse import collections import json import os",
"host last_host = host_or_port else: # port host_port_mapping[last_host].append(host_or_port) assert None",
"in deployment automation to configure a cluster. usage: python config_slave.py",
"<host1> <port1> <port2> <host2> <port3> ... \"\"\" import argparse import",
"FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ: FILE = os.environ[\"QKC_CONFIG\"]",
"\"\"\" python config_slave.py 127.0.0.1 38000 38006 127.0.0.2 18999 18002 will",
"############### # parse hosts and ports to form a slave",
"open(FILE, \"r+\") as f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers",
"json import os FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ:",
"\"QKC_CONFIG\" in os.environ: FILE = os.environ[\"QKC_CONFIG\"] def main(): parser =",
"number of slaves is power of 2 assert slave_num >",
"host_port_mapping = collections.defaultdict(list) last_host = None for host_or_port in args.hostports:",
"port_list: s = { \"HOST\": host, \"PORT\": int(port), \"ID\": \"S%d\"",
"= host_or_port else: # port host_port_mapping[last_host].append(host_or_port) assert None not in",
"############### # read config file and substitute with updated slave",
"will be used in deployment automation to configure a cluster.",
"with updated slave config ############### with open(FILE, \"r+\") as f:",
"parser.parse_args() abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ############### #",
"args.hostports: # type: str if not host_or_port.isdigit(): # host last_host",
"cluster. usage: python config_slave.py <host1> <port1> <port2> <host2> <port3> ...",
"ports to form a slave list ############### host_port_mapping = collections.defaultdict(list)",
"(slave_num - 1) == 0) slave_servers, i = [], 0",
"= \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ: FILE = os.environ[\"QKC_CONFIG\"] def",
"nargs=\"+\", metavar=\"hostports\", help=\"Host and ports for slave config\", ) args",
"os FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\" in os.environ: FILE =",
"form a slave list ############### host_port_mapping = collections.defaultdict(list) last_host =",
"a slave list ############### host_port_mapping = collections.defaultdict(list) last_host = None",
"updated slave config ############### with open(FILE, \"r+\") as f: parsed_config",
"| slave_num], } slave_servers.append(s) i += 1 ############### # read",
"slave config\", ) args = parser.parse_args() abspath = os.path.abspath(__file__) dname",
"of 2 assert slave_num > 0 and (slave_num & (slave_num",
"s = { \"HOST\": host, \"PORT\": int(port), \"ID\": \"S%d\" %",
"FILE = os.environ[\"QKC_CONFIG\"] def main(): parser = argparse.ArgumentParser() parser.add_argument( \"hostports\",",
"slave server configs accordingly. will be used in deployment automation",
"os.environ[\"QKC_CONFIG\"] def main(): parser = argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\",",
"= collections.defaultdict(list) last_host = None for host_or_port in args.hostports: #",
"and substitute with updated slave config ############### with open(FILE, \"r+\")",
"else: # port host_port_mapping[last_host].append(host_or_port) assert None not in host_port_mapping slave_num",
"args = parser.parse_args() abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname)",
"parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4)) if __name__ ==",
"to form a slave list ############### host_port_mapping = collections.defaultdict(list) last_host",
"host_port_mapping.items(): for port in port_list: s = { \"HOST\": host,",
"parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and ports for slave config\",",
"last_host = None for host_or_port in args.hostports: # type: str",
"& (slave_num - 1) == 0) slave_servers, i = [],",
"############### host_port_mapping = collections.defaultdict(list) last_host = None for host_or_port in",
"i, \"CHAIN_MASK_LIST\": [i | slave_num], } slave_servers.append(s) i += 1",
"= { \"HOST\": host, \"PORT\": int(port), \"ID\": \"S%d\" % i,",
"configure a cluster. usage: python config_slave.py <host1> <port1> <port2> <host2>",
"# make sure number of slaves is power of 2",
"os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ############### # parse hosts and",
"slave list ############### host_port_mapping = collections.defaultdict(list) last_host = None for",
"# type: str if not host_or_port.isdigit(): # host last_host =",
"list ############### host_port_mapping = collections.defaultdict(list) last_host = None for host_or_port",
"2 assert slave_num > 0 and (slave_num & (slave_num -",
"slave_num > 0 and (slave_num & (slave_num - 1) ==",
"None not in host_port_mapping slave_num = sum(len(port_list) for port_list in",
"= argparse.ArgumentParser() parser.add_argument( \"hostports\", nargs=\"+\", metavar=\"hostports\", help=\"Host and ports for",
"read config file and substitute with updated slave config ###############",
"used in deployment automation to configure a cluster. usage: python",
"slave_servers f.seek(0) f.truncate() f.write(json.dumps(parsed_config, indent=4)) if __name__ == \"__main__\": main()",
"assert slave_num > 0 and (slave_num & (slave_num - 1)",
"python config_slave.py <host1> <port1> <port2> <host2> <port3> ... \"\"\" import",
"and (slave_num & (slave_num - 1) == 0) slave_servers, i",
"as f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0) f.truncate()",
"\"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\": [i | slave_num], } slave_servers.append(s)",
"import argparse import collections import json import os FILE =",
"host_or_port else: # port host_port_mapping[last_host].append(host_or_port) assert None not in host_port_mapping",
"to configure a cluster. usage: python config_slave.py <host1> <port1> <port2>",
"<port2> <host2> <port3> ... \"\"\" import argparse import collections import",
"host_port_mapping[last_host].append(host_or_port) assert None not in host_port_mapping slave_num = sum(len(port_list) for",
"<port3> ... \"\"\" import argparse import collections import json import",
"ports for slave config\", ) args = parser.parse_args() abspath =",
"configs accordingly. will be used in deployment automation to configure",
"collections import json import os FILE = \"../../testnet/2/cluster_config_template.json\" if \"QKC_CONFIG\"",
"a cluster. usage: python config_slave.py <host1> <port1> <port2> <host2> <port3>",
"not host_or_port.isdigit(): # host last_host = host_or_port else: # port",
"1) == 0) slave_servers, i = [], 0 for host,",
"with open(FILE, \"r+\") as f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] =",
"host_port_mapping.values()) # make sure number of slaves is power of",
"\"r+\") as f: parsed_config = json.load(f) parsed_config[\"SLAVE_LIST\"] = slave_servers f.seek(0)",
"int(port), \"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\": [i | slave_num], }",
"- 1) == 0) slave_servers, i = [], 0 for",
"for slave config\", ) args = parser.parse_args() abspath = os.path.abspath(__file__)",
"= parser.parse_args() abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ###############",
"metavar=\"hostports\", help=\"Host and ports for slave config\", ) args =",
"dname = os.path.dirname(abspath) os.chdir(dname) ############### # parse hosts and ports",
"# port host_port_mapping[last_host].append(host_or_port) assert None not in host_port_mapping slave_num =",
"0 for host, port_list in host_port_mapping.items(): for port in port_list:",
"host, port_list in host_port_mapping.items(): for port in port_list: s =",
"\"PORT\": int(port), \"ID\": \"S%d\" % i, \"CHAIN_MASK_LIST\": [i | slave_num],",
"python config_slave.py 127.0.0.1 38000 38006 127.0.0.2 18999 18002 will generate",
"type: str if not host_or_port.isdigit(): # host last_host = host_or_port",
"(slave_num & (slave_num - 1) == 0) slave_servers, i =",
") args = parser.parse_args() abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath)"
] |
[
"list of strings. Using a while loop, append each string",
"list as input and contains a while loop that only",
"while i<length: str = in_list[i] i+=1 if str==\"bye\" or i>10:",
"i<length: number = input_lst[i] i+=1 if number==7: break else :",
"rewrite the problem so that it does the same thing,",
"its parameter, and contains a while loop that only stops",
"parameter. In the function, use a while loop to return",
"takes a list as its parameter, and contains a while",
"original list up until it reaches the string “STOP” (it",
"str = \"\" i = 0 while str!=\"STOP\": str =",
"a list as input and contains a while loop that",
"Below is a for loop that works. Underneath the for",
"the element of the # list is the number 7.",
"list() str = \"\" i = 0 while str!=\"z\": str",
"i+=1 if str==\"STOP\": break else: out_list.append(str) return out_list #4) Write",
"21, 33] lenght = len(lst) i = 0 sum2 =",
"and contains a while loop that only stops once the",
"to make this even more of a challenge, do this",
"of a for loop. # Assign the accumulated total in",
"is returned is a list that contains up to the",
"“bye” is the 5th element, the first 4 are returned.)",
"loop, rewrite the problem so that it does the same",
"the problem so that it does the same thing, but",
"while loop, append each string to a new list until",
"first 4 are returned.) If you want to make this",
"the string “STOP”). def sublist(in_lst): out_list = list() str =",
"while loop to return a sublist of the input list.",
"only stops once the element of the list is the",
"while str!=\"z\": str = in_lst[i] i+=1 if str==\"z\": break else:",
"a while loop, append each string to a new list",
"#3) Write a function, sublist, that takes in a list",
"function, use a while loop to return a sublist of",
"that only stops once the element of the # list",
"str==\"z\": break else: out_list.append(str) return out_list #5) Below is a",
"takes a list as input and contains a while loop",
"0 print(input_lst) print(len(input_lst)) length = len(input_lst) while i<length: number =",
"to the variable sum2. Once complete, sum2 should equal sum1.",
"function called check_nums that takes a list as its parameter,",
"= len(input_lst) while i<length: number = input_lst[i] i+=1 if number==5:",
"break else : out_lst.append(number) print(out_lst) return out_lst #3) Write a",
"the element of the list is the string ‘bye’. #",
"loop instead of a for loop. # Assign the accumulated",
"is the number 7. What is returned is a list",
"to the first 10 strings, regardless of where the loop",
"Write a function called stop_at_z that iterates through a list",
"# appears is “z”. The function should return the new",
"the parameter. In the function, use a while loop to",
"loop to return a sublist of the input list. #",
"do this without slicing def beginning(in_list): length = len(in_list) out_lst",
"reaches the string “STOP” (it should not contain the string",
"list() number = 0 i = 0 print(input_lst) print(len(input_lst)) length",
"def stop_at_z(in_lst): out_list = list() str = \"\" i =",
"the first 10 are # returned. If “bye” is the",
"i = 0 sum2 = 0 while i<lenght: sum2 +=",
"out_lst.append(number) print(out_lst) return out_lst #3) Write a function, sublist, that",
"first 10 are # returned. If “bye” is the 5th",
"the first 10 strings, regardless of where the loop stops.",
"if str==\"STOP\": break else: out_list.append(str) return out_list #4) Write a",
"it stops on the 32nd element, the first 10 are",
"until it reaches 7.def check_nums(input_lst): def check_nums(input_lst): out_lst = list()",
"i+=1 if str==\"z\": break else: out_list.append(str) return out_list #5) Below",
"as input and contains a while loop that only stops",
": out_lst.append(number) print(out_lst) return out_lst #2) Write a function called",
"str = in_lst[i] i+=1 if str==\"z\": break else: out_list.append(str) return",
"input and contains a while loop that only stops once",
"list up until it reaches the number 5 (it should",
"a list as its parameter, and contains a while loop",
"return out_list #5) Below is a for loop that works.",
"loop that works. Underneath the for loop, rewrite the problem",
"number==7: break else : out_lst.append(number) print(out_lst) return out_lst #3) Write",
"function should return the new list. def stop_at_z(in_lst): out_list =",
"print(len(input_lst)) length = len(input_lst) while i<length: number = input_lst[i] i+=1",
"through a list of strings. Using a while loop, append",
"challenge, do this without slicing def beginning(in_list): length = len(in_list)",
"the number 5 (it should not contain the number 5).",
"Write a function, sublist, that takes in a list of",
"complete, sum2 should equal sum1. lst = [65, 78, 21,",
"that works. Underneath the for loop, rewrite the problem so",
"the # list is the number 7. What is returned",
"Challenge: Write a function called beginning that takes a list",
"i+=1 if number==7: break else : out_lst.append(number) print(out_lst) return out_lst",
"33] lenght = len(lst) i = 0 sum2 = 0",
"only stops once the element of the # list is",
"if str==\"z\": break else: out_list.append(str) return out_list #5) Below is",
"in_lst[i] i+=1 if str==\"STOP\": break else: out_list.append(str) return out_list #4)",
"out_list #4) Write a function called stop_at_z that iterates through",
"string to a new list until the string that #",
"for loop. # Assign the accumulated total in the while",
"out_lst #3) Write a function, sublist, that takes in a",
"contains up to the first 10 strings, regardless of where",
"str = \"\" while i<length: str = in_list[i] i+=1 if",
"#2) Write a function called check_nums that takes a list",
"until it reaches the string “STOP” (it should not contain",
"0 while str!=\"STOP\": str = in_lst[i] i+=1 if str==\"STOP\": break",
"str = in_lst[i] i+=1 if str==\"STOP\": break else: out_list.append(str) return",
"32nd element, the first 10 are # returned. If “bye”",
"that it does the same thing, but using a while",
"out_lst = list() number = 0 i = 0 print(input_lst)",
"if number==5: break else : out_lst.append(number) print(out_lst) return out_lst #2)",
"does the same thing, but using a while loop instead",
"in a list of strings as the parameter. In the",
"The function should return the new list. def stop_at_z(in_lst): out_list",
"= \"\" while i<length: str = in_list[i] i+=1 if str==\"bye\"",
"return out_lst #3) Write a function, sublist, that takes in",
"a for loop. # Assign the accumulated total in the",
"the 32nd element, the first 10 are # returned. If",
"slicing def beginning(in_list): length = len(in_list) out_lst = list() i",
"in a list of numbers as the parameter. In the",
"loop that only stops once the element of the list",
"is “z”. The function should return the new list. def",
"the same values of the original list up until it",
"If you want to make this even more of a",
"element of the # list is the number 7. What",
"stop_at_z that iterates through a list of strings. Using a",
"a while loop instead of a for loop. # Assign",
"called stop_at_z that iterates through a list of strings. Using",
"input list. # The sublist should contain the same values",
"so that it does the same thing, but using a",
"while i<length: number = input_lst[i] i+=1 if number==5: break else",
"that iterates through a list of strings. Using a while",
"# list is the number 7. What is returned is",
"lst = [65, 78, 21, 33] lenght = len(lst) i",
"out_list #5) Below is a for loop that works. Underneath",
"check_nums(input_lst): def check_nums(input_lst): out_lst = list() number = 0 i",
"Write a function called beginning that takes a list as",
"iterates through a list of strings. Using a while loop,",
"list() i = 0 str = \"\" while i<length: str",
"length = len(in_list) out_lst = list() i = 0 str",
"the for loop, rewrite the problem so that it does",
"number 7. What is returned is a list of all",
"the original list up until it reaches the string “STOP”",
"a new list until the string that # appears is",
"until it reaches the number 5 (it should not contain",
"without slicing def beginning(in_list): length = len(in_list) out_lst = list()",
"string that # appears is “z”. The function should return",
"should not contain the number 5). def sublist(input_lst): out_lst =",
"called check_nums that takes a list as its parameter, and",
"it does the same thing, but using a while loop",
"len(in_list) out_lst = list() i = 0 str = \"\"",
"\"\" i = 0 while str!=\"STOP\": str = in_lst[i] i+=1",
"[65, 78, 21, 33] lenght = len(lst) i = 0",
"else: out_list.append(str) return out_list #4) Write a function called stop_at_z",
"10 strings, regardless of where the loop stops. (i.e., if",
"the number 7. What is returned is a list of",
"a function called beginning that takes a list as input",
"a challenge, do this without slicing def beginning(in_list): length =",
"str!=\"z\": str = in_lst[i] i+=1 if str==\"z\": break else: out_list.append(str)",
": out_lst.append(number) print(out_lst) return out_lst #3) Write a function, sublist,",
"list of strings as the parameter. In the function, use",
"element, the first 4 are returned.) If you want to",
"same values of the original list up until it reaches",
"i+=1 #6) Challenge: Write a function called beginning that takes",
"a function called stop_at_z that iterates through a list of",
"= [65, 78, 21, 33] lenght = len(lst) i =",
"list of all of the numbers up until it reaches",
"contain the string “STOP”). def sublist(in_lst): out_list = list() str",
"the while loop code to the variable sum2. Once complete,",
"out_lst.append(number) print(out_lst) return out_lst #2) Write a function called check_nums",
"else: out_list.append(str) return out_list #5) Below is a for loop",
"def sublist(input_lst): out_lst = list() number = 0 i =",
"# returned. If “bye” is the 5th element, the first",
"# The sublist should contain the same values of the",
"= 0 while i<lenght: sum2 += lst[i] i+=1 #6) Challenge:",
"function called stop_at_z that iterates through a list of strings.",
"break else : out_lst.append(number) print(out_lst) return out_lst #2) Write a",
"that takes in a list of strings as the parameter.",
"loop code to the variable sum2. Once complete, sum2 should",
"the input list. # The sublist should contain the same",
"takes in a list of strings as the parameter. In",
"5th element, the first 4 are returned.) If you want",
"it reaches the number 5 (it should not contain the",
"string “STOP” (it should not contain the string “STOP”). def",
"new list until the string that # appears is “z”.",
"once the element of the list is the string ‘bye’.",
"= in_lst[i] i+=1 if str==\"z\": break else: out_list.append(str) return out_list",
"that takes a list as its parameter, and contains a",
"0 i = 0 print(input_lst) print(len(input_lst)) length = len(input_lst) while",
"while i<lenght: sum2 += lst[i] i+=1 #6) Challenge: Write a",
"string “STOP”). def sublist(in_lst): out_list = list() str = \"\"",
"0 str = \"\" while i<length: str = in_list[i] i+=1",
"all of the numbers up until it reaches 7.def check_nums(input_lst):",
"a for loop that works. Underneath the for loop, rewrite",
"(it should not contain the number 5). def sublist(input_lst): out_lst",
"number = input_lst[i] i+=1 if number==7: break else : out_lst.append(number)",
"once the element of the # list is the number",
"up until it reaches 7.def check_nums(input_lst): def check_nums(input_lst): out_lst =",
"using a while loop instead of a for loop. #",
"that only stops once the element of the list is",
"of the original list up until it reaches the number",
"append each string to a new list until the string",
"#5) Below is a for loop that works. Underneath the",
"string ‘bye’. # What is returned is a list that",
"the variable sum2. Once complete, sum2 should equal sum1. lst",
"list. def stop_at_z(in_lst): out_list = list() str = \"\" i",
"a function, sublist, that takes in a list of numbers",
"loop, append each string to a new list until the",
"of strings as the parameter. In the function, use a",
"should not contain the string “STOP”). def sublist(in_lst): out_list =",
"stops once the element of the # list is the",
"a list that contains up to the first 10 strings,",
"loop. # Assign the accumulated total in the while loop",
"element of the list is the string ‘bye’. # What",
"in_list[i] i+=1 if str==\"bye\" or i>10: break out_lst.append(str) return out_lst",
"it reaches the string “STOP” (it should not contain the",
"= 0 while str!=\"STOP\": str = in_lst[i] i+=1 if str==\"STOP\":",
"contain the number 5). def sublist(input_lst): out_lst = list() number",
"lst[i] i+=1 #6) Challenge: Write a function called beginning that",
"sum2 = 0 while i<lenght: sum2 += lst[i] i+=1 #6)",
"\"\" i = 0 while str!=\"z\": str = in_lst[i] i+=1",
"up to the first 10 strings, regardless of where the",
"of the list is the string ‘bye’. # What is",
"the new list. def stop_at_z(in_lst): out_list = list() str =",
"str==\"STOP\": break else: out_list.append(str) return out_list #4) Write a function",
"not contain the string “STOP”). def sublist(in_lst): out_list = list()",
"use a while loop to return a sublist of the",
"= len(in_list) out_lst = list() i = 0 str =",
"total in the while loop code to the variable sum2.",
"sum1. lst = [65, 78, 21, 33] lenght = len(lst)",
"= list() str = \"\" i = 0 while str!=\"STOP\":",
"appears is “z”. The function should return the new list.",
"i = 0 while str!=\"z\": str = in_lst[i] i+=1 if",
"while loop code to the variable sum2. Once complete, sum2",
"the string that # appears is “z”. The function should",
"parameter, and contains a while loop that only stops once",
"beginning(in_list): length = len(in_list) out_lst = list() i = 0",
"equal sum1. lst = [65, 78, 21, 33] lenght =",
"“STOP”). def sublist(in_lst): out_list = list() str = \"\" i",
"a list of strings. Using a while loop, append each",
"check_nums that takes a list as its parameter, and contains",
"works. Underneath the for loop, rewrite the problem so that",
"strings. Using a while loop, append each string to a",
"each string to a new list until the string that",
"the string ‘bye’. # What is returned is a list",
"list is the number 7. What is returned is a",
"while loop that only stops once the element of the",
"def check_nums(input_lst): out_lst = list() number = 0 i =",
"stops once the element of the list is the string",
"is a list that contains up to the first 10",
"stops. (i.e., if it stops on the 32nd element, the",
"i<length: number = input_lst[i] i+=1 if number==5: break else :",
"loop stops. (i.e., if it stops on the 32nd element,",
"In the function, use a while loop to return a",
"= \"\" i = 0 while str!=\"z\": str = in_lst[i]",
"= in_list[i] i+=1 if str==\"bye\" or i>10: break out_lst.append(str) return",
"a sublist of the input list. # The sublist should",
"should return the new list. def stop_at_z(in_lst): out_list = list()",
"new list. def stop_at_z(in_lst): out_list = list() str = \"\"",
"as the parameter. In the function, use a while loop",
"= list() number = 0 i = 0 print(input_lst) print(len(input_lst))",
"return out_list #4) Write a function called stop_at_z that iterates",
"takes in a list of numbers as the parameter. In",
"of a challenge, do this without slicing def beginning(in_list): length",
"list() str = \"\" i = 0 while str!=\"STOP\": str",
"a while loop that only stops once the element of",
"of the # list is the number 7. What is",
"returned.) If you want to make this even more of",
"5 (it should not contain the number 5). def sublist(input_lst):",
"#6) Challenge: Write a function called beginning that takes a",
"print(out_lst) return out_lst #3) Write a function, sublist, that takes",
"Once complete, sum2 should equal sum1. lst = [65, 78,",
"where the loop stops. (i.e., if it stops on the",
"are # returned. If “bye” is the 5th element, the",
"\"\" while i<length: str = in_list[i] i+=1 if str==\"bye\" or",
"you want to make this even more of a challenge,",
"7.def check_nums(input_lst): def check_nums(input_lst): out_lst = list() number = 0",
"contains a while loop that only stops once the element",
"out_lst = list() i = 0 str = \"\" while",
"number 5). def sublist(input_lst): out_lst = list() number = 0",
"sum2 += lst[i] i+=1 #6) Challenge: Write a function called",
"first 10 strings, regardless of where the loop stops. (i.e.,",
"of where the loop stops. (i.e., if it stops on",
"returned is a list that contains up to the first",
"is a list of all of the numbers up until",
"sublist, that takes in a list of numbers as the",
"list as its parameter, and contains a while loop that",
"= input_lst[i] i+=1 if number==7: break else : out_lst.append(number) print(out_lst)",
"return out_lst #2) Write a function called check_nums that takes",
"numbers as the parameter. In the function, use a while",
"4 are returned.) If you want to make this even",
"is a for loop that works. Underneath the for loop,",
"input_lst[i] i+=1 if number==7: break else : out_lst.append(number) print(out_lst) return",
"(i.e., if it stops on the 32nd element, the first",
"list is the string ‘bye’. # What is returned is",
"= input_lst[i] i+=1 if number==5: break else : out_lst.append(number) print(out_lst)",
"sublist of the input list. # The sublist should contain",
"list of numbers as the parameter. In the function, use",
"sublist(in_lst): out_list = list() str = \"\" i = 0",
"reaches 7.def check_nums(input_lst): def check_nums(input_lst): out_lst = list() number =",
"#4) Write a function called stop_at_z that iterates through a",
"78, 21, 33] lenght = len(lst) i = 0 sum2",
"more of a challenge, do this without slicing def beginning(in_list):",
"(it should not contain the string “STOP”). def sublist(in_lst): out_list",
"of the numbers up until it reaches 7.def check_nums(input_lst): def",
"function called beginning that takes a list as input and",
"for loop that works. Underneath the for loop, rewrite the",
"up until it reaches the number 5 (it should not",
"“STOP” (it should not contain the string “STOP”). def sublist(in_lst):",
"stops on the 32nd element, the first 10 are #",
"that takes a list as input and contains a while",
"this even more of a challenge, do this without slicing",
"sum2. Once complete, sum2 should equal sum1. lst = [65,",
"= 0 str = \"\" while i<length: str = in_list[i]",
"the 5th element, the first 4 are returned.) If you",
"accumulated total in the while loop code to the variable",
"loop that only stops once the element of the #",
"list until the string that # appears is “z”. The",
"Write a function called check_nums that takes a list as",
"strings as the parameter. In the function, use a while",
"str = in_list[i] i+=1 if str==\"bye\" or i>10: break out_lst.append(str)",
"the first 4 are returned.) If you want to make",
"sublist(input_lst): out_lst = list() number = 0 i = 0",
"list. # The sublist should contain the same values of",
"if number==7: break else : out_lst.append(number) print(out_lst) return out_lst #3)",
"returned is a list of all of the numbers up",
"are returned.) If you want to make this even more",
"if it stops on the 32nd element, the first 10",
"for loop, rewrite the problem so that it does the",
"a list of all of the numbers up until it",
"break else: out_list.append(str) return out_list #5) Below is a for",
"same thing, but using a while loop instead of a",
"make this even more of a challenge, do this without",
"is returned is a list of all of the numbers",
"i<length: str = in_list[i] i+=1 if str==\"bye\" or i>10: break",
"sublist, that takes in a list of strings as the",
"number 5 (it should not contain the number 5). def",
"else : out_lst.append(number) print(out_lst) return out_lst #3) Write a function,",
"i = 0 str = \"\" while i<length: str =",
"= len(lst) i = 0 sum2 = 0 while i<lenght:",
"is the 5th element, the first 4 are returned.) If",
"this without slicing def beginning(in_list): length = len(in_list) out_lst =",
"to return a sublist of the input list. # The",
"What is returned is a list that contains up to",
"the numbers up until it reaches 7.def check_nums(input_lst): def check_nums(input_lst):",
"‘bye’. # What is returned is a list that contains",
"thing, but using a while loop instead of a for",
"#1) Write a function, sublist, that takes in a list",
"0 while i<lenght: sum2 += lst[i] i+=1 #6) Challenge: Write",
"break else: out_list.append(str) return out_list #4) Write a function called",
"out_list.append(str) return out_list #5) Below is a for loop that",
"number = input_lst[i] i+=1 if number==5: break else : out_lst.append(number)",
"the original list up until it reaches the number 5",
"return the new list. def stop_at_z(in_lst): out_list = list() str",
"str = \"\" i = 0 while str!=\"z\": str =",
"is the string ‘bye’. # What is returned is a",
"list that contains up to the first 10 strings, regardless",
"out_list.append(str) return out_list #4) Write a function called stop_at_z that",
"reaches the number 5 (it should not contain the number",
"of strings. Using a while loop, append each string to",
"returned. If “bye” is the 5th element, the first 4",
"of the input list. # The sublist should contain the",
"= \"\" i = 0 while str!=\"STOP\": str = in_lst[i]",
"str!=\"STOP\": str = in_lst[i] i+=1 if str==\"STOP\": break else: out_list.append(str)",
"that contains up to the first 10 strings, regardless of",
"= 0 i = 0 print(input_lst) print(len(input_lst)) length = len(input_lst)",
"lenght = len(lst) i = 0 sum2 = 0 while",
"len(input_lst) while i<length: number = input_lst[i] i+=1 if number==5: break",
"check_nums(input_lst): out_lst = list() number = 0 i = 0",
"beginning that takes a list as input and contains a",
"# What is returned is a list that contains up",
"a function called check_nums that takes a list as its",
"+= lst[i] i+=1 #6) Challenge: Write a function called beginning",
"variable sum2. Once complete, sum2 should equal sum1. lst =",
"even more of a challenge, do this without slicing def",
"to a new list until the string that # appears",
"print(out_lst) return out_lst #2) Write a function called check_nums that",
"but using a while loop instead of a for loop.",
"strings, regardless of where the loop stops. (i.e., if it",
"else : out_lst.append(number) print(out_lst) return out_lst #2) Write a function",
"of numbers as the parameter. In the function, use a",
"instead of a for loop. # Assign the accumulated total",
"What is returned is a list of all of the",
"= 0 sum2 = 0 while i<lenght: sum2 += lst[i]",
"in_lst[i] i+=1 if str==\"z\": break else: out_list.append(str) return out_list #5)",
"the list is the string ‘bye’. # What is returned",
"it reaches 7.def check_nums(input_lst): def check_nums(input_lst): out_lst = list() number",
"stop_at_z(in_lst): out_list = list() str = \"\" i = 0",
"up until it reaches the string “STOP” (it should not",
"Using a while loop, append each string to a new",
"return a sublist of the input list. # The sublist",
"the number 5). def sublist(input_lst): out_lst = list() number =",
"“z”. The function should return the new list. def stop_at_z(in_lst):",
"len(lst) i = 0 sum2 = 0 while i<lenght: sum2",
"while str!=\"STOP\": str = in_lst[i] i+=1 if str==\"STOP\": break else:",
"on the 32nd element, the first 10 are # returned.",
"in the while loop code to the variable sum2. Once",
"the loop stops. (i.e., if it stops on the 32nd",
"0 while str!=\"z\": str = in_lst[i] i+=1 if str==\"z\": break",
"a function, sublist, that takes in a list of strings",
"numbers up until it reaches 7.def check_nums(input_lst): def check_nums(input_lst): out_lst",
"The sublist should contain the same values of the original",
"code to the variable sum2. Once complete, sum2 should equal",
"that takes in a list of numbers as the parameter.",
"list up until it reaches the string “STOP” (it should",
"function, sublist, that takes in a list of numbers as",
"the function, use a while loop to return a sublist",
"10 are # returned. If “bye” is the 5th element,",
"= list() str = \"\" i = 0 while str!=\"z\":",
"sublist should contain the same values of the original list",
"If “bye” is the 5th element, the first 4 are",
"while i<length: number = input_lst[i] i+=1 if number==7: break else",
"the string “STOP” (it should not contain the string “STOP”).",
"not contain the number 5). def sublist(input_lst): out_lst = list()",
"sum2 should equal sum1. lst = [65, 78, 21, 33]",
"values of the original list up until it reaches the",
"= 0 print(input_lst) print(len(input_lst)) length = len(input_lst) while i<length: number",
"i<lenght: sum2 += lst[i] i+=1 #6) Challenge: Write a function",
"a while loop to return a sublist of the input",
"def beginning(in_list): length = len(in_list) out_lst = list() i =",
"len(input_lst) while i<length: number = input_lst[i] i+=1 if number==7: break",
"Assign the accumulated total in the while loop code to",
"i+=1 if number==5: break else : out_lst.append(number) print(out_lst) return out_lst",
"while loop instead of a for loop. # Assign the",
"5). def sublist(input_lst): out_lst = list() number = 0 i",
"= 0 while str!=\"z\": str = in_lst[i] i+=1 if str==\"z\":",
"contain the same values of the original list up until",
"a list of strings as the parameter. In the function,",
"input_lst[i] i+=1 if number==5: break else : out_lst.append(number) print(out_lst) return",
"0 sum2 = 0 while i<lenght: sum2 += lst[i] i+=1",
"a list of numbers as the parameter. In the function,",
"def sublist(in_lst): out_list = list() str = \"\" i =",
"function, sublist, that takes in a list of strings as",
"number==5: break else : out_lst.append(number) print(out_lst) return out_lst #2) Write",
"i = 0 while str!=\"STOP\": str = in_lst[i] i+=1 if",
"i = 0 print(input_lst) print(len(input_lst)) length = len(input_lst) while i<length:",
"number = 0 i = 0 print(input_lst) print(len(input_lst)) length =",
"# Assign the accumulated total in the while loop code",
"= len(input_lst) while i<length: number = input_lst[i] i+=1 if number==7:",
"= in_lst[i] i+=1 if str==\"STOP\": break else: out_list.append(str) return out_list",
"as its parameter, and contains a while loop that only",
"the accumulated total in the while loop code to the",
"of all of the numbers up until it reaches 7.def",
"original list up until it reaches the number 5 (it",
"= list() i = 0 str = \"\" while i<length:",
"out_lst #2) Write a function called check_nums that takes a",
"that # appears is “z”. The function should return the",
"want to make this even more of a challenge, do",
"out_list = list() str = \"\" i = 0 while",
"element, the first 10 are # returned. If “bye” is",
"problem so that it does the same thing, but using",
"Underneath the for loop, rewrite the problem so that it",
"should contain the same values of the original list up",
"of the original list up until it reaches the string",
"the same thing, but using a while loop instead of",
"regardless of where the loop stops. (i.e., if it stops",
"print(input_lst) print(len(input_lst)) length = len(input_lst) while i<length: number = input_lst[i]",
"called beginning that takes a list as input and contains",
"7. What is returned is a list of all of",
"<filename>python-function-files-dictionaries/week4-assignment1.py #1) Write a function, sublist, that takes in a",
"length = len(input_lst) while i<length: number = input_lst[i] i+=1 if",
"should equal sum1. lst = [65, 78, 21, 33] lenght",
"until the string that # appears is “z”. The function"
] |
[
"@view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data)",
"写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t in",
"serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(",
"role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz =",
"in data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK:",
"Response([one.dict() for one in data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\"",
"GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def list(self,",
"from .filters import GroupFilter, GroupTemplateSystemFilter from .serializers import ( GroupAddMemberSLZ,",
"\"group %s delete members %s by user %s\", group.id, data[\"members\"],",
"GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ,",
"group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s,",
"request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args,",
"id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id,",
"data[\"members\"], request.user.username ) for m in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\")",
"new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return Response([c.dict() for c in",
"lookup_field = \"id\" biz = GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema(",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"return Response({\"count\": count, \"results\": [one.dict() for one in group_members]}) @swagger_auto_schema(",
"\"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() serializer_class =",
"def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def wrapper(view, request, *args,",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class = None # 去掉swagger中的limit offset参数",
"ANY KIND, either express or implied. See the License for",
".filters import GroupFilter, GroupTemplateSystemFilter from .serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ,",
"group_biz = GroupBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED:",
"from backend.apps.group.models import Group from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ",
"return response return wrapper return decorate class GroupQueryMixin: def get_queryset(self):",
"m in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"])",
"user_id = request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"])",
"old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) #",
"[RolePermission] action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value,",
"= { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class",
"serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group = self.group_biz.update(group, data[\"name\"],",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class",
"GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import",
"None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() filterset_class = GroupTemplateSystemFilter",
"responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs):",
"GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data templates =",
"@check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args, **kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True)",
"_ from drf_yasg.utils import swagger_auto_schema from pydantic.tools import parse_obj_as from",
"Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)},",
"context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids,",
"offset参数 queryset = Group.objects.all() lookup_field = \"id\" biz = GroupBiz()",
"conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return",
"**kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject =",
"@swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def",
"= serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group = self.group_biz.update(group,",
"import List from django.shortcuts import get_object_or_404 from django.utils.translation import gettext",
"limit = pagination.get_limit(request) offset = pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id,",
"ConditionTagSLZ from backend.apps.group import tasks # noqa from backend.apps.group.models import",
"ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict() for p",
"GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants import OperateEnum from .filters",
"= RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider)",
") def list(self, request, *args, **kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True)",
"-*- \"\"\" TencentBlueKing is pleased to support the open source",
"get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject)",
"operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs):",
"serializer.validated_data group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1.",
"class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\":",
"backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template import TemplateBiz from",
"slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data system_id = data[\"system_id\"]",
"from backend.apps.group import tasks # noqa from backend.apps.group.models import Group",
"related_resource_type[\"type\"], ) # 2. 对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]),",
"GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): group",
"group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission] action_permission",
"**kwargs) return response return wrapper return decorate class GroupQueryMixin: def",
"responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): return",
"list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\",",
"import TemplateBiz from backend.common.error_codes import error_codes from backend.common.filters import NoCheckModelFilterBackend",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args, **kwargs):",
"retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\",",
"import SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum,",
"lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"],",
"= PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset = Group.objects.all() lookup_field =",
"Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class = None # 去掉swagger中的limit offset参数 queryset",
"data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(group=group)",
"== RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username)",
"== action_id: # 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"]",
"return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self, request, obj): if",
"drf_yasg.utils import swagger_auto_schema from pydantic.tools import parse_obj_as from rest_framework import",
"See the License for the specific language governing permissions and",
"GroupTrans from .audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider,",
"\"id\" group_biz = GroupBiz() group_check_biz = GroupCheckBiz() role_biz = RoleBiz()",
"role_biz = RoleBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED:",
"the License at http://opensource.org/licenses/MIT Unless required by applicable law or",
"group = self.get_object() data = serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role,",
"destroy(self, request, *args, **kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id =",
"= Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\",",
"= data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围",
"from backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean,",
"= TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def",
"= PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action)",
"operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self,",
"request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"],",
"**kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group =",
"# 用户组数量在角色内是否超限 number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) #",
"import audit_context_setter, view_audit_decorator from backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from",
"slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject =",
"= serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group =",
"# 2. 对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition),",
"return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def",
"并且 存在筛选的role_id if role.type == RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内",
"写入审计上下文 audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission]",
"return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\",",
"group_members]}) pagination = LimitOffsetPagination() limit = pagination.get_limit(request) offset = pagination.get_offset(request)",
"检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add members %s",
"= PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes =",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args, **kwargs):",
"检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members(",
"= self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\": count, \"results\": [one.dict() for",
"related_resource_type = data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate",
"members, expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m in members])",
"\"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def",
"pagination.get_limit(request) offset = pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id, limit, offset)",
"operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request,",
"not use this file except in compliance with the License.",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s policy deleted",
"responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): group",
"template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject,",
"self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return",
"you may not use this file except in compliance with",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"the License. You may obtain a copy of the License",
"list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限",
"from .audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider,",
"slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group = self.get_object() subject = Subject(type=SubjectType.GROUP.value,",
"class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field",
"= data[\"members\"] expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject],",
"related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition = related_resource_type.condition if related_resource_type else []",
"import PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter, view_audit_decorator from backend.biz.group import",
"and limitations under the License. \"\"\" import logging from functools",
"group = self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group) return",
"by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited,",
"slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids,",
"get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker = RoleObjectRelationChecker(request.role) if not checker.check_group(group):",
"GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def",
"queryset = Group.objects.all() serializer_class = GroupSLZ filterset_class = GroupFilter lookup_field",
"self.get_object() data = serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates)",
"= self.get_object() action_id = data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type =",
"= slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict() for",
"PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group =",
"\"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None # 去掉swagger中的limit",
"func(view, request, *args, **kwargs) return response return wrapper return decorate",
"group = self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data",
"get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template",
"(C) 2017-2021 THL A29 Limited, a Tencent company. All rights",
"username = request.user.username filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id",
"@swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def list(self, request,",
"# 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group =",
"group_check_biz = GroupCheckBiz() role_biz = RoleBiz() group_trans = GroupTrans() @swagger_auto_schema(",
"import get_object_or_404 from django.utils.translation import gettext as _ from drf_yasg.utils",
"queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")},",
"data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group",
") @view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args, **kwargs): slz = GroupTransferSLZ(data=request.data,",
"GenericViewSet): permission_classes = [RolePermission] action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\":",
"*args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data",
"raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet):",
"law or agreed to in writing, software distributed under the",
"audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)]",
"subject.id, request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限",
"get_queryset(self): request = self.request role = request.role username = request.user.username",
"Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {",
"at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to",
"typing import List from django.shortcuts import get_object_or_404 from django.utils.translation import",
"import ConditionTagBean, ConditionTagBiz from backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker from",
"# 写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request",
"= GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider)",
"*args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider)",
"= serializer.validated_data permission_logger.info( \"group %s delete members %s by user",
"related_resource_type[\"type\"] ) old_condition = related_resource_type.condition if related_resource_type else [] #",
"= PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id == action_id: # 操作操作中对应于资源类型的操作",
"GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\")",
"# noqa from backend.apps.group.models import Group from backend.apps.policy.serializers import PolicyDeleteSLZ,",
"backend.apps.group.models import Group from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from",
"@swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self,",
"not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params)",
"data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group)",
"serializer.validated_data permission_logger.info( \"group %s delete members %s by user %s\",",
"RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz",
"request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request,",
"= self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"],",
"RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can not access group {obj.id}\") class",
"*args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker =",
"1. 查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"],",
"related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2. 对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean],",
"members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members( request.role.id,",
"return decorate class GroupQueryMixin: def get_queryset(self): request = self.request return",
"group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t in data[\"templates\"]], )",
"p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"]",
"Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All",
"GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field = \"id\"",
"[one.dict() for one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"= serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文",
"decorate class GroupQueryMixin: def get_queryset(self): request = self.request return RoleListQuery(request.role,",
"} pagination_class = None # 去掉swagger中的limit offset参数 queryset = Group.objects.all()",
"request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return",
"GroupFilter, GroupTemplateSystemFilter from .serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ,",
"request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def list(self,",
"**kwargs): return super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"],",
"GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz()",
"查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"],",
"view.get_object() readonly = group.readonly if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation),",
"m in members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK:",
"# service group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"@check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args, **kwargs): group = self.get_object() serializer",
"group_members = self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\": count, \"results\": [one.dict()",
"update members %s expired_at by user %s\", group.id, data[\"members\"], request.user.username",
"request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request,",
"TemplateBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"),",
"# 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"group.id) group = self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group)",
"\"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None",
"utf-8 -*- \"\"\" TencentBlueKing is pleased to support the open",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"system_id = slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value,",
"audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission]",
"slz.is_valid(raise_exception=True) data = slz.validated_data system_id = data[\"system_id\"] template_id = data[\"template_id\"]",
"backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ from backend.common.time import",
"keyword) return Response({\"results\": [one.dict() for one in group_members]}) pagination =",
"self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文",
"serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data =",
"self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return Response([c.dict() for",
"= Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\",",
"request, *args, **kwargs): return super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK:",
"from backend.account.permissions import RolePermission, role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ",
"slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id",
"*args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group",
"serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data",
"list(self, request, *args, **kwargs): group = self.get_object() data = self.biz.list_system_counter(group.id)",
") def list(self, request, *args, **kwargs): group = self.get_object() data",
"for c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id,",
"subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2. 对比合并差异 conditions",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args, **kwargs):",
"create(self, request, *args, **kwargs): \"\"\" 创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data)",
"resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition = related_resource_type.condition if related_resource_type else",
"data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2. 对比合并差异 conditions = self.condition_biz.compare_and_tag(",
"= GroupSLZ filterset_class = GroupFilter lookup_field = \"id\" group_biz =",
"wraps from typing import List from django.shortcuts import get_object_or_404 from",
"from backend.common.serializers import SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS from backend.service.constants",
"request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker",
"except in compliance with the License. You may obtain a",
"add members %s by user %s\", group.id, members, request.user.username) #",
"gettext as _ from drf_yasg.utils import swagger_auto_schema from pydantic.tools import",
"by user %s\", group.id, data[\"members\"], request.user.username ) for m in",
"request, *args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object()",
"serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() subject = Subject(type=SubjectType.GROUP.value,",
"= self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2.",
"= GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data members_data",
"request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args,",
"@swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self, request, *args,",
"import gettext as _ from drf_yasg.utils import swagger_auto_schema from pydantic.tools",
"language governing permissions and limitations under the License. \"\"\" import",
"serializer_class = GroupSLZ filterset_class = GroupFilter lookup_field = \"id\" group_biz",
"[one.dict() for one in group_members]}) pagination = LimitOffsetPagination() limit =",
"responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs):",
"updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label)",
"backend.apps.group import tasks # noqa from backend.apps.group.models import Group from",
"response = func(view, request, *args, **kwargs) return response return wrapper",
"in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider)",
"permission_classes = [RolePermission] action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value,",
"= self.get_object() data = serializer.validated_data permission_logger.info( \"group %s update members",
"# -*- coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to",
"slz.validated_data system_id = data[\"system_id\"] template_id = data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS,",
"= GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def",
"self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"],",
"for one in data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes",
"# 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes",
"templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(group=group) return",
"operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request,",
"from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized",
"lookup_field = \"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz",
"*args, **kwargs) return response return wrapper return decorate class GroupQueryMixin:",
"old_condition), is_template=True ) return Response([c.dict() for c in conditions]) raise",
"Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field = \"id\"",
"tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args, **kwargs): slz",
"import NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS",
"如果当前角色是staff 并且 存在筛选的role_id if role.type == RoleType.STAFF.value and filter_role_id: #",
"List from django.shortcuts import get_object_or_404 from django.utils.translation import gettext as",
"OperateEnum from .filters import GroupFilter, GroupTemplateSystemFilter from .serializers import (",
"\"\"\" 创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username",
"ConditionTagBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"),",
"PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() serializer_class = GroupSLZ",
"Unless required by applicable law or agreed to in writing,",
"username) if not filter_role: return Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role,",
"user_id = request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"],",
"# ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict() for",
"t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t in data[\"templates\"]], ) return Response({},",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args, **kwargs):",
"GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self,",
"request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"]",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition",
"data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz",
"lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"],",
"express or implied. See the License for the specific language",
"request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members =",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data)",
"= GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data system_id = data[\"system_id\"] template_id",
"if policy.action_id == action_id: # 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id,",
"rest_framework.viewsets import GenericViewSet, mixins from backend.account.permissions import RolePermission, role_perm_class from",
"# 如果当前角色是staff 并且 存在筛选的role_id if role.type == RoleType.STAFF.value and filter_role_id:",
"tags=[\"group\"], ) def list(self, request, *args, **kwargs): slz = SystemQuerySLZ(data=request.query_params)",
"GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants import OperateEnum",
"data = serializer.validated_data group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset",
"from backend.common.error_codes import error_codes from backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers",
"\"id\" biz = GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"),",
"user %s\", group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) #",
"tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args, **kwargs): serializer",
"policy_operation_biz = PolicyOperationBiz() group_biz = GroupBiz() group_trans = GroupTrans() @swagger_auto_schema(",
"GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants import",
"return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission =",
"PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() lookup_field = \"id\" biz =",
"policy_biz = PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset = Group.objects.all() lookup_field",
"update(self, request, *args, **kwargs): group = self.get_object() serializer = GroupUpdateSLZ(group,",
"def retrieve(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id",
"= request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id)",
"self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data system_id =",
"mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value,",
"# 1. 查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject,",
"offset参数 queryset = Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend]",
"*args, **kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group",
"backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean, PolicyOperationBiz,",
"group, templates) # 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]}",
"self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\":",
"t[\"template_id\"]} for t in data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema(",
"from backend.biz.template import TemplateBiz from backend.common.error_codes import error_codes from backend.common.filters",
"# 去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field = \"id\" policy_query_biz",
"PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit import",
"= \"id\" # service group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"),",
"= { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset",
"return Response([p.dict() for p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK:",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"the specific language governing permissions and limitations under the License.",
"PolicyOperationBiz() group_biz = GroupBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"),",
"from .serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ,",
"[RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value,",
"class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value}",
"= view.get_object() readonly = group.readonly if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id,",
"pagination_class = None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() filterset_class",
"写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m in members]) return Response({}, status=status.HTTP_201_CREATED)",
"filter_role_id: # 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role:",
"or agreed to in writing, software distributed under the License",
"\"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all()",
"from backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template import TemplateBiz",
"GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\") def",
"reserved. Licensed under the MIT License (the \"License\"); you may",
"GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants",
"pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM)",
"Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {",
"= GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() action_id",
"raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword",
"@view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args, **kwargs): group = self.get_object()",
"request = self.request role = request.role username = request.user.username filter_role_id",
"coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to support the",
"return Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group()",
"= kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id))",
"self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition related_resource_type =",
"error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz",
"if not filter_role: return Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group()",
"Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def",
"**kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data =",
"audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider)",
"request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request,",
"for one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data)",
"RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template import TemplateBiz from backend.common.error_codes import",
"= GroupBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()},",
"group_ids = slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id)",
"return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label)",
"permission_classes = [RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None",
"data[\"name\"], group.id) group = self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) # 写入审计上下文",
"from pydantic.tools import parse_obj_as from rest_framework import serializers, status, views",
"self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add members %s by",
"is_template=True ) return Response([c.dict() for c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板:",
"data = serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) #",
"*args, **kwargs): group = self.get_object() data = self.biz.list_system_counter(group.id) return Response([one.dict()",
"# 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates)",
"def destroy(self, request, *args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group",
"= self.get_object() data = serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group,",
"去掉swagger中的limit offset参数 queryset = Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends =",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset)",
"用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\",",
"GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ,",
"audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz()",
"from rest_framework.viewsets import GenericViewSet, mixins from backend.account.permissions import RolePermission, role_perm_class",
"limitations under the License. \"\"\" import logging from functools import",
"%s expired_at by user %s\", group.id, data[\"members\"], request.user.username ) for",
"tags=[\"group\"], ) def list(self, request, *args, **kwargs): return super().list(request, *args,",
"A29 Limited, a Tencent company. All rights reserved. Licensed under",
"@swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def",
"= request.role username = request.user.username filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff",
"group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], )",
"# 添加成员 self.biz.add_members(group.id, members, expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for",
"responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs):",
"ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id,",
"condition_biz = ConditionTagBiz() template_biz = TemplateBiz() queryset = Group.objects.all() lookup_field",
"GroupBiz() group_check_biz = GroupCheckBiz() role_biz = RoleBiz() group_trans = GroupTrans()",
"SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword) return",
"operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def list(self, request,",
"self.biz.add_members(group.id, members, expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m in",
"def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) @swagger_auto_schema(",
"super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def",
"= data[\"system_id\"] template_id = data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for",
"request.role username = request.user.username filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff 并且",
"# 校验权限 checker = RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id),",
"request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id,",
"= GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")},",
"data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if data[\"templates\"]:",
"slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"]",
"self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members)",
"( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider,",
"GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data permission_logger.info( \"group",
"group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition",
"import Group from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models",
"serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() action_id = data[\"action_id\"]",
"GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\"",
"= GroupFilter lookup_field = \"id\" group_biz = GroupBiz() group_check_biz =",
"group_biz = GroupBiz() group_check_biz = GroupCheckBiz() role_biz = RoleBiz() group_trans",
"get_object_or_404 from django.utils.translation import gettext as _ from drf_yasg.utils import",
"members = list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members))",
"action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, }",
"def update(self, request, *args, **kwargs): group = self.get_object() slz =",
"if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz =",
"{obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission] action_permission =",
"= func(view, request, *args, **kwargs) return response return wrapper return",
"操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition =",
") permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func)",
"= list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group",
"def create(self, request, *args, **kwargs): \"\"\" 创建用户组 \"\"\" serializer =",
"GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class",
"one in group_members]}) pagination = LimitOffsetPagination() limit = pagination.get_limit(request) offset",
"slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({})",
"self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s policy",
"class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"list\":",
"data = serializer.validated_data permission_logger.info( \"group %s delete members %s by",
"checker = RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if",
"GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data #",
"from rest_framework import serializers, status, views from rest_framework.pagination import LimitOffsetPagination",
"class GroupSystemViewSet(GenericViewSet): pagination_class = None # 去掉swagger中的limit offset参数 queryset =",
") old_condition = related_resource_type.condition if related_resource_type else [] # 对比用户组已有的条件与用户提交的条件",
"**kwargs): \"\"\" 创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id =",
"group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group,",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"data = self.biz.list_system_counter(group.id) return Response([one.dict() for one in data]) class",
"return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset =",
"= None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field =",
"in writing, software distributed under the License is distributed on",
"import OperateEnum from .filters import GroupFilter, GroupTemplateSystemFilter from .serializers import",
"required by applicable law or agreed to in writing, software",
"= self.request return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self, request,",
"group = self.get_object() data = serializer.validated_data members_data = data[\"members\"] expired_at",
"= get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider,",
"TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def list(self,",
"GroupUpdateAuditProvider, ) from .constants import OperateEnum from .filters import GroupFilter,",
"用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group = self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id)",
"policies) return Response([p.dict() for p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"),",
"= Group.objects.all() lookup_field = \"id\" biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\",",
"request.user.username filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id if role.type",
"distributed under the License is distributed on an \"AS IS\"",
"status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label)",
"Response({\"results\": [one.dict() for one in group_members]}) pagination = LimitOffsetPagination() limit",
"# 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t",
"group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies =",
"CONDITIONS OF ANY KIND, either express or implied. See the",
") @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args, **kwargs): group =",
"GroupPermissionMixin: def check_object_permissions(self, request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type}",
"import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ,",
"related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition = related_resource_type.condition",
"\"id\" biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"],",
"Group.objects.all() serializer_class = GroupSLZ filterset_class = GroupFilter lookup_field = \"id\"",
"= slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin,",
"serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data members_data = data[\"members\"]",
"**kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"]",
"under the License. \"\"\" import logging from functools import wraps",
"= [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field = \"id\" # service",
"in members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data",
"= self.get_object() serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username",
"@check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"\"id\" # service group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK:",
"destroy(self, request, *args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group =",
"template_id=template_id, policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class = None #",
"**kwargs): group = self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return Response({})",
"tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args, **kwargs): group",
"for m in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean],",
"None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field = \"id\"",
"PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset = Group.objects.all() lookup_field = \"id\"",
"replace=True ) response = func(view, request, *args, **kwargs) return response",
"= SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword)",
"audit_context_setter, view_audit_decorator from backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy",
"= GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data",
"**kwargs): return super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")},",
"request = self.request return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self,",
"backend.account.permissions import RolePermission, role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from",
"PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz = GroupBiz() group_trans = GroupTrans()",
"group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id, action_id)) class",
"= Group.objects.all() lookup_field = \"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz =",
"%s delete members %s by user %s\", group.id, data[\"members\"], request.user.username",
"error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response = func(view, request, *args,",
"len(members)) permission_logger.info(\"group %s add members %s by user %s\", group.id,",
"self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id,",
"return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz() template_biz =",
"def create(self, request, *args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data",
"= slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"related_resource_type.condition if related_resource_type else [] # 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag(",
"making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a",
"GroupTemplateSystemFilter from .serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ,",
"= GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider)",
"去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field = \"id\" biz =",
"= \"id\" group_biz = GroupBiz() group_check_biz = GroupCheckBiz() role_biz =",
"Limited, a Tencent company. All rights reserved. Licensed under the",
"Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider)",
"permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field = \"id\" #",
"parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin,",
"GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger =",
"self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2. 对比合并差异",
"GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ,",
"data = slz.validated_data system_id = data[\"system_id\"] template_id = data[\"template_id\"] policies",
"= self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict() for p in updated_policies])",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args,",
"Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request = self.request role =",
"= self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin,",
"License. \"\"\" import logging from functools import wraps from typing",
"obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can not access",
"\"results\": [one.dict() for one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK:",
"= LimitOffsetPagination() limit = pagination.get_limit(request) offset = pagination.get_offset(request) count, group_members",
"access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission]",
"= self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(group=group) return Response({\"id\":",
"@check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id, members,",
"may not use this file except in compliance with the",
"data[\"name\"], data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\",",
"import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import tasks # noqa from",
"data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK:",
"# 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes",
"= [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\":",
"the License. \"\"\" import logging from functools import wraps from",
"You may obtain a copy of the License at http://opensource.org/licenses/MIT",
"from backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ from backend.common.time",
"def create(self, request, *args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group",
"expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m in members]) return",
"import PermissionCodeEnum, RoleType, SubjectType from backend.service.models import Subject from backend.trans.group",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args,",
") policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject,",
"request, *args, **kwargs): \"\"\" 创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): return super().list(request,",
"= ConditionTagBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\",",
"PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None #",
"ConditionTagBean, ConditionTagBiz from backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template",
"import wraps from typing import List from django.shortcuts import get_object_or_404",
"policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition = related_resource_type.condition if related_resource_type",
"*args, **kwargs): return super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK:",
"operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def list(self, request, *args,",
"tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args, **kwargs): slz =",
"*args, **kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids =",
"backend.common.serializers import SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS from backend.service.constants import",
"message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response = func(view, request, *args, **kwargs)",
"tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args, **kwargs): serializer",
"2017-2021 THL A29 Limited, a Tencent company. All rights reserved.",
"response return wrapper return decorate class GroupQueryMixin: def get_queryset(self): request",
"user %s\", group.id, members, request.user.username) # 添加成员 self.biz.add_members(group.id, members, expired_at)",
"request, *args, **kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data",
") def create(self, request, *args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter, view_audit_decorator from backend.biz.group import GroupBiz,",
"request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id)",
"@view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args, **kwargs): group = self.get_object()",
"= PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\",",
"agreed to in writing, software distributed under the License is",
"tags=[\"group\"], ) def create(self, request, *args, **kwargs): serializer = ConditionCompareSLZ(data=request.data)",
"self.request role = request.role username = request.user.username filter_role_id = request.query_params.get(\"role_id\")",
"= group.readonly if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True )",
"queryset = Group.objects.all() lookup_field = \"id\" # service group_biz =",
"TencentBlueKing is pleased to support the open source community by",
"= get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\")",
"return Response({\"results\": [one.dict() for one in group_members]}) pagination = LimitOffsetPagination()",
"authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id == action_id:",
"group = self.get_object() data = self.biz.list_system_counter(group.id) return Response([one.dict() for one",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
") @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args, **kwargs): serializer =",
"= get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id,",
"GenericViewSet): condition_biz = ConditionTagBiz() template_biz = TemplateBiz() queryset = Group.objects.all()",
"conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return Response([c.dict()",
"django.shortcuts import get_object_or_404 from django.utils.translation import gettext as _ from",
"action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies) # 写入审计上下文",
"License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed",
"= GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider)",
"对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return",
"source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL",
"**kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data =",
"def destroy(self, request, *args, **kwargs): group = self.get_object() self.group_biz.delete(group.id) #",
"system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"user_id, members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates =",
"filterset_class = GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field = \"id\" template_biz",
"by user %s\", group.id, members, request.user.username) # 添加成员 self.biz.add_members(group.id, members,",
"= self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data)",
"ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() subject =",
"status, views from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response",
"= GroupBiz() group_check_biz = GroupCheckBiz() role_biz = RoleBiz() group_trans =",
"from backend.trans.group import GroupTrans from .audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider,",
"query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self, request, *args, **kwargs):",
"rights reserved. Licensed under the MIT License (the \"License\"); you",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args, **kwargs): slz",
"= self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict() for one in group_members]})",
"compliance with the License. You may obtain a copy of",
"permission_logger.info( \"group %s update members %s expired_at by user %s\",",
"for m in members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"),",
"return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request = self.request role",
"Group.objects.all() lookup_field = \"id\" biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK:",
"role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class",
"def list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject",
"( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ,",
"[role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field = \"id\" # service group_biz",
"[PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id,",
") # 2. 对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean],",
"backend.trans.group import GroupTrans from .audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider,",
"= \"id\" biz = GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\",",
"query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def list(self, request, *args,",
".audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider,",
"PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None # 去掉swagger中的limit offset参数 queryset = Group.objects.all()",
"GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value,",
"# 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies)",
"THL A29 Limited, a Tencent company. All rights reserved. Licensed",
"tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): group = get_object_or_404(self.queryset,",
"= serializer.validated_data permission_logger.info( \"group %s update members %s expired_at by",
"self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict() for one in group_members]}) pagination",
"responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): group",
"data = serializer.validated_data members_data = data[\"members\"] expired_at = data[\"expired_at\"] #",
"*args, **kwargs): group = self.get_object() serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True)",
"= self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"] ) #",
"Response([c.dict() for c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {}",
"从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template",
"list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject =",
"company. All rights reserved. Licensed under the MIT License (the",
"request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request, *args,",
"from drf_yasg.utils import swagger_auto_schema from pydantic.tools import parse_obj_as from rest_framework",
"number_of_new_group) # 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group",
"= self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role: return Group.objects.none() # 返回角色的用户组列表",
"get_queryset(self): request = self.request return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def",
"= parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"],",
"from .constants import OperateEnum from .filters import GroupFilter, GroupTemplateSystemFilter from",
"%s\", group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文",
"operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self,",
"= slz.validated_data system_id = data[\"system_id\"] template_id = data[\"template_id\"] policies =",
"\"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def",
"@view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request, *args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data)",
"responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs):",
"= \"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz =",
"from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import tasks #",
"parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return Response([c.dict() for c in conditions])",
"user %s\", group.id, data[\"members\"], request.user.username ) for m in data[\"members\"]:",
"if related_resource_type else [] # 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition,",
"data[\"system_id\"] template_id = data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action",
"policies = self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject,",
"parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return Response([c.dict() for c in conditions])",
"GroupSLZ filterset_class = GroupFilter lookup_field = \"id\" group_biz = GroupBiz()",
"*args, **kwargs): \"\"\" 创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id",
"= request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id if role.type == RoleType.STAFF.value",
"= [RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None #",
"= TemplateBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\",",
"def list(self, request, *args, **kwargs): group = self.get_object() data =",
"Tencent company. All rights reserved. Licensed under the MIT License",
"**kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data =",
"Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all()",
"slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group = self.get_object()",
"limit, offset) return Response({\"count\": count, \"results\": [one.dict() for one in",
"\"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"),",
"request, *args, **kwargs): group = self.get_object() data = self.biz.list_system_counter(group.id) return",
"PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter, view_audit_decorator",
"data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\",",
"request, *args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object()",
"= RoleBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")},",
"filter_backends = [NoCheckModelFilterBackend] lookup_field = \"id\" template_biz = TemplateBiz() @swagger_auto_schema(",
"import tasks # noqa from backend.apps.group.models import Group from backend.apps.policy.serializers",
"def update(self, request, *args, **kwargs): group = self.get_object() serializer =",
"data = serializer.validated_data group = self.get_object() action_id = data[\"action_id\"] resource_group_id",
"self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes",
"GenericViewSet): permission_classes = [RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class =",
"# 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet):",
"wrapper(view, request, *args, **kwargs): group = view.get_object() readonly = group.readonly",
"role can not access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):",
".constants import OperateEnum from .filters import GroupFilter, GroupTemplateSystemFilter from .serializers",
"group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"] )",
"condition_biz = ConditionTagBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema(",
"GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset = Group.objects.all()",
"self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\": count, \"results\": [one.dict() for one",
"self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id},",
"request, *args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object()",
"if role.type == RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role =",
"is pleased to support the open source community by making",
"data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"])",
"用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1",
"many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): group =",
"policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class = None # 去掉swagger中的limit",
"create(self, request, *args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group =",
"view_audit_decorator from backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import",
"@swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def list(self, request,",
"request, *args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object()",
"from typing import List from django.shortcuts import get_object_or_404 from django.utils.translation",
"RolePermission, role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import",
"operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self,",
"class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz =",
"under the MIT License (the \"License\"); you may not use",
"serializers, status, views from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import",
"m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"])",
"GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label)",
"PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from backend.biz.role import RoleBiz,",
"# 查询对应的操作 if policy.action_id == action_id: # 操作操作中对应于资源类型的操作 related_resource_type =",
"PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() serializer_class = GroupSLZ filterset_class =",
"= [RolePermission] action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\":",
"readonly = group.readonly if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True",
"GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\":",
") @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args, **kwargs): serializer =",
"GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag",
"GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ,",
"= \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], )",
"# 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True )",
"%s by user %s\", group.id, members, request.user.username) # 添加成员 self.biz.add_members(group.id,",
"slz.validated_data[\"ids\"] group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject",
"= data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id",
"# 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members)",
"*args, **kwargs): group = self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in",
"@view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args, **kwargs): group = self.get_object()",
"self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class",
"PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() serializer_class",
"def create(self, request, *args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group",
"count, group_members = self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\": count, \"results\":",
") for m in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id,",
"mixins from backend.account.permissions import RolePermission, role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ,",
"backend.common.error_codes import error_codes from backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers import",
"%s\", group.id, data[\"members\"], request.user.username ) for m in data[\"members\"]: m[\"policy_expired_at\"]",
"写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class",
"request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request,",
"swagger_auto_schema from pydantic.tools import parse_obj_as from rest_framework import serializers, status,",
"# 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m in members]) return Response({},",
"in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) )",
") @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args, **kwargs): slz =",
"data[\"description\"], user_id, members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates",
"= self.request role = request.role username = request.user.username filter_role_id =",
"a copy of the License at http://opensource.org/licenses/MIT Unless required by",
"@view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args, **kwargs): slz = PolicyDeleteSLZ(data=request.data)",
"= self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) #",
"backend.service.constants import PermissionCodeEnum, RoleType, SubjectType from backend.service.models import Subject from",
"return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider)",
"serializer.validated_data group = self.get_object() action_id = data[\"action_id\"] resource_group_id = data[\"resource_group_id\"]",
"parse_obj_as from rest_framework import serializers, status, views from rest_framework.pagination import",
"rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.viewsets import",
"def get_queryset(self): request = self.request role = request.role username =",
"@swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self, request, *args,",
"slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict() for one",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): group",
"update(self, request, *args, **kwargs): group = self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data)",
"operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self, request,",
"data = serializer.validated_data permission_logger.info( \"group %s update members %s expired_at",
"governing permissions and limitations under the License. \"\"\" import logging",
"self.get_object() data = serializer.validated_data members_data = data[\"members\"] expired_at = data[\"expired_at\"]",
"pagination = LimitOffsetPagination() limit = pagination.get_limit(request) offset = pagination.get_offset(request) count,",
"under the License is distributed on an \"AS IS\" BASIS,",
"# 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group = 1 #",
"from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from backend.biz.role import RoleBiz, RoleListQuery,",
"request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self, request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj):",
"tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args, **kwargs): serializer",
"subject) # ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict()",
"open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021",
"Group.objects.all() lookup_field = \"id\" biz = GroupBiz() group_check_biz = GroupCheckBiz()",
"Licensed under the MIT License (the \"License\"); you may not",
"if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in authorized_template.data[\"actions\"]:",
"this file except in compliance with the License. You may",
"group = view.get_object() readonly = group.readonly if readonly: raise error_codes.FORBIDDEN.format(",
"serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data templates = self.group_trans.from_group_grant_data(data[\"templates\"])",
"template_biz = TemplateBiz() queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema(",
"检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role: return Group.objects.none()",
"check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def wrapper(view, request, *args, **kwargs):",
"= self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\":",
"%s update members %s expired_at by user %s\", group.id, data[\"members\"],",
"updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict() for p in",
"policy_query_biz = PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz = GroupBiz() group_trans",
"action_id = data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition",
"GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider,",
"ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import tasks # noqa from backend.apps.group.models",
"\"group %s update members %s expired_at by user %s\", group.id,",
"{\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None # 去掉swagger中的limit offset参数 queryset =",
"file except in compliance with the License. You may obtain",
"in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id ==",
"self.request return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self, request, obj):",
"@swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self, request,",
"templates) # 写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self):",
"members, request.user.username) # 添加成员 self.biz.add_members(group.id, members, expired_at) # 写入审计上下文 audit_context_setter(group=group,",
"# 去掉swagger中的limit offset参数 queryset = Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id if role.type ==",
"} queryset = Group.objects.all() serializer_class = GroupSLZ filterset_class = GroupFilter",
"GenericViewSet, mixins from backend.account.permissions import RolePermission, role_perm_class from backend.apps.application.serializers import",
"create(self, request, *args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group =",
"data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作,",
"# 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group = self.group_biz.update(group, data[\"name\"], data[\"description\"],",
"serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group = 1",
"in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider)",
"request.role.id, data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if",
"m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文",
"request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value,",
"# 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition",
"class GroupQueryMixin: def get_queryset(self): request = self.request return RoleListQuery(request.role, request.user).query_group()",
"check_object_permissions(self, request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can",
"group = self.get_object() serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id =",
"conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin,",
"@check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() action_id =",
"pk=kwargs[\"id\"]) # 校验权限 checker = RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise",
"GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation):",
"**kwargs): group = view.get_object() readonly = group.readonly if readonly: raise",
"members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"from django.utils.translation import gettext as _ from drf_yasg.utils import swagger_auto_schema",
"views from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from",
"audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission",
"int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission",
"return Response([c.dict() for c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作:",
"group.id, system_id, template_id, policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies)",
"= pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\":",
"= serializer.validated_data group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) #",
"request.user.username ) for m in data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at(",
"[RolePermission] action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None # 去掉swagger中的limit",
"policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"rest_framework.response import Response from rest_framework.viewsets import GenericViewSet, mixins from backend.account.permissions",
"资源类型的条件 template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template =",
"self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add members %s by user %s\",",
"%s add members %s by user %s\", group.id, members, request.user.username)",
"policy deleted by user %s\", subject.type, subject.id, request.user.username ) policy_list",
"data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], )",
"return super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], )",
"= GroupDeleteMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data permission_logger.info(",
"接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role,",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset,",
"= [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class",
"request, *args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data",
"{ \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset =",
"new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"]",
"self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], )",
"= pagination.get_limit(request) offset = pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id, limit,",
"%s\", group.id, members, request.user.username) # 添加成员 self.biz.add_members(group.id, members, expired_at) #",
"Response([p.dict() for p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"system_id = slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group = self.get_object() subject",
"{} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz",
"用户组数量在角色内是否超限 number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围",
"*args, **kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids",
"= [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id,",
"use this file except in compliance with the License. You",
"GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ,",
"id=str(group.id)) # 1. 查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions(",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action",
"= RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"):",
"GroupQueryMixin: def get_queryset(self): request = self.request return RoleListQuery(request.role, request.user).query_group() class",
"service group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"lookup_field = \"id\" group_biz = GroupBiz() group_check_biz = GroupCheckBiz() role_biz",
"filter_role: return Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role,",
"PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) #",
"action_id: # 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] )",
"self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) # 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema(",
"data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data # 用户组名称在角色内唯一",
"= data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) #",
"1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject],",
"group = self.get_object() data = serializer.validated_data permission_logger.info( \"group %s update",
"**kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group =",
"import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from",
"serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data",
"def wrapper(view, request, *args, **kwargs): group = view.get_object() readonly =",
"backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized from",
"create(self, request, *args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group =",
"ConditionTagBiz() template_biz = TemplateBiz() queryset = Group.objects.all() lookup_field = \"id\"",
"the MIT License (the \"License\"); you may not use this",
"# 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add members",
"(the \"License\"); you may not use this file except in",
"*args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self,",
"operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self,",
"= PolicyOperationBiz() group_biz = GroupBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\",",
"self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED)",
"= self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition related_resource_type",
"Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self,",
"= slz.validated_data[\"ids\"] group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info(",
"obtain a copy of the License at http://opensource.org/licenses/MIT Unless required",
"backend.biz.template import TemplateBiz from backend.common.error_codes import error_codes from backend.common.filters import",
"policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return Response({}) class",
"data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean],",
"= 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members =",
"or implied. See the License for the specific language governing",
"KIND, either express or implied. See the License for the",
"queryset = Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field",
"request, *args, **kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids",
"serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object()",
"存在筛选的role_id if role.type == RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role",
"ids = slz.validated_data[\"ids\"] group = self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset",
"return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission =",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin,",
"members) group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"]",
"pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id, limit, offset) return Response({\"count\": count,",
"authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in authorized_template.data[\"actions\"]: policy =",
"members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission",
"Response({\"count\": count, \"results\": [one.dict() for one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\",",
"class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz() template_biz = TemplateBiz() queryset",
"self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group = self.group_biz.update(group, data[\"name\"], data[\"description\"], user_id) #",
"django.utils.translation import gettext as _ from drf_yasg.utils import swagger_auto_schema from",
"GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): group =",
"the License for the specific language governing permissions and limitations",
"members %s by user %s\", group.id, members, request.user.username) # 添加成员",
"permission_logger.info(\"group %s add members %s by user %s\", group.id, members,",
"offset = pagination.get_offset(request) count, group_members = self.biz.list_paging_group_member(group.id, limit, offset) return",
"implied. See the License for the specific language governing permissions",
") self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({})",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"import Subject from backend.trans.group import GroupTrans from .audit import (",
"Subject from backend.trans.group import GroupTrans from .audit import ( GroupCreateAuditProvider,",
"t in data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ,",
"backend.common.time import PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum, RoleType, SubjectType from",
"GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data system_id = data[\"system_id\"] template_id =",
"request, *args, **kwargs) return response return wrapper return decorate class",
"*args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data",
"group.id, members, request.user.username) # 添加成员 self.biz.add_members(group.id, members, expired_at) # 写入审计上下文",
"GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): return",
"import serializers, status, views from rest_framework.pagination import LimitOffsetPagination from rest_framework.response",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args, **kwargs):",
"serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data permission_logger.info( \"group %s",
"GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from",
"group.readonly if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response",
"= self.get_object() subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s",
"GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ,",
"members=[m.dict() for m in members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\",",
"related_resource_type = data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"],",
"= policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"], related_resource_type[\"type\"] ) old_condition = related_resource_type.condition if",
"= Group.objects.all() serializer_class = GroupSLZ filterset_class = GroupFilter lookup_field =",
"audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()},",
"的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz =",
"of the License at http://opensource.org/licenses/MIT Unless required by applicable law",
"audit_context_setter(group=group, members=[m.dict() for m in members]) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema(",
"GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label)",
"对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, )",
"writing, software distributed under the License is distributed on an",
"group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], )",
"class GroupPermissionMixin: def check_object_permissions(self, request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request,",
"biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)}, tags=[\"group\"], )",
"list(self, request, *args, **kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id =",
"operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self,",
"in compliance with the License. You may obtain a copy",
"\"\"\" 用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema(",
"in data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)]",
"backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter, view_audit_decorator from backend.biz.group",
"= { \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset",
"创建用户组 \"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data",
"role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"group.id, data[\"members\"], request.user.username ) for m in data[\"members\"]: m[\"policy_expired_at\"] =",
"permission_classes = [role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK:",
"request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request,",
"%s\", subject.type, subject.id, request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids)",
"data[\"members\"]: m[\"policy_expired_at\"] = m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) #",
"backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import tasks # noqa",
"GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, )",
"either express or implied. See the License for the specific",
"**kwargs): group = self.get_object() serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id",
"\"License\"); you may not use this file except in compliance",
"return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"[role_perm_class(PermissionCodeEnum.TRANSFER_GROUP.value)] role_biz = RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"@swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self,",
"\"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() serializer_class = GroupSLZ filterset_class",
"request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request,",
"去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field = \"id\" policy_query_biz =",
"data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin,",
"queryset = Group.objects.all() lookup_field = \"id\" biz = GroupBiz() @swagger_auto_schema(",
"= [NoCheckModelFilterBackend] lookup_field = \"id\" template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\",",
"pydantic.tools import parse_obj_as from rest_framework import serializers, status, views from",
"*args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject",
"添加成员 self.biz.add_members(group.id, members, expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict() for m",
"**kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids =",
"role.type == RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id,",
"= self.get_object() data = serializer.validated_data members_data = data[\"members\"] expired_at =",
"RoleListQuery, RoleObjectRelationChecker from backend.biz.template import TemplateBiz from backend.common.error_codes import error_codes",
"request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self, request,",
"2. 对比合并差异 conditions = self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True,",
") def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs)",
"PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum, RoleType, SubjectType from backend.service.models import",
"request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限",
"GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data members_data =",
"system_id=system_id, template_id=template_id, policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class = None",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies =",
"return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"],",
"subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文 audit_context_setter(group=group,",
"import PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum, RoleType, SubjectType from backend.service.models",
"action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, }",
"readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response = func(view,",
"= GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data templates",
"not access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes =",
"# 去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field = \"id\" biz",
"c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {} 没有操作: {} 的权限\").format(template_id, action_id))",
"import GroupTrans from .audit import ( GroupCreateAuditProvider, GroupDeleteAuditProvider, GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider,",
"user %s\", subject.type, subject.id, request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject,",
"LimitOffsetPagination() limit = pagination.get_limit(request) offset = pagination.get_offset(request) count, group_members =",
"= Group.objects.all() filterset_class = GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field =",
"Group from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models import",
") def retrieve(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"])",
"queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK:",
"kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return",
"= self.condition_biz.compare_and_tag( parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return Response([c.dict()",
"role = request.role username = request.user.username filter_role_id = request.query_params.get(\"role_id\") #",
"request, *args, **kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"]",
"删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return",
"tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args, **kwargs): group",
"from backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter, view_audit_decorator from",
"PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id == action_id: # 操作操作中对应于资源类型的操作 related_resource_type",
"for t in data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\",",
"写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes =",
"pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject) #",
"= GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def",
"MIT License (the \"License\"); you may not use this file",
"data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role,",
"operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def list(self, request, *args,",
") def list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"])",
"from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet, mixins from",
"**kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset",
"GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz = ConditionTagBiz() queryset =",
"not filter_role: return Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return",
"GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): return super().retrieve(request,",
"@view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args, **kwargs): serializer = GroupDeleteMemberSLZ(data=request.data)",
"community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29",
"@view_audit_decorator(GroupTransferAuditProvider) def post(self, request, *args, **kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\":",
"create(self, request, *args, **kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data =",
"related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return Response([c.dict() for c in",
"= request.user.username filter_role_id = request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id if",
"PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from backend.biz.role import",
"\"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def wrapper(view, request, *args, **kwargs): group",
") return Response([c.dict() for c in conditions]) raise error_codes.VALIDATE_ERROR.format(_(\"模板: {}",
"\"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all()",
"RoleType, SubjectType from backend.service.models import Subject from backend.trans.group import GroupTrans",
"= self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies = self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies)",
"= self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return Response([c.dict() for",
"serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id,",
"self.get_object() serializer = GroupUpdateSLZ(group, data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data",
") @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args, **kwargs): serializer =",
"tags=[\"group\"], ) def list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset,",
"= {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None # 去掉swagger中的limit offset参数 queryset",
"# 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\",",
"responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTemplateCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_CREATE.label) def create(self, request, *args,",
"self.get_object() data = self.biz.list_system_counter(group.id) return Response([one.dict() for one in data])",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return",
"from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.viewsets",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args,",
"data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id,",
"parse_obj_as(List[Subject], data[\"members\"]) self.group_check_biz.check_role_subject_scope(request.role, members) group = self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"],",
"*args, **kwargs): group = self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data",
"status=status.HTTP_201_CREATED) def get_queryset(self): request = self.request role = request.role username",
"= serializer.validated_data group = self.get_object() action_id = data[\"action_id\"] resource_group_id =",
") def create(self, request, *args, **kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) # 删除权限 self.policy_operation_biz.delete_by_ids(system_id, subject, ids)",
"{} 没有操作: {} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz =",
"permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value,",
"使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) #",
"retrieve(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id =",
"NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS from",
"self.group_biz.create_and_add_members( request.role.id, data[\"name\"], data[\"description\"], user_id, members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权",
"@swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def",
"= ConditionTagBiz() template_biz = TemplateBiz() queryset = Group.objects.all() lookup_field =",
"return Response([one.dict() for one in data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出",
"self.get_object() data = serializer.validated_data permission_logger.info( \"group %s update members %s",
"audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t in data[\"templates\"]],",
"return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], )",
"**kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label)",
"request, *args, **kwargs): group = self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True)",
"from backend.service.models import Subject from backend.trans.group import GroupTrans from .audit",
"= slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group = self.get_object() subject =",
"operation), replace=True ) response = func(view, request, *args, **kwargs) return",
"responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request, *args, **kwargs):",
"request.query_params.get(\"role_id\") # 如果当前角色是staff 并且 存在筛选的role_id if role.type == RoleType.STAFF.value and",
"audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return Response({}) class GroupSystemViewSet(GenericViewSet): pagination_class =",
"RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)},",
"slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies",
"= serializer.validated_data members_data = data[\"members\"] expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重",
"def create(self, request, *args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group",
"tasks # noqa from backend.apps.group.models import Group from backend.apps.policy.serializers import",
"没有操作: {} 的权限\").format(template_id, action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz()",
"GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"],",
"*args, **kwargs): group = view.get_object() readonly = group.readonly if readonly:",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args,",
"specific language governing permissions and limitations under the License. \"\"\"",
"serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data",
"group, templates) # 写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def",
"backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz",
"applicable law or agreed to in writing, software distributed under",
"operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK: MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self, request, *args,",
"GroupBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"],",
"for p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"],",
"backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker",
"@swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self,",
"PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK:",
"post(self, request, *args, **kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True)",
"data[\"members\"] expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data)))",
"one in data]) class GroupTransferView(views.APIView): \"\"\" 用户组转出 \"\"\" permission_classes =",
"by user %s\", group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject], data[\"members\"]))",
"template_id = data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in",
"@swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def post(self,",
"create(self, request, *args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data) serializer.is_valid(raise_exception=True) data =",
"decorate(func): @wraps(func) def wrapper(view, request, *args, **kwargs): group = view.get_object()",
"GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ,",
"tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args, **kwargs): group",
"GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\":",
"GroupSystemViewSet(GenericViewSet): pagination_class = None # 去掉swagger中的limit offset参数 queryset = Group.objects.all()",
"PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None # 去掉swagger中的limit offset参数 queryset =",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition related_resource_type = data[\"related_resource_type\"] old_condition =",
"may obtain a copy of the License at http://opensource.org/licenses/MIT Unless",
") @view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args, **kwargs): \"\"\" 创建用户组 \"\"\"",
"**kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group =",
"for one in group_members]}) pagination = LimitOffsetPagination() limit = pagination.get_limit(request)",
"operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self,",
"system_id = data[\"system_id\"] template_id = data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action)",
"OF ANY KIND, either express or implied. See the License",
"self.policy_operation_biz.update_due_to_renamed_resource(system_id, subject, policies) return Response([p.dict() for p in updated_policies]) @swagger_auto_schema(",
"import GroupFilter, GroupTemplateSystemFilter from .serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ,",
"lookup_field = \"id\" biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\",",
"self.get_object() action_id = data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"]",
"PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): slz",
"TemplateBiz from backend.common.error_codes import error_codes from backend.common.filters import NoCheckModelFilterBackend from",
"GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args, **kwargs): \"\"\"",
"the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C)",
"request, *args, **kwargs): group = view.get_object() readonly = group.readonly if",
"support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright",
"audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request = self.request",
"MemberSLZ(label=\"成员\")}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): group =",
"import GenericViewSet, mixins from backend.account.permissions import RolePermission, role_perm_class from backend.apps.application.serializers",
"SystemQuerySLZ from backend.common.time import PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum, RoleType,",
"group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"用户组添加权限\", request_body=GroupAuthorizationSLZ(label=\"授权信息\"), responses={status.HTTP_201_CREATED: serializers.Serializer()}, tags=[\"group\"], )",
"wrapper return decorate class GroupQueryMixin: def get_queryset(self): request = self.request",
"operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs):",
"for action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies) #",
"many=True).data) @swagger_auto_schema( operation_description=\"用户组权限模板授权信息\", responses={status.HTTP_200_OK: GroupTemplateDetailSchemaSLZ(label=\"授权信息\")}, tags=[\"group\"], ) def retrieve(self, request,",
") @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args, **kwargs): group =",
"subject, policies) return Response([p.dict() for p in updated_policies]) @swagger_auto_schema( operation_description=\"用户组删除自定义权限\",",
"def list(self, request, *args, **kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id",
"data[\"members\"])) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet):",
"= self.get_object() data = serializer.validated_data permission_logger.info( \"group %s delete members",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) policies = self.policy_query_biz.list_by_subject(system_id, subject) # ResourceNameAutoUpdate updated_policies",
"= data[\"related_resource_type\"] old_condition = self.policy_biz.get_policy_resource_type_conditions( subject, data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"],",
"PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean, ConditionTagBiz from backend.biz.role",
"related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value,",
"self.biz.list_system_counter(group.id) return Response([one.dict() for one in data]) class GroupTransferView(views.APIView): \"\"\"",
"number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def destroy(self, request, *args, **kwargs):",
"permissions and limitations under the License. \"\"\" import logging from",
"serializer.validated_data members_data = data[\"members\"] expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members",
"Group.objects.all() lookup_field = \"id\" # service group_biz = GroupBiz() @swagger_auto_schema(",
"slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet):",
"PolicySLZ, PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit import audit_context_setter,",
"pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset =",
"logging from functools import wraps from typing import List from",
"request, *args, **kwargs): group = self.get_object() serializer = GroupUpdateSLZ(group, data=request.data)",
"rest_framework import serializers, status, views from rest_framework.pagination import LimitOffsetPagination from",
"and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if not",
"request, *args, **kwargs): group = self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group)",
"policy.action_id == action_id: # 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type( resource_group_id, related_resource_type[\"system_id\"],",
"backend.audit.audit import audit_context_setter, view_audit_decorator from backend.biz.group import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean",
"permission_logger.info( \"group %s delete members %s by user %s\", group.id,",
"responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args, **kwargs):",
"# 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role: return",
"operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self, request,",
"else [] # 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition),",
"role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group import tasks",
"lookup_field = \"id\" template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\",",
"group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label)",
"= parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"] subject",
"import GroupBiz, GroupCheckBiz, GroupMemberExpiredAtBean from backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz",
"return wrapper return decorate class GroupQueryMixin: def get_queryset(self): request =",
"= data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition =",
"= request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) #",
"filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role: return Group.objects.none() #",
"subject, ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema(",
"available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company.",
"[NoCheckModelFilterBackend] lookup_field = \"id\" template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK:",
"system_id, template_id, policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return",
"slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id,",
"copy of the License at http://opensource.org/licenses/MIT Unless required by applicable",
"成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id,",
"id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for action in authorized_template.data[\"actions\"]: policy",
"\"\"\" import logging from functools import wraps from typing import",
"filterset_class = GroupFilter lookup_field = \"id\" group_biz = GroupBiz() group_check_biz",
"parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]), parse_obj_as(List[ConditionTagBean], old_condition), is_template=True, ) return Response([c.dict() for c",
"@swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self,",
"import RolePermission, role_perm_class from backend.apps.application.serializers import ConditionCompareSLZ, ConditionTagSLZ from backend.apps.group",
"noqa from backend.apps.group.models import Group from backend.apps.policy.serializers import PolicyDeleteSLZ, PolicySLZ,",
"= get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker = RoleObjectRelationChecker(request.role) if not",
"= m.pop(\"expired_at\") self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group,",
"a Tencent company. All rights reserved. Licensed under the MIT",
"def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) @swagger_auto_schema(",
"import error_codes from backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ",
"self.role_biz.get_role_scope_include_user(filter_role_id, username) if not filter_role: return Group.objects.none() # 返回角色的用户组列表 return",
"PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() lookup_field = \"id\"",
"group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request = self.request role = request.role",
"tags=[\"group\"], ) @view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args, **kwargs): \"\"\" 创建用户组",
"members %s expired_at by user %s\", group.id, data[\"members\"], request.user.username )",
"Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label)",
"action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, }",
"GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ, GroupPolicyUpdateSLZ, GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ,",
"group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker = RoleObjectRelationChecker(request.role) if",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args, **kwargs):",
"import swagger_auto_schema from pydantic.tools import parse_obj_as from rest_framework import serializers,",
"# 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"),",
") return Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)},",
"offset) return Response({\"count\": count, \"results\": [one.dict() for one in group_members]})",
"queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset = self.filter_queryset(queryset) return Response(GroupTemplateSLZ(queryset, many=True).data) @swagger_auto_schema(",
"not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can not access group {obj.id}\")",
"if readonly: raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response =",
"message=f\"{request.role.type} role can not access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin,",
"self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz",
"**kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data =",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args,",
"group = self.get_object() action_id = data[\"action_id\"] resource_group_id = data[\"resource_group_id\"] related_resource_type",
"return super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"],",
"import LimitOffsetPagination from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet,",
"members, data[\"expired_at\"] ) # 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"])",
"data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id =",
"data[\"policy_id\"], data[\"resource_group_id\"], related_resource_type[\"system_id\"], related_resource_type[\"type\"], ) # 2. 对比合并差异 conditions =",
"def check_object_permissions(self, request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role",
"SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func):",
"checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True)",
"from backend.service.constants import PermissionCodeEnum, RoleType, SubjectType from backend.service.models import Subject",
"backend.service.models import Subject from backend.trans.group import GroupTrans from .audit import",
"import parse_obj_as from rest_framework import serializers, status, views from rest_framework.pagination",
"= SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"])",
"= ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object() subject",
"http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in",
"responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args,",
"software distributed under the License is distributed on an \"AS",
"permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value,",
"Group.objects.none() # 返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema(",
"import Response from rest_framework.viewsets import GenericViewSet, mixins from backend.account.permissions import",
"request, *args, **kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"]",
"\"template_id\": t[\"template_id\"]} for t in data[\"templates\"]], ) return Response({}, status=status.HTTP_201_CREATED)",
"self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"]) # 用户组数量在角色内是否超限 number_of_new_group = 1 # 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role,",
"one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject",
"tags=[\"group\"], ) def create(self, request, *args, **kwargs): serializer = GroupAuthoriedConditionSLZ(data=request.data)",
"= [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\":",
"group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({})",
"group = self.get_object() data = serializer.validated_data permission_logger.info( \"group %s delete",
"GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data # 用户组名称在角色内唯一",
"@wraps(func) def wrapper(view, request, *args, **kwargs): group = view.get_object() readonly",
"\"subject type=%s, id=%s policy deleted by user %s\", subject.type, subject.id,",
"SubjectType from backend.service.models import Subject from backend.trans.group import GroupTrans from",
"id=%s policy deleted by user %s\", subject.type, subject.id, request.user.username )",
"查询对应的操作 if policy.action_id == action_id: # 操作操作中对应于资源类型的操作 related_resource_type = policy.get_related_resource_type(",
"queryset = Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK:",
"super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], )",
"id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s policy deleted by user %s\",",
"GenericViewSet): permission_classes = [RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\":",
"serializer.validated_data permission_logger.info( \"group %s update members %s expired_at by user",
"写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], )",
"LimitOffsetPagination from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet, mixins",
"int(template_id)) for action in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) # 查询对应的操作",
"= \"id\" template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)},",
".serializers import ( GroupAddMemberSLZ, GroupAuthoriedConditionSLZ, GroupAuthorizationSLZ, GroupCreateSLZ, GroupDeleteMemberSLZ, GroupIdSLZ, GroupMemberUpdateExpiredAtSLZ,",
"\"\"\" serializer = GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data =",
"= GroupCreateSLZ(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.username data = serializer.validated_data #",
"error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True) if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword =",
"GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = { \"list\": PermissionCodeEnum.MANAGE_GROUP.value,",
"GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field = \"id\" template_biz = TemplateBiz()",
"= PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz = GroupBiz() group_trans =",
"from backend.common.time import PERMANENT_SECONDS from backend.service.constants import PermissionCodeEnum, RoleType, SubjectType",
"tags=[\"group\"], ) def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args,",
"related_resource_type else [] # 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean],",
"校验权限 checker = RoleObjectRelationChecker(request.role) if not checker.check_group(group): raise error_codes.FORBIDDEN.format(message=_(\"用户组({})不在当前用户身份可访问的范围内\").format(group.id), replace=True)",
"def create(self, request, *args, **kwargs): serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data",
"import RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template import TemplateBiz from backend.common.error_codes",
"= data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in data[\"actions\"]]",
"ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\",",
"by user %s\", subject.type, subject.id, request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id,",
"GroupCheckBiz() role_biz = RoleBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"),",
"= Group.objects.all() lookup_field = \"id\" biz = GroupBiz() group_check_biz =",
"serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args, **kwargs):",
"delete members %s by user %s\", group.id, data[\"members\"], request.user.username )",
"self.get_object() data = serializer.validated_data permission_logger.info( \"group %s delete members %s",
"request.user.username data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group",
"MemberSLZ, SearchMemberSLZ, ) permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def",
"if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can not access group",
"写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response() @swagger_auto_schema( operation_description=\"用户组权限修改\", request_body=GroupPolicyUpdateSLZ(label=\"修改策略\"), responses={status.HTTP_200_OK:",
"**kwargs): group = self.get_object() data = self.biz.list_system_counter(group.id) return Response([one.dict() for",
"GroupMemberCreateAuditProvider, GroupMemberDeleteAuditProvider, GroupMemberRenewAuditProvider, GroupPolicyDeleteAuditProvider, GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from",
"request.user.username) # 添加成员 self.biz.add_members(group.id, members, expired_at) # 写入审计上下文 audit_context_setter(group=group, members=[m.dict()",
"to in writing, software distributed under the License is distributed",
"templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group, templates) # 写入审计上下文 audit_context_setter( group=group,",
"pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template =",
"@swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"), responses={status.HTTP_200_OK: GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def",
"= Group.objects.all() lookup_field = \"id\" # service group_biz = GroupBiz()",
"many=True)}, tags=[\"group\"], ) def create(self, request, *args, **kwargs): serializer =",
"@check_readonly_group(operation=OperateEnum.GROUP_POLICY_UPDATE.label) def update(self, request, *args, **kwargs): group = self.get_object() slz",
"= GroupCheckBiz() role_biz = RoleBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\",",
"= self.biz.list_system_counter(group.id) return Response([one.dict() for one in data]) class GroupTransferView(views.APIView):",
"policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id,",
"data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role,",
"@swagger_auto_schema( operation_description=\"用户组成员续期\", request_body=GroupMemberUpdateExpiredAtSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def",
"responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def destroy(self, request, *args,",
"for the specific language governing permissions and limitations under the",
"subject.type, subject.id, request.user.username ) policy_list = self.policy_query_biz.query_policy_list_by_policy_ids(system_id, subject, ids) #",
"import logging from functools import wraps from typing import List",
"GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data permission_logger.info( \"group",
"写入审计上下文 audit_context_setter(group=group) return Response({\"id\": group.id}, status=status.HTTP_201_CREATED) def get_queryset(self): request =",
"-*- coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to support",
"= GroupTemplateSystemFilter filter_backends = [NoCheckModelFilterBackend] lookup_field = \"id\" template_biz =",
"request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"修改用户组\", request_body=GroupUpdateSLZ(label=\"用户组\"),",
"data[\"template_id\"] policies = [PolicyBean(expired_at=PERMANENT_SECONDS, **action) for action in data[\"actions\"]] self.group_biz.update_policies(request.role,",
"error_codes from backend.common.filters import NoCheckModelFilterBackend from backend.common.serializers import SystemQuerySLZ from",
"# 接口只支持创建一个用户组,不支持批量,所以新增用户组数量为1 self.group_check_biz.check_role_group_limit(request.role, number_of_new_group) # 检测成员是否满足管理的授权范围 members = parse_obj_as(List[Subject], data[\"members\"])",
"in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies) # 写入审计上下文 audit_context_setter(group=group,",
"slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\":",
"def destroy(self, request, *args, **kwargs): slz = PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id",
"@view_audit_decorator(GroupCreateAuditProvider) def create(self, request, *args, **kwargs): \"\"\" 创建用户组 \"\"\" serializer",
"queryset = Group.objects.all() lookup_field = \"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz",
"kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) for",
"self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True ) return Response([c.dict() for c",
"from functools import wraps from typing import List from django.shortcuts",
"\"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None # 去掉swagger中的limit offset参数 queryset",
"operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def list(self, request, *args,",
"self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet):",
"from django.shortcuts import get_object_or_404 from django.utils.translation import gettext as _",
"Response from rest_framework.viewsets import GenericViewSet, mixins from backend.account.permissions import RolePermission,",
"**kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")}, tags=[\"group\"], ) def retrieve(self, request,",
"返回角色的用户组列表 return RoleListQuery(filter_role, request.user).query_group() return RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK:",
"from backend.biz.policy import PolicyBean, PolicyOperationBiz, PolicyQueryBiz from backend.biz.policy_tag import ConditionTagBean,",
"pagination_class = None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() lookup_field",
"= related_resource_type.condition if related_resource_type else [] # 对比用户组已有的条件与用户提交的条件 conditions =",
"action_id)) class GroupCustomPolicyConditionCompareView(GroupPermissionMixin, GenericViewSet): policy_biz = PolicyQueryBiz() condition_biz = ConditionTagBiz()",
"tags=[\"group\"], ) @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args, **kwargs): serializer",
"RoleBiz() @swagger_auto_schema( operation_description=\"用户组批量转出\", request_body=GroupTransferSLZ(label=\"用户转移\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupTransferAuditProvider) def",
"request, obj): if not RoleObjectRelationChecker(request.role).check_group(obj): self.permission_denied(request, message=f\"{request.role.type} role can not",
"Response({}, status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], )",
"RoleType.STAFF.value and filter_role_id: # 检查用户是否在角色的授权范围内 filter_role = self.role_biz.get_role_scope_include_user(filter_role_id, username) if",
"RoleListQuery(role, request.user).query_group() @swagger_auto_schema( operation_description=\"用户组列表\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\", many=True)}, tags=[\"group\"], ) def",
"**kwargs): group = self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data =",
"serializer = ConditionCompareSLZ(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data group = self.get_object()",
"to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.",
"members %s by user %s\", group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id),",
"\"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz() group_biz = GroupBiz()",
"serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data",
"subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) # 1. 查询policy的condition related_resource_type = data[\"related_resource_type\"]",
"destroy(self, request, *args, **kwargs): group = self.get_object() self.group_biz.delete(group.id) # 写入审计上下文",
"Group.objects.all() lookup_field = \"id\" policy_query_biz = PolicyQueryBiz() policy_operation_biz = PolicyOperationBiz()",
") from .constants import OperateEnum from .filters import GroupFilter, GroupTemplateSystemFilter",
"lookup_field = \"id\" # service group_biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组成员续期\",",
"**action) for action in data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies)",
"policy = PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id == action_id: #",
"data = serializer.validated_data # 用户组名称在角色内唯一 self.group_check_biz.check_role_group_name_unique(request.role.id, data[\"name\"], group.id) group =",
"[RolePermission] action_permission = { \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value,",
"get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset = PermTemplatePolicyAuthorized.objects.filter_by_subject(subject).defer(\"_data\") queryset",
"def get_queryset(self): request = self.request return RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin:",
"RoleBiz() group_trans = GroupTrans() @swagger_auto_schema( operation_description=\"创建用户组\", request_body=GroupCreateSLZ(label=\"用户组\"), responses={status.HTTP_201_CREATED: GroupIdSLZ(label=\"用户组ID\")}, tags=[\"group\"],",
"License for the specific language governing permissions and limitations under",
"} queryset = Group.objects.all() lookup_field = \"id\" biz = GroupBiz()",
"= None # 去掉swagger中的limit offset参数 queryset = Group.objects.all() filterset_class =",
"in group_members]}) pagination = LimitOffsetPagination() limit = pagination.get_limit(request) offset =",
"id=str(group.id)) authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet):",
"self.group_biz.update_members_expired_at( group.id, parse_obj_as(List[GroupMemberExpiredAtBean], data[\"members\"]) ) # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return",
"= Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s policy deleted by",
"@swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], ) def list(self, request,",
"= self.get_object() data = self.biz.list_system_counter(group.id) return Response([one.dict() for one in",
"import PolicyDeleteSLZ, PolicySLZ, PolicySystemSLZ from backend.apps.template.models import PermTemplatePolicyAuthorized from backend.audit.audit",
"= GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data = serializer.validated_data permission_logger.info(",
"%s by user %s\", group.id, data[\"members\"], request.user.username ) self.biz.remove_members(str(group.id), parse_obj_as(List[Subject],",
"permission_logger.info( \"subject type=%s, id=%s policy deleted by user %s\", subject.type,",
"templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for t in data[\"templates\"]], ) return",
"can not access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes",
"ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request, *args, **kwargs): serializer",
"@check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data) serializer.is_valid(raise_exception=True)",
"resource_group_id = data[\"resource_group_id\"] related_resource_type = data[\"related_resource_type\"] new_condition = parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"])",
"data[\"actions\"]] self.group_biz.update_policies(request.role, group.id, system_id, template_id, policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id,",
"RoleObjectRelationChecker from backend.biz.template import TemplateBiz from backend.common.error_codes import error_codes from",
"permission_logger = logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def",
"GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, ) permission_logger",
"PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class = None # 去掉swagger中的limit offset参数",
"deleted by user %s\", subject.type, subject.id, request.user.username ) policy_list =",
") @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args, **kwargs): group =",
"@swagger_auto_schema( operation_description=\"用户组删除成员\", request_body=GroupDeleteMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_DELETE.label) def",
"= GroupTransferSLZ(data=request.data, context={\"role\": request.role}) slz.is_valid(raise_exception=True) group_ids = slz.validated_data[\"group_ids\"] role_id =",
"action in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) # 查询对应的操作 if policy.action_id",
"License (the \"License\"); you may not use this file except",
"RoleListQuery(request.role, request.user).query_group() class GroupPermissionMixin: def check_object_permissions(self, request, obj): if not",
"members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add",
"All rights reserved. Licensed under the MIT License (the \"License\");",
"ConditionTagBiz from backend.biz.role import RoleBiz, RoleListQuery, RoleObjectRelationChecker from backend.biz.template import",
"for action in authorized_template.data[\"actions\"]: policy = PolicyBean.parse_obj(action) # 查询对应的操作 if",
"Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {\"create\":",
"@swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def list(self,",
"def list(self, request, *args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) #",
"parse_obj_as(List[ConditionTagBean], related_resource_type[\"condition\"]) # 从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"] subject =",
"# 写入审计上下文 audit_context_setter(group=group) return Response({}) class GroupMemberViewSet(GroupPermissionMixin, GenericViewSet): permission_classes =",
"# 从模板数据中查找匹配的操作, 资源类型的条件 template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"= PolicyDeleteSLZ(data=request.data) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] ids = slz.validated_data[\"ids\"] group",
"Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz() template_biz = TemplateBiz()",
"class GroupViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = [RolePermission] action_permission = {",
"{ \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, \"update\": PermissionCodeEnum.MANAGE_GROUP.value, } pagination_class =",
"template_id, policies) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, template_id=template_id, policies=policies) return Response({})",
"写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes =",
"tags=[\"group\"], ) def list(self, request, *args, **kwargs): group = self.get_object()",
"list(set(parse_obj_as(List[Subject], members_data))) # 检测成员是否满足管理的授权范围 self.group_check_biz.check_role_subject_scope(request.role, members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s",
"@swagger_auto_schema( operation_description=\"用户组删除自定义权限\", request_body=PolicyDeleteSLZ(label=\"ids\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupPolicyDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_POLICY_DELETE.label) def",
"biz = GroupBiz() group_check_biz = GroupCheckBiz() @swagger_auto_schema( operation_description=\"用户组成员列表\", query_serializer=SearchMemberSLZ(label=\"keyword\"), responses={status.HTTP_200_OK:",
"from backend.audit.audit import audit_context_setter, view_audit_decorator from backend.biz.group import GroupBiz, GroupCheckBiz,",
"by applicable law or agreed to in writing, software distributed",
"**kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) # 校验权限 checker = RoleObjectRelationChecker(request.role)",
"def post(self, request, *args, **kwargs): slz = GroupTransferSLZ(data=request.data, context={\"role\": request.role})",
"replace=True) if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower()",
"= self.get_object() slz = GroupPolicyUpdateSLZ(data=request.data) slz.is_valid(raise_exception=True) data = slz.validated_data system_id",
"*args, **kwargs): slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group",
"operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupDeleteAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request,",
") def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs)",
"expired_at by user %s\", group.id, data[\"members\"], request.user.username ) for m",
"templates) # 写入审计上下文 audit_context_setter( group=group, templates=[{\"system_id\": t[\"system_id\"], \"template_id\": t[\"template_id\"]} for",
"group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) template_id = kwargs[\"template_id\"] subject = Subject(type=SubjectType.GROUP.value,",
"\"\"\" TencentBlueKing is pleased to support the open source community",
"group_members = self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict() for one in",
"user_id) # 写入审计上下文 audit_context_setter(group=group) return Response(serializer.data) @swagger_auto_schema( operation_description=\"删除用户组\", responses={status.HTTP_200_OK: serializers.Serializer()},",
"template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"], )",
"= \"id\" @swagger_auto_schema( operation_description=\"条件差异对比\", request_body=ConditionCompareSLZ(label=\"资源条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], )",
") @view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args, **kwargs): serializer =",
"*args, **kwargs): return super().list(request, *args, **kwargs) @swagger_auto_schema( operation_description=\"用户组详情\", responses={status.HTTP_200_OK: GroupSLZ(label=\"用户组\")},",
") # 使用长时任务触发多个模板同时授权 if data[\"templates\"]: templates = self.group_trans.from_group_grant_data(data[\"templates\"]) self.group_biz.grant(request.role, group,",
"return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission] action_permission =",
"type=%s, id=%s policy deleted by user %s\", subject.type, subject.id, request.user.username",
"= slz.validated_data[\"group_ids\"] role_id = slz.validated_data[\"role_id\"] self.role_biz.transfer_groups_role(group_ids, role_id) audit_context_setter(group_ids=group_ids, role_id=role_id) return",
"= logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def wrapper(view,",
"authorized_template = PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes",
"as _ from drf_yasg.utils import swagger_auto_schema from pydantic.tools import parse_obj_as",
"\"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() lookup_field = \"id\" biz",
"def decorate(func): @wraps(func) def wrapper(view, request, *args, **kwargs): group =",
"= \"id\" biz = GroupBiz() @swagger_auto_schema( operation_description=\"用户组有权限的所有系统列表\", responses={status.HTTP_200_OK: PolicySystemSLZ(label=\"系统\", many=True)},",
"GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz() template_biz = TemplateBiz() queryset =",
"with the License. You may obtain a copy of the",
"functools import wraps from typing import List from django.shortcuts import",
"request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)}, tags=[\"group\"], ) def create(self, request, *args,",
"raise error_codes.FORBIDDEN.format( message=_(\"只读用户组({})无法进行({})操作!\").format(group.id, operation), replace=True ) response = func(view, request,",
"keyword = slz.validated_data[\"keyword\"].lower() group_members = self.biz.search_member_by_keyword(group.id, keyword) return Response({\"results\": [one.dict()",
"logging.getLogger(\"permission\") def check_readonly_group(operation): \"\"\"用户组可读检测\"\"\" def decorate(func): @wraps(func) def wrapper(view, request,",
"GroupMemberUpdateExpiredAtViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [role_perm_class(PermissionCodeEnum.MANAGE_GROUP.value)] queryset = Group.objects.all() lookup_field =",
"self.permission_denied(request, message=f\"{request.role.type} role can not access group {obj.id}\") class GroupViewSet(mixins.RetrieveModelMixin,",
"Subject(type=SubjectType.GROUP.value, id=str(group.id)) permission_logger.info( \"subject type=%s, id=%s policy deleted by user",
"*args, **kwargs): serializer = GroupAddMemberSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data",
"self.policy_operation_biz.delete_by_ids(system_id, subject, ids) # 写入审计上下文 audit_context_setter(group=group, system_id=system_id, policies=policy_list.policies) return Response()",
") response = func(view, request, *args, **kwargs) return response return",
") # 写入审计上下文 audit_context_setter(group=group, members=data[\"members\"]) return Response({}) class GroupTemplateViewSet(GroupPermissionMixin, GenericViewSet):",
"PermissionCodeEnum, RoleType, SubjectType from backend.service.models import Subject from backend.trans.group import",
"@check_readonly_group(operation=OperateEnum.GROUP_DELETE.label) def destroy(self, request, *args, **kwargs): group = self.get_object() self.group_biz.delete(group.id)",
"queryset = Group.objects.all() lookup_field = \"id\" biz = GroupBiz() group_check_biz",
"@view_audit_decorator(GroupMemberRenewAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_RENEW.label) def create(self, request, *args, **kwargs): serializer = GroupMemberUpdateExpiredAtSLZ(data=request.data)",
"members_data = data[\"members\"] expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members =",
"count, \"results\": [one.dict() for one in group_members]}) @swagger_auto_schema( operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"),",
"*args, **kwargs): group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id))",
"group = self.get_object() self.group_biz.delete(group.id) # 写入审计上下文 audit_context_setter(group=group) return Response({}) class",
"GroupFilter lookup_field = \"id\" group_biz = GroupBiz() group_check_biz = GroupCheckBiz()",
"{ \"list\": PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset =",
"GroupSLZ, GroupTemplateDetailSchemaSLZ, GroupTemplateDetailSLZ, GroupTemplateSchemaSLZ, GroupTemplateSLZ, GroupTransferSLZ, GroupUpdateSLZ, MemberSLZ, SearchMemberSLZ, )",
"slz = SystemQuerySLZ(data=request.query_params) slz.is_valid(raise_exception=True) system_id = slz.validated_data[\"system_id\"] group = get_object_or_404(self.queryset,",
"role_id=role_id) return Response({}) class GroupTemplateConditionCompareView(GroupPermissionMixin, GenericViewSet): condition_biz = ConditionTagBiz() template_biz",
"\"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() lookup_field =",
"蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent",
"if request.query_params.get(\"keyword\"): slz = SearchMemberSLZ(data=request.query_params) slz.is_valid(raise_exception=True) keyword = slz.validated_data[\"keyword\"].lower() group_members",
"expired_at = data[\"expired_at\"] # 成员Dict结构转换为Subject结构,并去重 members = list(set(parse_obj_as(List[Subject], members_data))) #",
"many=True)}, tags=[\"group\"], ) def list(self, request, *args, **kwargs): slz =",
"status=status.HTTP_201_CREATED) @swagger_auto_schema( operation_description=\"用户组自定义权限列表\", query_serializer=SystemQuerySLZ, responses={status.HTTP_200_OK: PolicySLZ(label=\"策略\", many=True)}, tags=[\"group\"], ) def",
"action_permission = {\"create\": PermissionCodeEnum.MANAGE_GROUP.value} pagination_class = None # 去掉swagger中的limit offset参数",
"operation_description=\"用户组添加成员\", request_body=GroupAddMemberSLZ(label=\"成员\"), responses={status.HTTP_200_OK: serializers.Serializer()}, tags=[\"group\"], ) @view_audit_decorator(GroupMemberCreateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_MEMBER_CREATE.label) def create(self,",
"members) self.group_check_biz.check_member_count(group.id, len(members)) permission_logger.info(\"group %s add members %s by user",
"GroupPolicyUpdateAuditProvider, GroupTemplateCreateAuditProvider, GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants import OperateEnum from",
"License. You may obtain a copy of the License at",
"offset参数 queryset = Group.objects.all() lookup_field = \"id\" policy_query_biz = PolicyQueryBiz()",
"old_condition = related_resource_type.condition if related_resource_type else [] # 对比用户组已有的条件与用户提交的条件 conditions",
"[] # 对比用户组已有的条件与用户提交的条件 conditions = self.condition_biz.compare_and_tag( new_condition, parse_obj_as(List[ConditionTagBean], old_condition), is_template=True",
"GroupUpdateSLZ(label=\"用户组\")}, tags=[\"group\"], ) @view_audit_decorator(GroupUpdateAuditProvider) @check_readonly_group(operation=OperateEnum.GROUP_UPDATE.label) def update(self, request, *args, **kwargs):",
"GroupTransferAuditProvider, GroupUpdateAuditProvider, ) from .constants import OperateEnum from .filters import",
"\"id\" template_biz = TemplateBiz() @swagger_auto_schema( operation_description=\"用户组拥有的权限模板列表\", responses={status.HTTP_200_OK: GroupTemplateSchemaSLZ(label=\"权限模板\", many=True)}, tags=[\"group\"],",
"PermTemplatePolicyAuthorized.objects.get_by_subject_template(subject, int(template_id)) return Response(GroupTemplateDetailSLZ(authorized_template).data) class GroupPolicyViewSet(GroupPermissionMixin, GenericViewSet): permission_classes = [RolePermission]",
"*args, **kwargs): serializer = GroupAuthorizationSLZ(data=request.data) serializer.is_valid(raise_exception=True) group = self.get_object() data",
"Group.objects.all() lookup_field = \"id\" @swagger_auto_schema( operation_description=\"权限模板操作条件对比\", request_body=GroupAuthoriedConditionSLZ(label=\"操作条件\"), responses={status.HTTP_200_OK: ConditionTagSLZ(label=\"条件差异\", many=True)},",
"group = get_object_or_404(self.queryset, pk=kwargs[\"id\"]) subject = Subject(type=SubjectType.GROUP.value, id=str(group.id)) queryset =",
"PermissionCodeEnum.MANAGE_GROUP.value, \"create\": PermissionCodeEnum.MANAGE_GROUP.value, \"destroy\": PermissionCodeEnum.MANAGE_GROUP.value, } queryset = Group.objects.all() lookup_field"
] |
[
"None # for e in self.state.entities.enemies(): # d = util.dist(self.x,",
"self.delete() def put (self): assert self.state.energy > 0 self.state.entities.append(self) self.state.energy",
"e preferred_targets = [] other_targets = [] for e in",
"= 20 def delete (self): self.state.is_paused = True return super(Heart,",
"e.x, e.y) if d < (self.radius + 1): if e",
"*args): super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000, self._research) def _research (self):",
"operator.itemgetter(0))[0] elif other_targets: _d, target = sorted(other_targets, key = operator.itemgetter(0))[0]",
"False self.rollback_timer = self.state.timers.start_run_once(1000, rollback) elif getattr(self, 'rollback_timer', False): self.rollback_timer.reset()",
"class Bait (Building): sym = Heart.sym color = tcod.pink max_hp",
"< 1: self.die() def hit (self, e): if e in",
"self).__init__(*args) self.timer = self.state.timers.start(1000, self._research) def _research (self): pass class",
"or (d < dist_min)): # dist_min = d # target",
"y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color) class AoeTower (Tower):",
"d # target = e preferred_targets = [] other_targets =",
"__init__ (self, *args): super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000, self._research) def",
"BasicTower (Tower): color = tcod.dark_green missile = BasicMissile cost =",
"= 0.2 color = tcod.dark_blue missile = IceMissile cost =",
"in range(target.x - radius, target.x + radius): for y in",
"sym = '*' color = tcod.dark_red def __init__ (self, radius,",
"self.hp < 1: self.die() def hit (self, e): if e",
"m.x = x m.y = y class BasicTower (Tower): color",
"e.x, e.y) x, y = tcod.line_step() if x is None:",
"1)): if util.dist(self.x, self.y, x, y) < (self.radius + 1):",
"for y in range(target.y - radius, target.y + radius): for",
"= None if preferred_targets: _d, target = sorted(preferred_targets, key =",
"update_missile (self, m, e): tcod.line_init(m.x, m.y, e.x, e.y) x, y",
"super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000, self._research) def _research (self): pass",
"= tcod.dark_green missile = BasicMissile cost = 1 class ResearchBuilding",
"(self.radius + 1)): if util.dist(self.x, self.y, x, y) < (self.radius",
"self.update_missile, [m, e]) def update_missile (self, m, e): tcod.line_init(m.x, m.y,",
"self.radius): tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color)",
"if preferred_targets: _d, target = sorted(preferred_targets, key = operator.itemgetter(0))[0] elif",
"self.radius = radius def render (self): for x in range(self.x",
"rollback (): target.timer.interval = old_speed target.timer.time_buf /= 3 target.is_debuffed =",
"y class BasicTower (Tower): color = tcod.dark_green missile = BasicMissile",
"tcod.BKGND_SET) def _shoot (self, e): self.cooldown = True def clear_cd",
"self.hit(e) return util.STOP else: m.x = x m.y = y",
"return util.STOP else: m.x = x m.y = y class",
"missile = IceMissile cost = 1 def hit (self, target):",
"0 self.state.entities.append(self) self.state.energy -= self.cost return self def delete (self):",
"radius = 15 max_hp = 10 damage = 1 missile",
"(util.Entity): sym = '@' max_hp = 1 cost = 0",
"return super(Heart, self).delete() class Bait (Building): sym = Heart.sym color",
"as tcod import enemies import operator class Missile (util.Entity): sym",
"True return super(Heart, self).delete() class Bait (Building): sym = Heart.sym",
"self.y, x, y) < (self.radius + 1): tcod.console_set_char_background(0, x, y,",
"class Tower (Building): radius = 15 max_hp = 10 damage",
"for e in self.state.entities.enemies(): # d = util.dist(self.x, self.y, e.x,",
"x in range(target.x - radius, target.x + radius): for y",
"for e in self.state.entities.enemies(): if (e.x, e.y) == (x, y):",
"self.die() def hit (self, e): if e in self.state.entities: e.hurt(self.damage)",
"1) and ((dist_min is None) or (d < dist_min)): #",
"[m, e]) def update_missile (self, m, e): tcod.line_init(m.x, m.y, e.x,",
"import operator class Missile (util.Entity): sym = '*' color =",
"if self.hp < 1: self.die() def hit (self, e): if",
"sorted(other_targets, key = operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target) def render",
"missile = AoeMissile cost = 2 def hit (self, target):",
"range(self.x - (self.radius + 1), self.x + (self.radius + 1)):",
"(self.radius + 1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET)",
"2 def hit (self, target): radius = 2 for x",
"(self, hp): self.hp -= hp if self.hp < 1: self.die()",
"for x in range(target.x - radius, target.x + radius): for",
"1)): for y in range(self.y - (self.radius + 1), self.y",
"False self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed",
"3 target.is_debuffed = False self.rollback_timer = self.state.timers.start_run_once(1000, rollback) elif getattr(self,",
"color = tcod.light_blue class AoeMissile (Missile): color = tcod.red class",
"= 10 damage = 1 missile = None def __init__",
"sorted(preferred_targets, key = operator.itemgetter(0))[0] elif other_targets: _d, target = sorted(other_targets,",
"self.y + (self.radius + 1)): if util.dist(self.x, self.y, x, y)",
"self).__init__(*args) self.radius = radius def render (self): for x in",
"def delete (self): self.state.entities.remove(self) self.state.energy += self.cost return self class",
"def hurt (self, hp): self.hp -= hp if self.hp <",
"dist_min = None # target = None # for e",
"def hit (self, target): radius = 2 for x in",
"target): radius = 2 for x in range(target.x - radius,",
"(self.radius + 1) and ((dist_min is None) or (d <",
"self.hp -= hp if self.hp < 1: self.die() def hit",
"(Tower): color = tcod.dark_green missile = BasicMissile cost = 1",
"target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower (Tower): damage =",
"Tower (Building): radius = 15 max_hp = 10 damage =",
"util.dist(self.x, self.y, e.x, e.y) # if d < (self.radius +",
"tcod.darker_red max_hp = 20 def delete (self): self.state.is_paused = True",
"self.state.entities: e.hurt(self.damage) def die (self): if self in self.state.entities: self.delete()",
"range(self.y - (self.radius + 1), self.y + (self.radius + 1)):",
"(self): super(Tower, self).render() if self.mouse_over: # if True: for x",
"Heart (Building): sym = '&' color = tcod.darker_red max_hp =",
"'*' color = tcod.white class BasicMissile (Missile): color = tcod.yellow",
"e)) target = None if preferred_targets: _d, target = sorted(preferred_targets,",
"cost = 2 def hit (self, target): radius = 2",
"= sum([t.damage for t in self.state.targets_towers[e]]) if total_damage < e.hp:",
"tcod.red class Building (util.Entity): sym = '@' max_hp = 1",
"(Building): sym = Heart.sym color = tcod.pink max_hp = 10",
"cost = 1 class ResearchBuilding (Building): color = tcod.dark_sepia cost",
"in self.state.entities: #TODO copypaste e.hurt(self.damage) e = AoeExplosion(radius, self.state, target.x,",
"is None) or (d < dist_min)): # dist_min = d",
"target: self.state.targets_towers[target].append(self) self._shoot(target) def render (self): super(Tower, self).render() if self.mouse_over:",
"max_hp = 10 damage = 1 missile = None def",
"+ 1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def",
"elif other_targets: _d, target = sorted(other_targets, key = operator.itemgetter(0))[0] if",
"else: other_targets.append((d, e)) else: preferred_targets.append((d, e)) target = None if",
"target.timer.interval = old_speed target.timer.time_buf /= 3 target.is_debuffed = False self.rollback_timer",
"= tcod.BKGND_SET) def _shoot (self, e): self.cooldown = True def",
"15 max_hp = 10 damage = 1 missile = None",
"super(Tower, self).render() if self.mouse_over: # if True: for x in",
"tcod import enemies import operator class Missile (util.Entity): sym =",
"= d # target = e preferred_targets = [] other_targets",
"target = sorted(other_targets, key = operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target)",
"tcod.pink max_hp = 10 class Tower (Building): radius = 15",
"(self, target): radius = 2 for x in range(target.x -",
"target = e preferred_targets = [] other_targets = [] for",
"enemies import operator class Missile (util.Entity): sym = '*' color",
"operator class Missile (util.Entity): sym = '*' color = tcod.white",
"cost = 0 def __init__ (self, *args): super(Building, self).__init__(*args) self.hp",
"e = AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e))",
"class Missile (util.Entity): sym = '*' color = tcod.white class",
"self class Heart (Building): sym = '&' color = tcod.darker_red",
"def render (self): super(Tower, self).render() if self.mouse_over: # if True:",
"*args): super(Tower, self).__init__(*args) self.cooldown = False def update (self): if",
"self.state.entities.remove(self) self.state.energy += self.cost return self class Heart (Building): sym",
"< (self.radius + 1): if e in self.state.targets_towers: total_damage =",
"other_targets: _d, target = sorted(other_targets, key = operator.itemgetter(0))[0] if target:",
"radius = 2 for x in range(target.x - radius, target.x",
"self.state.energy -= self.cost return self def delete (self): self.state.entities.remove(self) self.state.energy",
"and ((dist_min is None) or (d < dist_min)): # dist_min",
"self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower (Tower): damage = 0.2 color",
"self.state.timers.start(1000, self._research) def _research (self): pass class AoeExplosion (util.Entity): sym",
"self).__init__(*args) self.hp = self.max_hp def hurt (self, hp): self.hp -=",
"= [] other_targets = [] for e in self.state.entities.enemies(): d",
"if util.dist(self.x, self.y, x, y) < (self.radius + 1): tcod.console_set_char_background(0,",
"def __init__ (self, *args): super(Building, self).__init__(*args) self.hp = self.max_hp def",
"IceMissile (Missile): color = tcod.light_blue class AoeMissile (Missile): color =",
"sym = '@' max_hp = 1 cost = 0 def",
"(Missile): color = tcod.light_blue class AoeMissile (Missile): color = tcod.red",
"target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower (Tower): damage",
"target.hurt(self.damage) if not getattr(target, 'is_debuffed', False): old_speed = target.timer.interval target.timer.interval",
"def delete (self): self.state.is_paused = True return super(Heart, self).delete() class",
"old_speed = target.timer.interval target.timer.interval *= 3 target.timer.time_buf *= 3 target.is_debuffed",
"(Building): sym = '&' color = tcod.darker_red max_hp = 20",
"tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color) class AoeTower (Tower): color =",
"if total_damage < e.hp: preferred_targets.append((d, e)) else: other_targets.append((d, e)) else:",
"self.y) self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile, [m, e]) def",
"(util.Entity): sym = '*' color = tcod.white class BasicMissile (Missile):",
"(Tower): damage = 0.2 color = tcod.dark_blue missile = IceMissile",
"0 def __init__ (self, *args): super(Building, self).__init__(*args) self.hp = self.max_hp",
"Bait (Building): sym = Heart.sym color = tcod.pink max_hp =",
"total_damage = sum([t.damage for t in self.state.targets_towers[e]]) if total_damage <",
"tcod.dark_green missile = BasicMissile cost = 1 class ResearchBuilding (Building):",
"# dist_min = None # target = None # for",
"+ (self.radius + 1)): for y in range(self.y - (self.radius",
"color = tcod.dark_red def __init__ (self, radius, *args): super(AoeExplosion, self).__init__(*args)",
"radius, *args): super(AoeExplosion, self).__init__(*args) self.radius = radius def render (self):",
"color = tcod.white class BasicMissile (Missile): color = tcod.yellow class",
"missile = BasicMissile cost = 1 class ResearchBuilding (Building): color",
"def __init__ (self, *args): super(Tower, self).__init__(*args) self.cooldown = False def",
"missile = None def __init__ (self, *args): super(Tower, self).__init__(*args) self.cooldown",
"y in range(self.y - (self.radius + 1), self.y + (self.radius",
"self.state.timers.start(missile_speed, self.update_missile, [m, e]) def update_missile (self, m, e): tcod.line_init(m.x,",
"sym = '&' color = tcod.darker_red max_hp = 20 def",
"if not self.cooldown: # dist_min = None # target =",
"e.y) # if d < (self.radius + 1) and ((dist_min",
"for e in self.state.entities.enemies(): d = util.dist(self.x, self.y, e.x, e.y)",
"# dist_min = d # target = e preferred_targets =",
"self.state.is_paused = True return super(Heart, self).delete() class Bait (Building): sym",
"x, y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def _shoot (self, e):",
"if True: for x in range(self.x - (self.radius + 1),",
"hit (self, e): if e in self.state.entities: e.hurt(self.damage) def die",
"self.color) class AoeTower (Tower): color = tcod.dark_orange missile = AoeMissile",
"__init__ (self, radius, *args): super(AoeExplosion, self).__init__(*args) self.radius = radius def",
"dist_min)): # dist_min = d # target = e preferred_targets",
"e.x, e.y) # if d < (self.radius + 1) and",
"target = None # for e in self.state.entities.enemies(): # d",
"= tcod.white class BasicMissile (Missile): color = tcod.yellow class IceMissile",
"def update_missile (self, m, e): tcod.line_init(m.x, m.y, e.x, e.y) x,",
"target.timer.time_buf *= 3 target.is_debuffed = True def rollback (): target.timer.interval",
"self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower (Tower): damage = 0.2",
"util.dist(self.x, self.y, x, y) < (self.radius + 1): tcod.console_set_char_background(0, x,",
"(Building): color = tcod.dark_sepia cost = 1 def __init__ (self,",
"self def delete (self): self.state.entities.remove(self) self.state.energy += self.cost return self",
"max_hp = 20 def delete (self): self.state.is_paused = True return",
"util.STOP else: m.x = x m.y = y class BasicTower",
"1 def hit (self, target): target.hurt(self.damage) if not getattr(target, 'is_debuffed',",
"def die (self): if self in self.state.entities: self.delete() def put",
"self.state.energy += self.cost return self class Heart (Building): sym =",
"d = util.dist(self.x, self.y, e.x, e.y) # if d <",
"= 2 def hit (self, target): radius = 2 for",
"None def __init__ (self, *args): super(Tower, self).__init__(*args) self.cooldown = False",
"self.state.entities: #TODO copypaste e.hurt(self.damage) e = AoeExplosion(radius, self.state, target.x, target.y)",
"preferred_targets.append((d, e)) target = None if preferred_targets: _d, target =",
"preferred_targets = [] other_targets = [] for e in self.state.entities.enemies():",
"lambda: self.state.entities.remove(e)) class IceTower (Tower): damage = 0.2 color =",
"+ 1) and ((dist_min is None) or (d < dist_min)):",
"m.y = y class BasicTower (Tower): color = tcod.dark_green missile",
"libtcodpy as tcod import enemies import operator class Missile (util.Entity):",
"AoeTower (Tower): color = tcod.dark_orange missile = AoeMissile cost =",
"+ radius): for e in self.state.entities.enemies(): if (e.x, e.y) ==",
"self.mouse_over: # if True: for x in range(self.x - (self.radius",
"IceMissile cost = 1 def hit (self, target): target.hurt(self.damage) if",
"self.hp = self.max_hp def hurt (self, hp): self.hp -= hp",
"(self): self.state.entities.remove(self) self.state.energy += self.cost return self class Heart (Building):",
"= tcod.dark_sepia cost = 1 def __init__ (self, *args): super(ResearchBuilding,",
"target.is_debuffed = True def rollback (): target.timer.interval = old_speed target.timer.time_buf",
"# if d < (self.radius + 1) and ((dist_min is",
"def clear_cd (): self.cooldown = False self.state.timers.start_run_once(1000, clear_cd) m =",
"clear_cd) m = self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed = 20",
"if e in self.state.entities: #TODO copypaste e.hurt(self.damage) e = AoeExplosion(radius,",
"= sorted(preferred_targets, key = operator.itemgetter(0))[0] elif other_targets: _d, target =",
"= IceMissile cost = 1 def hit (self, target): target.hurt(self.damage)",
"clear_cd (): self.cooldown = False self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state,",
"= 1 class ResearchBuilding (Building): color = tcod.dark_sepia cost =",
"for y in range(self.y - self.radius, self.y + self.radius): tcod.console_put_char(0,",
"class AoeMissile (Missile): color = tcod.red class Building (util.Entity): sym",
"True: for x in range(self.x - (self.radius + 1), self.x",
"1 cost = 0 def __init__ (self, *args): super(Building, self).__init__(*args)",
"(Tower): color = tcod.dark_orange missile = AoeMissile cost = 2",
"None: self.state.entities.remove(m) self.hit(e) return util.STOP else: m.x = x m.y",
"if e in self.state.entities: e.hurt(self.damage) def die (self): if self",
"# if True: for x in range(self.x - (self.radius +",
"= 10 class Tower (Building): radius = 15 max_hp =",
"self.y, e.x, e.y) if d < (self.radius + 1): if",
"self.cooldown = False self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state, self.x, self.y)",
"'&' color = tcod.darker_red max_hp = 20 def delete (self):",
"'is_debuffed', False): old_speed = target.timer.interval target.timer.interval *= 3 target.timer.time_buf *=",
"class Heart (Building): sym = '&' color = tcod.darker_red max_hp",
"for x in range(self.x - (self.radius + 1), self.x +",
"in self.state.entities.enemies(): if (e.x, e.y) == (x, y): if e",
"key = operator.itemgetter(0))[0] elif other_targets: _d, target = sorted(other_targets, key",
"BasicMissile cost = 1 class ResearchBuilding (Building): color = tcod.dark_sepia",
"/= 3 target.is_debuffed = False self.rollback_timer = self.state.timers.start_run_once(1000, rollback) elif",
"y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def _shoot (self, e): self.cooldown",
"= tcod.yellow class IceMissile (Missile): color = tcod.light_blue class AoeMissile",
"(x, y): if e in self.state.entities: #TODO copypaste e.hurt(self.damage) e",
"tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color) class",
"BasicMissile (Missile): color = tcod.yellow class IceMissile (Missile): color =",
"__init__ (self, *args): super(Tower, self).__init__(*args) self.cooldown = False def update",
"= '&' color = tcod.darker_red max_hp = 20 def delete",
"in self.state.entities.enemies(): d = util.dist(self.x, self.y, e.x, e.y) if d",
"self.x + self.radius): for y in range(self.y - self.radius, self.y",
"= 1 def hit (self, target): target.hurt(self.damage) if not getattr(target,",
"3 target.is_debuffed = True def rollback (): target.timer.interval = old_speed",
"(util.Entity): sym = '*' color = tcod.dark_red def __init__ (self,",
"e.hurt(self.damage) def die (self): if self in self.state.entities: self.delete() def",
"def hit (self, e): if e in self.state.entities: e.hurt(self.damage) def",
"# d = util.dist(self.x, self.y, e.x, e.y) # if d",
"other_targets = [] for e in self.state.entities.enemies(): d = util.dist(self.x,",
"if x is None: self.state.entities.remove(m) self.hit(e) return util.STOP else: m.x",
"+= self.cost return self class Heart (Building): sym = '&'",
"(self, *args): super(Tower, self).__init__(*args) self.cooldown = False def update (self):",
"1): if e in self.state.targets_towers: total_damage = sum([t.damage for t",
"import enemies import operator class Missile (util.Entity): sym = '*'",
"AoeExplosion (util.Entity): sym = '*' color = tcod.dark_red def __init__",
"= operator.itemgetter(0))[0] elif other_targets: _d, target = sorted(other_targets, key =",
"= False self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state, self.x, self.y) self.state.entities.append(m)",
"in range(self.y - self.radius, self.y + self.radius): tcod.console_put_char(0, x, y,",
"self.cost return self class Heart (Building): sym = '&' color",
"in self.state.entities.enemies(): # d = util.dist(self.x, self.y, e.x, e.y) #",
"def hit (self, target): target.hurt(self.damage) if not getattr(target, 'is_debuffed', False):",
"self.x, self.y) self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile, [m, e])",
"0.2 color = tcod.dark_blue missile = IceMissile cost = 1",
"render (self): super(Tower, self).render() if self.mouse_over: # if True: for",
"= tcod.pink max_hp = 10 class Tower (Building): radius =",
"y = tcod.line_step() if x is None: self.state.entities.remove(m) self.hit(e) return",
"radius): for e in self.state.entities.enemies(): if (e.x, e.y) == (x,",
"*args): super(AoeExplosion, self).__init__(*args) self.radius = radius def render (self): for",
"20 self.state.timers.start(missile_speed, self.update_missile, [m, e]) def update_missile (self, m, e):",
"= True def clear_cd (): self.cooldown = False self.state.timers.start_run_once(1000, clear_cd)",
"self.max_hp def hurt (self, hp): self.hp -= hp if self.hp",
"(self.radius + 1): if e in self.state.targets_towers: total_damage = sum([t.damage",
"class AoeTower (Tower): color = tcod.dark_orange missile = AoeMissile cost",
"in range(self.y - (self.radius + 1), self.y + (self.radius +",
"True def clear_cd (): self.cooldown = False self.state.timers.start_run_once(1000, clear_cd) m",
"in self.state.entities: self.delete() def put (self): assert self.state.energy > 0",
"- self.radius, self.y + self.radius): tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE)",
"class IceMissile (Missile): color = tcod.light_blue class AoeMissile (Missile): color",
"hp): self.hp -= hp if self.hp < 1: self.die() def",
"self).__init__(*args) self.cooldown = False def update (self): if not self.cooldown:",
"self.state.entities.enemies(): d = util.dist(self.x, self.y, e.x, e.y) if d <",
"else: m.x = x m.y = y class BasicTower (Tower):",
"self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower (Tower):",
"= 15 max_hp = 10 damage = 1 missile =",
"self.state.targets_towers[e]]) if total_damage < e.hp: preferred_targets.append((d, e)) else: other_targets.append((d, e))",
"__init__ (self, *args): super(Building, self).__init__(*args) self.hp = self.max_hp def hurt",
"other_targets.append((d, e)) else: preferred_targets.append((d, e)) target = None if preferred_targets:",
"= 2 for x in range(target.x - radius, target.x +",
"tcod.yellow class IceMissile (Missile): color = tcod.light_blue class AoeMissile (Missile):",
"= '*' color = tcod.dark_red def __init__ (self, radius, *args):",
"#TODO copypaste e.hurt(self.damage) e = AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e)",
"update (self): if not self.cooldown: # dist_min = None #",
"tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def _shoot (self,",
"(self, *args): super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000, self._research) def _research",
"= 20 self.state.timers.start(missile_speed, self.update_missile, [m, e]) def update_missile (self, m,",
"e]) def update_missile (self, m, e): tcod.line_init(m.x, m.y, e.x, e.y)",
"util.dist(self.x, self.y, e.x, e.y) if d < (self.radius + 1):",
"e in self.state.entities.enemies(): # d = util.dist(self.x, self.y, e.x, e.y)",
"= Heart.sym color = tcod.pink max_hp = 10 class Tower",
"e in self.state.entities.enemies(): if (e.x, e.y) == (x, y): if",
"= util.dist(self.x, self.y, e.x, e.y) # if d < (self.radius",
"(Building): radius = 15 max_hp = 10 damage = 1",
"target): target.hurt(self.damage) if not getattr(target, 'is_debuffed', False): old_speed = target.timer.interval",
"y in range(target.y - radius, target.y + radius): for e",
"sym = Heart.sym color = tcod.pink max_hp = 10 class",
"max_hp = 10 class Tower (Building): radius = 15 max_hp",
"self.cooldown: # dist_min = None # target = None #",
"import libtcodpy as tcod import enemies import operator class Missile",
"1: self.die() def hit (self, e): if e in self.state.entities:",
"# target = e preferred_targets = [] other_targets = []",
"hit (self, target): target.hurt(self.damage) if not getattr(target, 'is_debuffed', False): old_speed",
"target.timer.time_buf /= 3 target.is_debuffed = False self.rollback_timer = self.state.timers.start_run_once(1000, rollback)",
"(self, e): self.cooldown = True def clear_cd (): self.cooldown =",
"tcod.white class BasicMissile (Missile): color = tcod.yellow class IceMissile (Missile):",
"hit (self, target): radius = 2 for x in range(target.x",
"d < (self.radius + 1): if e in self.state.targets_towers: total_damage",
"_d, target = sorted(other_targets, key = operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self)",
"< (self.radius + 1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag =",
"self.state.entities.remove(m) self.hit(e) return util.STOP else: m.x = x m.y =",
"= BasicMissile cost = 1 class ResearchBuilding (Building): color =",
"radius, target.x + radius): for y in range(target.y - radius,",
"e)) else: other_targets.append((d, e)) else: preferred_targets.append((d, e)) target = None",
"((dist_min is None) or (d < dist_min)): # dist_min =",
"self.state.targets_towers[target].append(self) self._shoot(target) def render (self): super(Tower, self).render() if self.mouse_over: #",
"if e in self.state.targets_towers: total_damage = sum([t.damage for t in",
"color = tcod.dark_orange missile = AoeMissile cost = 2 def",
"Heart.sym color = tcod.pink max_hp = 10 class Tower (Building):",
"in self.state.targets_towers: total_damage = sum([t.damage for t in self.state.targets_towers[e]]) if",
"self.radius, self.y + self.radius): tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0,",
"+ self.radius): for y in range(self.y - self.radius, self.y +",
"(self): assert self.state.energy > 0 self.state.entities.append(self) self.state.energy -= self.cost return",
"def _shoot (self, e): self.cooldown = True def clear_cd ():",
"tcod.console_set_char_foreground(0, x, y, self.color) class AoeTower (Tower): color = tcod.dark_orange",
"class Building (util.Entity): sym = '@' max_hp = 1 cost",
"(self): pass class AoeExplosion (util.Entity): sym = '*' color =",
"assert self.state.energy > 0 self.state.entities.append(self) self.state.energy -= self.cost return self",
"x, y) < (self.radius + 1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3),",
"= self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile,",
"_shoot (self, e): self.cooldown = True def clear_cd (): self.cooldown",
"x m.y = y class BasicTower (Tower): color = tcod.dark_green",
"= True def rollback (): target.timer.interval = old_speed target.timer.time_buf /=",
"pass class AoeExplosion (util.Entity): sym = '*' color = tcod.dark_red",
"x, y = tcod.line_step() if x is None: self.state.entities.remove(m) self.hit(e)",
"self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color) class AoeTower (Tower): color",
"target.is_debuffed = False self.rollback_timer = self.state.timers.start_run_once(1000, rollback) elif getattr(self, 'rollback_timer',",
"target = sorted(preferred_targets, key = operator.itemgetter(0))[0] elif other_targets: _d, target",
"tcod.dark_orange missile = AoeMissile cost = 2 def hit (self,",
"cost = 1 def hit (self, target): target.hurt(self.damage) if not",
"e in self.state.entities.enemies(): d = util.dist(self.x, self.y, e.x, e.y) if",
"= 1 missile = None def __init__ (self, *args): super(Tower,",
"self.radius): for y in range(self.y - self.radius, self.y + self.radius):",
"missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile, [m, e]) def update_missile (self,",
"self).delete() class Bait (Building): sym = Heart.sym color = tcod.pink",
"radius def render (self): for x in range(self.x - self.radius,",
"preferred_targets: _d, target = sorted(preferred_targets, key = operator.itemgetter(0))[0] elif other_targets:",
"self.x + (self.radius + 1)): for y in range(self.y -",
"self.timer = self.state.timers.start(1000, self._research) def _research (self): pass class AoeExplosion",
"= tcod.red class Building (util.Entity): sym = '@' max_hp =",
"y): if e in self.state.entities: #TODO copypaste e.hurt(self.damage) e =",
"False def update (self): if not self.cooldown: # dist_min =",
"in range(self.x - (self.radius + 1), self.x + (self.radius +",
"self.cooldown = False def update (self): if not self.cooldown: #",
"self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed =",
"'*' color = tcod.dark_red def __init__ (self, radius, *args): super(AoeExplosion,",
"IceTower (Tower): damage = 0.2 color = tcod.dark_blue missile =",
"util import libtcodpy as tcod import enemies import operator class",
"1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def _shoot",
"class BasicTower (Tower): color = tcod.dark_green missile = BasicMissile cost",
"(self, radius, *args): super(AoeExplosion, self).__init__(*args) self.radius = radius def render",
"False): old_speed = target.timer.interval target.timer.interval *= 3 target.timer.time_buf *= 3",
"e in self.state.targets_towers: total_damage = sum([t.damage for t in self.state.targets_towers[e]])",
"'@' max_hp = 1 cost = 0 def __init__ (self,",
"= e preferred_targets = [] other_targets = [] for e",
"d < (self.radius + 1) and ((dist_min is None) or",
"(Missile): color = tcod.red class Building (util.Entity): sym = '@'",
"# for e in self.state.entities.enemies(): # d = util.dist(self.x, self.y,",
"- radius, target.y + radius): for e in self.state.entities.enemies(): if",
"m.y, e.x, e.y) x, y = tcod.line_step() if x is",
"None # target = None # for e in self.state.entities.enemies():",
"= False self.rollback_timer = self.state.timers.start_run_once(1000, rollback) elif getattr(self, 'rollback_timer', False):",
"color = tcod.dark_green missile = BasicMissile cost = 1 class",
"= x m.y = y class BasicTower (Tower): color =",
"= tcod.darker_red max_hp = 20 def delete (self): self.state.is_paused =",
"else: preferred_targets.append((d, e)) target = None if preferred_targets: _d, target",
"color = tcod.darker_red max_hp = 20 def delete (self): self.state.is_paused",
"= tcod.dark_orange missile = AoeMissile cost = 2 def hit",
"10 damage = 1 missile = None def __init__ (self,",
"+ (self.radius + 1)): if util.dist(self.x, self.y, x, y) <",
"self.state.entities.append(self) self.state.energy -= self.cost return self def delete (self): self.state.entities.remove(self)",
"self.state.energy > 0 self.state.entities.append(self) self.state.energy -= self.cost return self def",
"if self.mouse_over: # if True: for x in range(self.x -",
"self.y + self.radius): tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x,",
"= AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class",
"1 missile = None def __init__ (self, *args): super(Tower, self).__init__(*args)",
"= util.dist(self.x, self.y, e.x, e.y) if d < (self.radius +",
"e.y) if d < (self.radius + 1): if e in",
"def render (self): for x in range(self.x - self.radius, self.x",
"-= self.cost return self def delete (self): self.state.entities.remove(self) self.state.energy +=",
"radius, target.y + radius): for e in self.state.entities.enemies(): if (e.x,",
"preferred_targets.append((d, e)) else: other_targets.append((d, e)) else: preferred_targets.append((d, e)) target =",
"+ 1): if e in self.state.targets_towers: total_damage = sum([t.damage for",
"# target = None # for e in self.state.entities.enemies(): #",
"(self.radius + 1)): for y in range(self.y - (self.radius +",
"Building (util.Entity): sym = '@' max_hp = 1 cost =",
"self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile, [m,",
"self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed, self.update_missile, [m, e]) def update_missile",
"ResearchBuilding (Building): color = tcod.dark_sepia cost = 1 def __init__",
"(self, e): if e in self.state.entities: e.hurt(self.damage) def die (self):",
"y in range(self.y - self.radius, self.y + self.radius): tcod.console_put_char(0, x,",
"(self.radius + 1), self.y + (self.radius + 1)): if util.dist(self.x,",
"= True return super(Heart, self).delete() class Bait (Building): sym =",
"2 for x in range(target.x - radius, target.x + radius):",
"sym = '*' color = tcod.white class BasicMissile (Missile): color",
"key = operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target) def render (self):",
"1), self.x + (self.radius + 1)): for y in range(self.y",
"class BasicMissile (Missile): color = tcod.yellow class IceMissile (Missile): color",
"- (self.radius + 1), self.y + (self.radius + 1)): if",
"range(self.x - self.radius, self.x + self.radius): for y in range(self.y",
"return self def delete (self): self.state.entities.remove(self) self.state.energy += self.cost return",
"+ 1), self.x + (self.radius + 1)): for y in",
"(d < dist_min)): # dist_min = d # target =",
"= '*' color = tcod.white class BasicMissile (Missile): color =",
"die (self): if self in self.state.entities: self.delete() def put (self):",
"target.timer.interval target.timer.interval *= 3 target.timer.time_buf *= 3 target.is_debuffed = True",
"if self in self.state.entities: self.delete() def put (self): assert self.state.energy",
"def __init__ (self, *args): super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000, self._research)",
"(self): for x in range(self.x - self.radius, self.x + self.radius):",
"1), self.y + (self.radius + 1)): if util.dist(self.x, self.y, x,",
"+ radius): for y in range(target.y - radius, target.y +",
"= y class BasicTower (Tower): color = tcod.dark_green missile =",
"def rollback (): target.timer.interval = old_speed target.timer.time_buf /= 3 target.is_debuffed",
"total_damage < e.hp: preferred_targets.append((d, e)) else: other_targets.append((d, e)) else: preferred_targets.append((d,",
"self.radius, self.x + self.radius): for y in range(self.y - self.radius,",
"hurt (self, hp): self.hp -= hp if self.hp < 1:",
"super(Heart, self).delete() class Bait (Building): sym = Heart.sym color =",
"= None def __init__ (self, *args): super(Tower, self).__init__(*args) self.cooldown =",
"*= 3 target.timer.time_buf *= 3 target.is_debuffed = True def rollback",
"target.timer.interval *= 3 target.timer.time_buf *= 3 target.is_debuffed = True def",
"= None # for e in self.state.entities.enemies(): # d =",
"(self, *args): super(Building, self).__init__(*args) self.hp = self.max_hp def hurt (self,",
"20 def delete (self): self.state.is_paused = True return super(Heart, self).delete()",
"> 0 self.state.entities.append(self) self.state.energy -= self.cost return self def delete",
"= False def update (self): if not self.cooldown: # dist_min",
"delete (self): self.state.is_paused = True return super(Heart, self).delete() class Bait",
"return self class Heart (Building): sym = '&' color =",
"AoeMissile (Missile): color = tcod.red class Building (util.Entity): sym =",
"dist_min = d # target = e preferred_targets = []",
"self._shoot(target) def render (self): super(Tower, self).render() if self.mouse_over: # if",
"x in range(self.x - self.radius, self.x + self.radius): for y",
"[] for e in self.state.entities.enemies(): d = util.dist(self.x, self.y, e.x,",
"e): tcod.line_init(m.x, m.y, e.x, e.y) x, y = tcod.line_step() if",
"e.hp: preferred_targets.append((d, e)) else: other_targets.append((d, e)) else: preferred_targets.append((d, e)) target",
"(self): if not self.cooldown: # dist_min = None # target",
"super(Building, self).__init__(*args) self.hp = self.max_hp def hurt (self, hp): self.hp",
"= tcod.light_blue class AoeMissile (Missile): color = tcod.red class Building",
"_d, target = sorted(preferred_targets, key = operator.itemgetter(0))[0] elif other_targets: _d,",
"self.y, e.x, e.y) # if d < (self.radius + 1)",
"AoeMissile cost = 2 def hit (self, target): radius =",
"in self.state.entities: e.hurt(self.damage) def die (self): if self in self.state.entities:",
"m = self.missile(self.state, self.x, self.y) self.state.entities.append(m) missile_speed = 20 self.state.timers.start(missile_speed,",
"Missile (util.Entity): sym = '*' color = tcod.white class BasicMissile",
"e.hurt(self.damage) e = AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda:",
"for t in self.state.targets_towers[e]]) if total_damage < e.hp: preferred_targets.append((d, e))",
"in self.state.targets_towers[e]]) if total_damage < e.hp: preferred_targets.append((d, e)) else: other_targets.append((d,",
"flag = tcod.BKGND_SET) def _shoot (self, e): self.cooldown = True",
"if d < (self.radius + 1) and ((dist_min is None)",
"if (e.x, e.y) == (x, y): if e in self.state.entities:",
"True def rollback (): target.timer.interval = old_speed target.timer.time_buf /= 3",
"+ 1), self.y + (self.radius + 1)): if util.dist(self.x, self.y,",
"self.state.entities.enemies(): # d = util.dist(self.x, self.y, e.x, e.y) # if",
"in range(self.x - self.radius, self.x + self.radius): for y in",
"delete (self): self.state.entities.remove(self) self.state.energy += self.cost return self class Heart",
"getattr(target, 'is_debuffed', False): old_speed = target.timer.interval target.timer.interval *= 3 target.timer.time_buf",
"e.y) x, y = tcod.line_step() if x is None: self.state.entities.remove(m)",
"= AoeMissile cost = 2 def hit (self, target): radius",
"if target: self.state.targets_towers[target].append(self) self._shoot(target) def render (self): super(Tower, self).render() if",
"import util import libtcodpy as tcod import enemies import operator",
"< (self.radius + 1) and ((dist_min is None) or (d",
"(self): self.state.is_paused = True return super(Heart, self).delete() class Bait (Building):",
"class ResearchBuilding (Building): color = tcod.dark_sepia cost = 1 def",
"color = tcod.dark_blue missile = IceMissile cost = 1 def",
"3 target.timer.time_buf *= 3 target.is_debuffed = True def rollback ():",
"= radius def render (self): for x in range(self.x -",
"target = None if preferred_targets: _d, target = sorted(preferred_targets, key",
"= '@' max_hp = 1 cost = 0 def __init__",
"= 0 def __init__ (self, *args): super(Building, self).__init__(*args) self.hp =",
"= 1 def __init__ (self, *args): super(ResearchBuilding, self).__init__(*args) self.timer =",
"+ 1)): if util.dist(self.x, self.y, x, y) < (self.radius +",
"e in self.state.entities: e.hurt(self.damage) def die (self): if self in",
"self.state.entities: self.delete() def put (self): assert self.state.energy > 0 self.state.entities.append(self)",
"- (self.radius + 1), self.x + (self.radius + 1)): for",
"copypaste e.hurt(self.damage) e = AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70,",
"x is None: self.state.entities.remove(m) self.hit(e) return util.STOP else: m.x =",
"x in range(self.x - (self.radius + 1), self.x + (self.radius",
"= [] for e in self.state.entities.enemies(): d = util.dist(self.x, self.y,",
"for x in range(self.x - self.radius, self.x + self.radius): for",
"== (x, y): if e in self.state.entities: #TODO copypaste e.hurt(self.damage)",
"self.state.entities.remove(e)) class IceTower (Tower): damage = 0.2 color = tcod.dark_blue",
"self.cost return self def delete (self): self.state.entities.remove(self) self.state.energy += self.cost",
"(self, target): target.hurt(self.damage) if not getattr(target, 'is_debuffed', False): old_speed =",
"def __init__ (self, radius, *args): super(AoeExplosion, self).__init__(*args) self.radius = radius",
"<filename>towers.py<gh_stars>1-10 import util import libtcodpy as tcod import enemies import",
"(self, m, e): tcod.line_init(m.x, m.y, e.x, e.y) x, y =",
"class IceTower (Tower): damage = 0.2 color = tcod.dark_blue missile",
"10 class Tower (Building): radius = 15 max_hp = 10",
"_research (self): pass class AoeExplosion (util.Entity): sym = '*' color",
"def put (self): assert self.state.energy > 0 self.state.entities.append(self) self.state.energy -=",
"t in self.state.targets_towers[e]]) if total_damage < e.hp: preferred_targets.append((d, e)) else:",
"is None: self.state.entities.remove(m) self.hit(e) return util.STOP else: m.x = x",
"old_speed target.timer.time_buf /= 3 target.is_debuffed = False self.rollback_timer = self.state.timers.start_run_once(1000,",
"tcod.dark_red def __init__ (self, radius, *args): super(AoeExplosion, self).__init__(*args) self.radius =",
"color = tcod.pink max_hp = 10 class Tower (Building): radius",
"x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y, self.color) class AoeTower",
"self.state.targets_towers: total_damage = sum([t.damage for t in self.state.targets_towers[e]]) if total_damage",
"1 class ResearchBuilding (Building): color = tcod.dark_sepia cost = 1",
"= self.max_hp def hurt (self, hp): self.hp -= hp if",
"- radius, target.x + radius): for y in range(target.y -",
"tcod.line_step() if x is None: self.state.entities.remove(m) self.hit(e) return util.STOP else:",
"= old_speed target.timer.time_buf /= 3 target.is_debuffed = False self.rollback_timer =",
"class AoeExplosion (util.Entity): sym = '*' color = tcod.dark_red def",
"self.state.entities.enemies(): if (e.x, e.y) == (x, y): if e in",
"target.x + radius): for y in range(target.y - radius, target.y",
"cost = 1 def __init__ (self, *args): super(ResearchBuilding, self).__init__(*args) self.timer",
"e in self.state.entities: #TODO copypaste e.hurt(self.damage) e = AoeExplosion(radius, self.state,",
"color = tcod.yellow class IceMissile (Missile): color = tcod.light_blue class",
"1 def __init__ (self, *args): super(ResearchBuilding, self).__init__(*args) self.timer = self.state.timers.start(1000,",
"(e.x, e.y) == (x, y): if e in self.state.entities: #TODO",
"(): self.cooldown = False self.state.timers.start_run_once(1000, clear_cd) m = self.missile(self.state, self.x,",
"def update (self): if not self.cooldown: # dist_min = None",
"e)) else: preferred_targets.append((d, e)) target = None if preferred_targets: _d,",
"tcod.light_blue class AoeMissile (Missile): color = tcod.red class Building (util.Entity):",
"self in self.state.entities: self.delete() def put (self): assert self.state.energy >",
"tcod.dark_blue missile = IceMissile cost = 1 def hit (self,",
"= tcod.dark_blue missile = IceMissile cost = 1 def hit",
"damage = 1 missile = None def __init__ (self, *args):",
"max_hp = 1 cost = 0 def __init__ (self, *args):",
"tcod.dark_sepia cost = 1 def __init__ (self, *args): super(ResearchBuilding, self).__init__(*args)",
"if d < (self.radius + 1): if e in self.state.targets_towers:",
"self).render() if self.mouse_over: # if True: for x in range(self.x",
"e): self.cooldown = True def clear_cd (): self.cooldown = False",
"tcod.line_init(m.x, m.y, e.x, e.y) x, y = tcod.line_step() if x",
"super(Tower, self).__init__(*args) self.cooldown = False def update (self): if not",
"m, e): tcod.line_init(m.x, m.y, e.x, e.y) x, y = tcod.line_step()",
"damage = 0.2 color = tcod.dark_blue missile = IceMissile cost",
"def _research (self): pass class AoeExplosion (util.Entity): sym = '*'",
"tcod.Color(*[15]*3), flag = tcod.BKGND_SET) def _shoot (self, e): self.cooldown =",
"(self.radius + 1), self.x + (self.radius + 1)): for y",
"render (self): for x in range(self.x - self.radius, self.x +",
"hp if self.hp < 1: self.die() def hit (self, e):",
"x, y, self.color) class AoeTower (Tower): color = tcod.dark_orange missile",
"if not getattr(target, 'is_debuffed', False): old_speed = target.timer.interval target.timer.interval *=",
"= target.timer.interval target.timer.interval *= 3 target.timer.time_buf *= 3 target.is_debuffed =",
"- self.radius, self.x + self.radius): for y in range(self.y -",
"*args): super(Building, self).__init__(*args) self.hp = self.max_hp def hurt (self, hp):",
"= self.state.timers.start(1000, self._research) def _research (self): pass class AoeExplosion (util.Entity):",
"range(target.x - radius, target.x + radius): for y in range(target.y",
"super(AoeExplosion, self).__init__(*args) self.radius = radius def render (self): for x",
"not self.cooldown: # dist_min = None # target = None",
"target.y + radius): for e in self.state.entities.enemies(): if (e.x, e.y)",
"for y in range(self.y - (self.radius + 1), self.y +",
"in range(target.y - radius, target.y + radius): for e in",
"(): target.timer.interval = old_speed target.timer.time_buf /= 3 target.is_debuffed = False",
"= tcod.dark_red def __init__ (self, radius, *args): super(AoeExplosion, self).__init__(*args) self.radius",
"None) or (d < dist_min)): # dist_min = d #",
"color = tcod.dark_sepia cost = 1 def __init__ (self, *args):",
"AoeExplosion(radius, self.state, target.x, target.y) self.state.entities.append(e) self.state.timers.start_run_once(70, lambda: self.state.entities.remove(e)) class IceTower",
"None if preferred_targets: _d, target = sorted(preferred_targets, key = operator.itemgetter(0))[0]",
"radius): for y in range(target.y - radius, target.y + radius):",
"d = util.dist(self.x, self.y, e.x, e.y) if d < (self.radius",
"sum([t.damage for t in self.state.targets_towers[e]]) if total_damage < e.hp: preferred_targets.append((d,",
"= None # target = None # for e in",
"not getattr(target, 'is_debuffed', False): old_speed = target.timer.interval target.timer.interval *= 3",
"self.cooldown = True def clear_cd (): self.cooldown = False self.state.timers.start_run_once(1000,",
"self._research) def _research (self): pass class AoeExplosion (util.Entity): sym =",
"(self): if self in self.state.entities: self.delete() def put (self): assert",
"operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target) def render (self): super(Tower, self).render()",
"+ 1)): for y in range(self.y - (self.radius + 1),",
"[] other_targets = [] for e in self.state.entities.enemies(): d =",
"= operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target) def render (self): super(Tower,",
"= tcod.line_step() if x is None: self.state.entities.remove(m) self.hit(e) return util.STOP",
"< dist_min)): # dist_min = d # target = e",
"-= hp if self.hp < 1: self.die() def hit (self,",
"color = tcod.red class Building (util.Entity): sym = '@' max_hp",
"y) < (self.radius + 1): tcod.console_set_char_background(0, x, y, tcod.Color(*[15]*3), flag",
"*= 3 target.is_debuffed = True def rollback (): target.timer.interval =",
"range(self.y - self.radius, self.y + self.radius): tcod.console_put_char(0, x, y, self.sym,",
"= 1 cost = 0 def __init__ (self, *args): super(Building,",
"put (self): assert self.state.energy > 0 self.state.entities.append(self) self.state.energy -= self.cost",
"y, self.color) class AoeTower (Tower): color = tcod.dark_orange missile =",
"e.y) == (x, y): if e in self.state.entities: #TODO copypaste",
"range(target.y - radius, target.y + radius): for e in self.state.entities.enemies():",
"< e.hp: preferred_targets.append((d, e)) else: other_targets.append((d, e)) else: preferred_targets.append((d, e))",
"= sorted(other_targets, key = operator.itemgetter(0))[0] if target: self.state.targets_towers[target].append(self) self._shoot(target) def",
"+ self.radius): tcod.console_put_char(0, x, y, self.sym, tcod.BKGND_NONE) tcod.console_set_char_foreground(0, x, y,",
"e): if e in self.state.entities: e.hurt(self.damage) def die (self): if",
"(Missile): color = tcod.yellow class IceMissile (Missile): color = tcod.light_blue"
] |
[
"= (y - (W / 4)) / (W / 4)",
"abs(c) > 2: return get_colors(i) c = c * c",
"c + cc return 0,0,0 if __name__ == \"__main__\": img",
"if abs(c) > 2: return get_colors(i) c = c *",
"1000): if abs(c) > 2: return get_colors(i) c = c",
"0.5)) return tuple(color.astype(int)) c, cc = 0, complex(x, y) for",
"#W=142 def mandelbrot(x, y): def get_colors(i): color = 255 *",
"__name__ == \"__main__\": img = Image.new(\"RGB\", (W, int(W / 2)))",
"pixels = img.load() for x in tqdm(range(img.size[0])): for y in",
"def mandelbrot(x, y): def get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i",
"in tqdm(range(img.size[1])): xx = (x - (0.75 * W)) /",
"x in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx = (x",
"cc return 0,0,0 if __name__ == \"__main__\": img = Image.new(\"RGB\",",
"import complex, array from tqdm import tqdm import colorsys W=512",
"range(1, 1000): if abs(c) > 2: return get_colors(i) c =",
"if __name__ == \"__main__\": img = Image.new(\"RGB\", (W, int(W /",
"c, cc = 0, complex(x, y) for i in range(1,",
"mandelbrot(x, y): def get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i /",
"4)) / (W / 4) pixels[x, y] = mandelbrot(xx, yy)",
"import Image from numpy import complex, array from tqdm import",
"255.0, 1.0, 0.5)) return tuple(color.astype(int)) c, cc = 0, complex(x,",
"= img.load() for x in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])):",
"= c * c + cc return 0,0,0 if __name__",
"y in tqdm(range(img.size[1])): xx = (x - (0.75 * W))",
"255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int)) c,",
"complex(x, y) for i in range(1, 1000): if abs(c) >",
"/ 4)) / (W / 4) pixels[x, y] = mandelbrot(xx,",
"cc = 0, complex(x, y) for i in range(1, 1000):",
"* array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int)) c, cc",
"colorsys W=512 #W=142 def mandelbrot(x, y): def get_colors(i): color =",
"(W / 4) pixels[x, y] = mandelbrot(xx, yy) img.show() img.save(\"mandelbrot.jpg\")",
"/ 4) yy = (y - (W / 4)) /",
"from tqdm import tqdm import colorsys W=512 #W=142 def mandelbrot(x,",
"array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int)) c, cc =",
"/ (W / 4) yy = (y - (W /",
"i in range(1, 1000): if abs(c) > 2: return get_colors(i)",
"return get_colors(i) c = c * c + cc return",
"1.0, 0.5)) return tuple(color.astype(int)) c, cc = 0, complex(x, y)",
"for x in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx =",
"tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx = (x - (0.75",
"def get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0,",
"> 2: return get_colors(i) c = c * c +",
"color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return",
"0, complex(x, y) for i in range(1, 1000): if abs(c)",
"/ (W / 4) pixels[x, y] = mandelbrot(xx, yy) img.show()",
"img.load() for x in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx",
"from numpy import complex, array from tqdm import tqdm import",
"in tqdm(range(img.size[0])): for y in tqdm(range(img.size[1])): xx = (x -",
"W)) / (W / 4) yy = (y - (W",
"(W / 4) yy = (y - (W / 4))",
"return 0,0,0 if __name__ == \"__main__\": img = Image.new(\"RGB\", (W,",
"import colorsys W=512 #W=142 def mandelbrot(x, y): def get_colors(i): color",
"2))) pixels = img.load() for x in tqdm(range(img.size[0])): for y",
"0,0,0 if __name__ == \"__main__\": img = Image.new(\"RGB\", (W, int(W",
"in range(1, 1000): if abs(c) > 2: return get_colors(i) c",
"c * c + cc return 0,0,0 if __name__ ==",
"y): def get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i / 255.0,",
"(x - (0.75 * W)) / (W / 4) yy",
"4) yy = (y - (W / 4)) / (W",
"(0.75 * W)) / (W / 4) yy = (y",
"/ 255.0, 1.0, 0.5)) return tuple(color.astype(int)) c, cc = 0,",
"= Image.new(\"RGB\", (W, int(W / 2))) pixels = img.load() for",
"= 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int))",
"2: return get_colors(i) c = c * c + cc",
"int(W / 2))) pixels = img.load() for x in tqdm(range(img.size[0])):",
"numpy import complex, array from tqdm import tqdm import colorsys",
"tuple(color.astype(int)) c, cc = 0, complex(x, y) for i in",
"- (W / 4)) / (W / 4) pixels[x, y]",
"get_colors(i) c = c * c + cc return 0,0,0",
"W=512 #W=142 def mandelbrot(x, y): def get_colors(i): color = 255",
"array from tqdm import tqdm import colorsys W=512 #W=142 def",
"- (0.75 * W)) / (W / 4) yy =",
"for i in range(1, 1000): if abs(c) > 2: return",
"y) for i in range(1, 1000): if abs(c) > 2:",
"complex, array from tqdm import tqdm import colorsys W=512 #W=142",
"get_colors(i): color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5))",
"PIL import Image from numpy import complex, array from tqdm",
"Image.new(\"RGB\", (W, int(W / 2))) pixels = img.load() for x",
"(y - (W / 4)) / (W / 4) pixels[x,",
"from PIL import Image from numpy import complex, array from",
"xx = (x - (0.75 * W)) / (W /",
"img = Image.new(\"RGB\", (W, int(W / 2))) pixels = img.load()",
"(W / 4)) / (W / 4) pixels[x, y] =",
"(W, int(W / 2))) pixels = img.load() for x in",
"= (x - (0.75 * W)) / (W / 4)",
"= 0, complex(x, y) for i in range(1, 1000): if",
"yy = (y - (W / 4)) / (W /",
"for y in tqdm(range(img.size[1])): xx = (x - (0.75 *",
"\"__main__\": img = Image.new(\"RGB\", (W, int(W / 2))) pixels =",
"== \"__main__\": img = Image.new(\"RGB\", (W, int(W / 2))) pixels",
"return tuple(color.astype(int)) c, cc = 0, complex(x, y) for i",
"* W)) / (W / 4) yy = (y -",
"+ cc return 0,0,0 if __name__ == \"__main__\": img =",
"tqdm import tqdm import colorsys W=512 #W=142 def mandelbrot(x, y):",
"Image from numpy import complex, array from tqdm import tqdm",
"import tqdm import colorsys W=512 #W=142 def mandelbrot(x, y): def",
"* c + cc return 0,0,0 if __name__ == \"__main__\":",
"tqdm import colorsys W=512 #W=142 def mandelbrot(x, y): def get_colors(i):",
"tqdm(range(img.size[1])): xx = (x - (0.75 * W)) / (W",
"c = c * c + cc return 0,0,0 if",
"#!/usr/bin/python3 from PIL import Image from numpy import complex, array",
"/ 2))) pixels = img.load() for x in tqdm(range(img.size[0])): for"
] |
[
"test_utils.io import catch_stdout @pytest.fixture def sleep(patch): return patch('time.sleep') @pytest.fixture def",
"assert all(var >= 0 for var in (deploying, inspecting, push_skip))",
"process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status':",
"= { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=False,",
"') pod_connect = output.find('Connecting to pod...') if did_push: assert all(var",
"verify that kubectl commands are specifying namespace for call_args in",
"2.0 (the \"License\"); # you may not use this file",
"@pytest.fixture def sleep(patch): return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg',",
"else: assert all(var == -1 for var in (pushing, pushed))",
"'--skip-crd-check': True, '--no-push': False}) deploy_cmd.config = {'name': 'app', 'namespace': 'namespace'}",
"if did_push: assert all(var >= 0 for var in (",
"'bar'}]} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>':",
"walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch): return patch('yaml.load')",
"interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template,",
"patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def",
"patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch):",
"-*- # # Copyright (c) 2018 Intel Corporation # #",
"push') deploying = output.find('Deploying ') inspecting = output.find('Inspect created objects",
"\"--namespace\" in command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple) assert len(call_args[0]) > 0 command",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"pod_connect > inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"<reponame>tonyreina/mlt # # -*- coding: utf-8 -*- # # Copyright",
"'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as caught_output: deploy.action() output",
"Intel Corporation # # Licensed under the Apache License, Version",
"@pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return patch('open')",
"kubectl commands are specifying namespace for call_args in process_helpers.run_popen.call_args_list: assert",
"fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture",
"[{'foo': 'bar'}]} with pytest.raises(ValueError): output = deploy( no_push=False, skip_crd_check=True, interactive=True,",
"'Running'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]}",
"we got the normal output, followed by the error message",
"all(var >= 0 for var in (output_location, error_location)) assert output_location",
"created objects by running:\\n') pushed = output.find('Pushed to ') pod_connect",
"all(var >= 0 for var in (deploying, inspecting, push_skip)) assert",
"assert isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple) assert len(call_args[0]) > 0",
"output.find(error_str) assert all(var >= 0 for var in (output_location, error_location))",
"did_push=True, interactive=False): \"\"\"assert pushing, deploying, then objs created, then pushed\"\"\"",
"\"\"\"assert pushing, deploying, then objs created, then pushed\"\"\" pushing =",
"push_skip = output.find('Skipping image push') deploying = output.find('Deploying ') inspecting",
"yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Error'}} yaml.return_value = {",
"'gcr://projectfoo'}) with catch_stdout() as caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output =",
"= 1 output_str = \"normal output...\" error_str = \"error message...\"",
"command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"use this file except in compliance with the License. #",
"DeployCommand from test_utils.io import catch_stdout @pytest.fixture def sleep(patch): return patch('time.sleep')",
"error_str = \"error message...\" build_output = MagicMock() build_output.decode.return_value = output_str",
"verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Error'}}",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"output...\" error_str = \"error message...\" build_output = MagicMock() build_output.decode.return_value =",
"sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Running'}} yaml.return_value =",
"License. # You may obtain a copy of the License",
"output_location = output.find(output_str) error_location = output.find(error_str) assert all(var >= 0",
"error_location = output.find(error_str) assert all(var >= 0 for var in",
"verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def",
"{'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} output = deploy( no_push=False, skip_crd_check=True,",
"json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock, progress_bar, popen_mock,",
"{'status': {'phase': 'Error'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers':",
"under the License is distributed on an \"AS IS\" BASIS,",
"output.find('Connecting to pod...') if did_push: assert all(var >= 0 for",
"{ 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup mock to induce",
"License for the specific language governing permissions and # limitations",
"import print_function import uuid import pytest from mock import call,",
"def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo',",
"deploy = DeployCommand( {'deploy': True, '--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive':",
"'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"deploy.config = {'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as",
"< inspecting, pushing < pushed else: assert all(var == -1",
"(build_output, error_output) deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push': False})",
"'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4()) json_mock_data = {",
"var in (pushing, pushed)) assert all(var >= 0 for var",
"deploy popen_mock.return_value.poll.return_value = 1 output_str = \"normal output...\" error_str =",
"= str(uuid.uuid4()) json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value",
"popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check': True,",
"push_skip)) assert push_skip < deploying, deploying < inspecting if interactive:",
"kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def",
"1 output_str = \"normal output...\" error_str = \"error message...\" build_output",
"limitations under the License. # # SPDX-License-Identifier: EPL-2.0 # from",
"def yaml(patch): return patch('yaml.load') def deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5):",
"json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output =",
"DeployCommand( {'deploy': True, '--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries':",
"# setup mock to induce and error during the deploy",
"error_output = MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value = (build_output, error_output)",
"pushing, deploying, then objs created, then pushed\"\"\" pushing = output.find('Pushing",
"assert all(var == -1 for var in (pushing, pushed)) assert",
"in compliance with the License. # You may obtain a",
"return patch('yaml.load') def deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5): deploy =",
"var in (deploying, inspecting, push_skip)) assert push_skip < deploying, deploying",
"output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'})",
"software # distributed under the License is distributed on an",
"progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect = lambda x, y, z:",
"= MagicMock() build_output.decode.return_value = output_str error_output = MagicMock() error_output.decode.return_value =",
"> inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"= error_str popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd = DeployCommand({'deploy': True,",
"'--logs':False}) deploy.config = {'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout()",
"no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock):",
"pytest from mock import call, MagicMock from mlt.commands.deploy import DeployCommand",
"return patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def popen_mock(patch):",
"verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"utf-8 -*- # # Copyright (c) 2018 Intel Corporation #",
"deploying, deploying < inspecting if interactive: assert pod_connect > inspecting",
"pushed)) assert deploying < inspecting, pushing < pushed else: assert",
"{ 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value = {'status':",
"mlt.commands.deploy import DeployCommand from test_utils.io import catch_stdout @pytest.fixture def sleep(patch):",
"') return patch('progress_bar', progress_mock) @pytest.fixture def template(patch): return patch('Template') @pytest.fixture",
"fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} #",
"# verify that kubectl commands are specifying namespace for call_args",
"error_output) deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push': False}) deploy_cmd.config",
"normal output, followed by the error message output_location = output.find(output_str)",
"'containers': [{'foo': 'bar'}]} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry':",
"return patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect =",
"verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value = ['foo'] yaml.return_value",
"deploy_cmd.action() output = caught_output.getvalue() # assert that we got the",
"followed by the error message output_location = output.find(output_str) error_location =",
"return patch('progress_bar', progress_mock) @pytest.fixture def template(patch): return patch('Template') @pytest.fixture def",
"with pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue() # assert that we",
"test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"@pytest.fixture def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch):",
"interactive: assert pod_connect > inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock,",
"popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value",
"@pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return patch('json')",
"pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue() # assert that we got",
"by the error message output_location = output.find(output_str) error_location = output.find(error_str)",
"test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"that kubectl commands are specifying namespace for call_args in process_helpers.run_popen.call_args_list:",
"no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def",
"'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject':",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd =",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"output.find(output_str) error_location = output.find(error_str) assert all(var >= 0 for var",
"MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch): return patch('yaml.load') def deploy(no_push, skip_crd_check,",
"verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase':",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"verify_init, fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889}",
"to in writing, software # distributed under the License is",
"interactive, '--retries': retries, '--logs':False}) deploy.config = {'name': 'app', 'namespace': 'namespace'}",
"verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"output, followed by the error message output_location = output.find(output_str) error_location",
"# See the License for the specific language governing permissions",
"(deploying, inspecting, push_skip)) assert push_skip < deploying, deploying < inspecting",
"language governing permissions and # limitations under the License. #",
"objs created, then pushed\"\"\" pushing = output.find('Pushing ') push_skip =",
"progress_mock.duration_progress.side_effect = lambda x, y, z: print( 'Pushing ') return",
"or agreed to in writing, software # distributed under the",
"'bar'])) @pytest.fixture def yaml(patch): return patch('yaml.load') def deploy(no_push, skip_crd_check, interactive,",
"required by applicable law or agreed to in writing, software",
"call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple) assert",
"error during the deploy popen_mock.return_value.poll.return_value = 1 output_str = \"normal",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"{ 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError): output",
"( deploying, inspecting, pushing, pushed)) assert deploying < inspecting, pushing",
"with the License. # You may obtain a copy of",
"progress_mock = MagicMock() progress_mock.duration_progress.side_effect = lambda x, y, z: print(",
"def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers')",
"'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id']",
"test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4()) json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id',",
"import DeployCommand from test_utils.io import catch_stdout @pytest.fixture def sleep(patch): return",
"error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd = DeployCommand({'deploy':",
"= { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup mock to",
"{'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as caught_output: deploy.action()",
"'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'})",
"verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Running'}}",
"'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id",
"patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect = lambda",
"compliance with the License. # You may obtain a copy",
"{'deploy': True, '--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries': retries,",
"'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as caught_output: with",
"agreed to in writing, software # distributed under the License",
"y, z: print( 'Pushing ') return patch('progress_bar', progress_mock) @pytest.fixture def",
"error message output_location = output.find(output_str) error_location = output.find(error_str) assert all(var",
"popen_mock.return_value.poll.return_value = 1 output_str = \"normal output...\" error_str = \"error",
"assert len(call_args[0]) > 0 command = call_args[0][0] if command[0] ==",
"def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture",
"popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml,",
"distributed under the License is distributed on an \"AS IS\"",
"process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple) assert len(call_args[0]) >",
"== \"kubectl\": assert \"--namespace\" in command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock,",
"deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock,",
"pytest.raises(ValueError): output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>':",
"\"normal output...\" error_str = \"error message...\" build_output = MagicMock() build_output.decode.return_value",
"test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"express or implied. # See the License for the specific",
"extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"{'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as caught_output:",
"except in compliance with the License. # You may obtain",
"deploying = output.find('Deploying ') inspecting = output.find('Inspect created objects by",
"the deploy popen_mock.return_value.poll.return_value = 1 output_str = \"normal output...\" error_str",
"= {'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as caught_output:",
"output def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing, deploying, then objs",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch):",
"not use this file except in compliance with the License.",
"MagicMock() build_output.decode.return_value = output_str error_output = MagicMock() error_output.decode.return_value = error_str",
"0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id def",
"True, '--skip-crd-check': True, '--no-push': False}) deploy_cmd.config = {'name': 'app', 'namespace':",
"= MagicMock() popen_mock.return_value.poll.return_value = 0 return patch('Popen', popen_mock) @pytest.fixture def",
"= output.find('Deploying ') inspecting = output.find('Inspect created objects by running:\\n')",
"interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template,",
"writing, software # distributed under the License is distributed on",
"deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar,",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch):",
"'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as caught_output: with pytest.raises(SystemExit):",
"{'status': {'phase': 'Running'}} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry':",
"return output def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing, deploying, then",
"skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock,",
"'bar'}]} with pytest.raises(ValueError): output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry':",
"[{'foo': 'bar'}]} json_mock.loads.return_value = {'status': {'phase': 'Running'}} output = deploy(",
"deploying < inspecting, pushing < pushed else: assert all(var ==",
"@pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return",
"yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value",
"'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value = {'status': {'phase': 'Running'}} output",
"def popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value = 0 return patch('Popen',",
"print( 'Pushing ') return patch('progress_bar', progress_mock) @pytest.fixture def template(patch): return",
"pushing, pushed)) assert deploying < inspecting, pushing < pushed else:",
"'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} output = deploy( no_push=False,",
"interactive, extra_config_args, retries=5): deploy = DeployCommand( {'deploy': True, '--no-push': no_push,",
"0 for var in (deploying, inspecting, push_skip)) assert push_skip <",
"yaml, json_mock): walk_mock.return_value = ['foo'] yaml.return_value = { 'template': {'foo':",
"output.find('Inspect created objects by running:\\n') pushed = output.find('Pushed to ')",
"if interactive: assert pod_connect > inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock,",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template,",
"open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value =",
"process_helpers, verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id',",
"= { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=True,",
"def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"deploying < inspecting if interactive: assert pod_connect > inspecting def",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"0 for var in ( deploying, inspecting, pushing, pushed)) assert",
"def template(patch): return patch('Template') @pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture",
"'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False,",
"deploy.action() output = caught_output.getvalue() return output def verify_successful_deploy(output, did_push=True, interactive=False):",
"= {'status': {'phase': 'Error'}} yaml.return_value = { 'template': {'foo': 'bar'},",
"def deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5): deploy = DeployCommand( {'deploy':",
"< inspecting if interactive: assert pod_connect > inspecting def test_deploy_gce(walk_mock,",
"template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value = {",
"from test_utils.io import catch_stdout @pytest.fixture def sleep(patch): return patch('time.sleep') @pytest.fixture",
"for var in (pushing, pushed)) assert all(var >= 0 for",
"@pytest.fixture def process_helpers(patch): return patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock =",
"all(var >= 0 for var in ( deploying, inspecting, pushing,",
"with catch_stdout() as caught_output: deploy.action() output = caught_output.getvalue() return output",
"{'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value = {'status': {'phase': 'Running'}}",
"EPL-2.0 # from __future__ import print_function import uuid import pytest",
"from mlt.commands.deploy import DeployCommand from test_utils.io import catch_stdout @pytest.fixture def",
"@pytest.fixture def yaml(patch): return patch('yaml.load') def deploy(no_push, skip_crd_check, interactive, extra_config_args,",
"interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock,",
"json_mock.loads.return_value = {'status': {'phase': 'Error'}} yaml.return_value = { 'template': {'foo':",
"skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id",
"def test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4()) json_mock_data = { 'last_remote_container':",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"catch_stdout @pytest.fixture def sleep(patch): return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return",
"and error during the deploy popen_mock.return_value.poll.return_value = 1 output_str =",
"assert that we got the normal output, followed by the",
"inspecting, push_skip)) assert push_skip < deploying, deploying < inspecting if",
"the License is distributed on an \"AS IS\" BASIS, #",
"yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Running'}} yaml.return_value = {",
"'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry':",
"pod_connect = output.find('Connecting to pod...') if did_push: assert all(var >=",
"with catch_stdout() as caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue()",
"'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'})",
"json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup",
"extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"retries, '--logs':False}) deploy.config = {'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args) with",
"= output.find('Skipping image push') deploying = output.find('Deploying ') inspecting =",
"popen_mock.return_value.poll.return_value = 0 return patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch): return",
"'containers': [{'foo': 'bar'}]} json_mock.loads.return_value = {'status': {'phase': 'Running'}} output =",
"process_helpers(patch): return patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect",
"pushed\"\"\" pushing = output.find('Pushing ') push_skip = output.find('Skipping image push')",
"output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def",
"# limitations under the License. # # SPDX-License-Identifier: EPL-2.0 #",
"mock import call, MagicMock from mlt.commands.deploy import DeployCommand from test_utils.io",
"= ['foo'] yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo':",
"commands are specifying namespace for call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args,",
"law or agreed to in writing, software # distributed under",
"verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing, deploying, then objs created, then",
"'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError): output = deploy( no_push=False, skip_crd_check=True,",
"# assert that we got the normal output, followed by",
"inspecting = output.find('Inspect created objects by running:\\n') pushed = output.find('Pushed",
"def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"created, then pushed\"\"\" pushing = output.find('Pushing ') push_skip = output.find('Skipping",
"@pytest.fixture def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return patch('os.walk',",
"kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container':",
"2018 Intel Corporation # # Licensed under the Apache License,",
"Copyright (c) 2018 Intel Corporation # # Licensed under the",
"def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify that kubectl commands",
"pod...') if did_push: assert all(var >= 0 for var in",
"{'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError): output = deploy(",
"deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify",
"= output_str error_output = MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value =",
"{'phase': 'Error'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo':",
"var in ( deploying, inspecting, pushing, pushed)) assert deploying <",
"may obtain a copy of the License at # #",
"patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def popen_mock(patch): popen_mock",
"patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch): return patch('process_helpers') @pytest.fixture def progress_bar(patch):",
"progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, json_mock):",
"== run_id def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"caught_output: deploy.action() output = caught_output.getvalue() return output def verify_successful_deploy(output, did_push=True,",
"patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch): return patch('yaml.load') def deploy(no_push,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"in ( deploying, inspecting, pushing, pushed)) assert deploying < inspecting,",
"return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def",
"0.18889} # setup mock to induce and error during the",
"may not use this file except in compliance with the",
"skip_crd_check, interactive, extra_config_args, retries=5): deploy = DeployCommand( {'deploy': True, '--no-push':",
"no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock,",
"open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock):",
"did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify that",
"json_mock): json_mock.loads.return_value = {'status': {'phase': 'Running'}} yaml.return_value = { 'template':",
"return patch('open') @pytest.fixture def popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup mock",
"assert \"--namespace\" in command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template,",
"all(var == -1 for var in (pushing, pushed)) assert all(var",
"the error message output_location = output.find(output_str) error_location = output.find(error_str) assert",
"this file except in compliance with the License. # You",
"DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push': False}) deploy_cmd.config = {'name': 'app',",
"yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} with",
"pushed else: assert all(var == -1 for var in (pushing,",
"yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} output",
"output.find('Pushed to ') pod_connect = output.find('Connecting to pod...') if did_push:",
"pushed)) assert all(var >= 0 for var in (deploying, inspecting,",
"> 0 command = call_args[0][0] if command[0] == \"kubectl\": assert",
"def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"= output.find('Connecting to pod...') if did_push: assert all(var >= 0",
"popen_mock) @pytest.fixture def process_helpers(patch): return patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock",
"kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value =",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"inspecting, pushing, pushed)) assert deploying < inspecting, pushing < pushed",
"json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data",
">= 0 for var in (deploying, inspecting, push_skip)) assert push_skip",
"deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True)",
"# # Licensed under the Apache License, Version 2.0 (the",
"# SPDX-License-Identifier: EPL-2.0 # from __future__ import print_function import uuid",
"# Copyright (c) 2018 Intel Corporation # # Licensed under",
"= { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError):",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"# # SPDX-License-Identifier: EPL-2.0 # from __future__ import print_function import",
"return patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch): return patch('process_helpers') @pytest.fixture def",
"running:\\n') pushed = output.find('Pushed to ') pod_connect = output.find('Connecting to",
"pushing < pushed else: assert all(var == -1 for var",
"verify_build, verify_init, fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration':",
"interactive=False): \"\"\"assert pushing, deploying, then objs created, then pushed\"\"\" pushing",
"{'status': {'phase': 'Running'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers':",
"json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock,",
"during the deploy popen_mock.return_value.poll.return_value = 1 output_str = \"normal output...\"",
"for var in (deploying, inspecting, push_skip)) assert push_skip < deploying,",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"patch('yaml.load') def deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5): deploy = DeployCommand(",
"test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"'--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries': retries, '--logs':False}) deploy.config = {'name':",
"'--retries': retries, '--logs':False}) deploy.config = {'name': 'app', 'namespace': 'namespace'} deploy.config.update(extra_config_args)",
"-*- coding: utf-8 -*- # # Copyright (c) 2018 Intel",
"fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Error'}} yaml.return_value",
"pushed = output.find('Pushed to ') pod_connect = output.find('Connecting to pod...')",
"popen_mock = MagicMock() popen_mock.return_value.poll.return_value = 0 return patch('Popen', popen_mock) @pytest.fixture",
"'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"to induce and error during the deploy popen_mock.return_value.poll.return_value = 1",
"= { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id)",
"kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value =",
"'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4()) json_mock_data",
"patch('progress_bar', progress_mock) @pytest.fixture def template(patch): return patch('Template') @pytest.fixture def verify_build(patch):",
"in (deploying, inspecting, push_skip)) assert push_skip < deploying, deploying <",
"walk_mock.return_value = ['foo'] yaml.return_value = { 'template': {'foo': 'bar'}, 'containers':",
"def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"template(patch): return patch('Template') @pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def",
"return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch):",
"progress_mock) @pytest.fixture def template(patch): return patch('Template') @pytest.fixture def verify_build(patch): return",
"patch('Template') @pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return",
"for call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple)",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"type(call)) assert isinstance(call_args[0], tuple) assert len(call_args[0]) > 0 command =",
"deploy.config.update(extra_config_args) with catch_stdout() as caught_output: deploy.action() output = caught_output.getvalue() return",
"open_mock(patch): return patch('open') @pytest.fixture def popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value",
"\"error message...\" build_output = MagicMock() build_output.decode.return_value = output_str error_output =",
"= output.find(error_str) assert all(var >= 0 for var in (output_location,",
"assert all(var >= 0 for var in ( deploying, inspecting,",
">= 0 for var in ( deploying, inspecting, pushing, pushed))",
"to ') pod_connect = output.find('Connecting to pod...') if did_push: assert",
"= 0 return patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch): return patch('process_helpers')",
"License. # # SPDX-License-Identifier: EPL-2.0 # from __future__ import print_function",
"def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing, deploying, then objs created,",
"True, '--no-push': False}) deploy_cmd.config = {'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject':",
"or implied. # See the License for the specific language",
"assert deploying < inspecting, pushing < pushed else: assert all(var",
"output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"# -*- coding: utf-8 -*- # # Copyright (c) 2018",
"json_mock): walk_mock.return_value = ['foo'] yaml.return_value = { 'template': {'foo': 'bar'},",
"retries=5): deploy = DeployCommand( {'deploy': True, '--no-push': no_push, '--skip-crd-check': skip_crd_check,",
"coding: utf-8 -*- # # Copyright (c) 2018 Intel Corporation",
"push_skip < deploying, deploying < inspecting if interactive: assert pod_connect",
"= { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} output =",
"= deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) #",
"deploy_cmd.config = {'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout()",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"message output_location = output.find(output_str) error_location = output.find(error_str) assert all(var >=",
"for var in ( deploying, inspecting, pushing, pushed)) assert deploying",
"then objs created, then pushed\"\"\" pushing = output.find('Pushing ') push_skip",
"from mock import call, MagicMock from mlt.commands.deploy import DeployCommand from",
"patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return",
"in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert isinstance(call_args[0], tuple) assert len(call_args[0])",
"interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar,",
"no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar,",
"mock to induce and error during the deploy popen_mock.return_value.poll.return_value =",
"output.find('Deploying ') inspecting = output.find('Inspect created objects by running:\\n') pushed",
"(pushing, pushed)) assert all(var >= 0 for var in (deploying,",
"as caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue() # assert",
"extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4())",
"@pytest.fixture def popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value = 0 return",
"-1 for var in (pushing, pushed)) assert all(var >= 0",
"(the \"License\"); # you may not use this file except",
"MagicMock from mlt.commands.deploy import DeployCommand from test_utils.io import catch_stdout @pytest.fixture",
"patch('open') @pytest.fixture def popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value = 0",
"run_id = str(uuid.uuid4()) json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889}",
"[{'foo': 'bar'}]} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub',",
"= {'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as",
"# you may not use this file except in compliance",
"output.find('Skipping image push') deploying = output.find('Deploying ') inspecting = output.find('Inspect",
"= { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value =",
"len(call_args[0]) > 0 command = call_args[0][0] if command[0] == \"kubectl\":",
"verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"= \"normal output...\" error_str = \"error message...\" build_output = MagicMock()",
"lambda x, y, z: print( 'Pushing ') return patch('progress_bar', progress_mock)",
"'bar'}, 'containers': [{'foo': 'bar'}]} output = deploy( no_push=False, skip_crd_check=True, interactive=True,",
"did_push: assert all(var >= 0 for var in ( deploying,",
"{'phase': 'Running'}} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'})",
"') push_skip = output.find('Skipping image push') deploying = output.find('Deploying ')",
"skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock,",
"inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"to pod...') if did_push: assert all(var >= 0 for var",
"permissions and # limitations under the License. # # SPDX-License-Identifier:",
"sleep(patch): return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture",
"output_str = \"normal output...\" error_str = \"error message...\" build_output =",
"# # Unless required by applicable law or agreed to",
"deploying, inspecting, pushing, pushed)) assert deploying < inspecting, pushing <",
"'namespace': 'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as caught_output: deploy.action() output =",
"json_mock): run_id = str(uuid.uuid4()) json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration':",
"image push') deploying = output.find('Deploying ') inspecting = output.find('Inspect created",
"by running:\\n') pushed = output.find('Pushed to ') pod_connect = output.find('Connecting",
"fetch_action_arg, json_mock): json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output",
"return patch('Template') @pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch):",
"def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture",
"json_mock.loads.return_value = {'status': {'phase': 'Running'}} yaml.return_value = { 'template': {'foo':",
"extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock,",
"'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError): output =",
"< pushed else: assert all(var == -1 for var in",
"@pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build') @pytest.fixture def verify_init(patch): return patch('config_helpers.load_config')",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"= output.find('Pushing ') push_skip = output.find('Skipping image push') deploying =",
"sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Error'}} yaml.return_value =",
"yaml(patch): return patch('yaml.load') def deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5): deploy",
"Version 2.0 (the \"License\"); # you may not use this",
"# # -*- coding: utf-8 -*- # # Copyright (c)",
"def open_mock(patch): return patch('open') @pytest.fixture def popen_mock(patch): popen_mock = MagicMock()",
"= MagicMock() progress_mock.duration_progress.side_effect = lambda x, y, z: print( 'Pushing",
"progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep,",
"implied. # See the License for the specific language governing",
"'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup mock to induce and",
"= DeployCommand( {'deploy': True, '--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive,",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value",
"{ 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} output = deploy(",
"def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture",
"inspecting if interactive: assert pod_connect > inspecting def test_deploy_gce(walk_mock, progress_bar,",
"json_mock.loads.return_value = {'status': {'phase': 'Running'}} output = deploy( no_push=False, skip_crd_check=True,",
"MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return",
"False}) deploy_cmd.config = {'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with",
"deploying, then objs created, then pushed\"\"\" pushing = output.find('Pushing ')",
"isinstance(call_args[0], tuple) assert len(call_args[0]) > 0 command = call_args[0][0] if",
"if command[0] == \"kubectl\": assert \"--namespace\" in command def test_deploy_interactive_two_files(walk_mock,",
"'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] ==",
"by applicable law or agreed to in writing, software #",
"return patch('files.fetch_action_arg', MagicMock(return_value='output')) @pytest.fixture def kube_helpers(patch): return patch('kubernetes_helpers') @pytest.fixture def",
"< deploying, deploying < inspecting if interactive: assert pod_connect >",
"= (build_output, error_output) deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push':",
"import call, MagicMock from mlt.commands.deploy import DeployCommand from test_utils.io import",
"deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output",
"fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value = ['foo'] yaml.return_value = {",
"import catch_stdout @pytest.fixture def sleep(patch): return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch):",
"from __future__ import print_function import uuid import pytest from mock",
"with pytest.raises(ValueError): output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub',",
"= {'status': {'phase': 'Running'}} output = deploy( no_push=False, skip_crd_check=True, interactive=True,",
"== -1 for var in (pushing, pushed)) assert all(var >=",
"'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=True, skip_crd_check=True, interactive=False,",
"test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"def process_helpers(patch): return patch('process_helpers') @pytest.fixture def progress_bar(patch): progress_mock = MagicMock()",
"'<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template,",
"def sleep(patch): return patch('time.sleep') @pytest.fixture def fetch_action_arg(patch): return patch('files.fetch_action_arg', MagicMock(return_value='output'))",
"\"kubectl\": assert \"--namespace\" in command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock,",
"induce and error during the deploy popen_mock.return_value.poll.return_value = 1 output_str",
"x, y, z: print( 'Pushing ') return patch('progress_bar', progress_mock) @pytest.fixture",
"= json_mock_data DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock, progress_bar,",
"def test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"command = call_args[0][0] if command[0] == \"kubectl\": assert \"--namespace\" in",
"'--no-push': False}) deploy_cmd.config = {'name': 'app', 'namespace': 'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'})",
"skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock,",
"= output.find('Inspect created objects by running:\\n') pushed = output.find('Pushed to",
"'bar'}, 'containers': [{'foo': 'bar'}]} with pytest.raises(ValueError): output = deploy( no_push=False,",
"z: print( 'Pushing ') return patch('progress_bar', progress_mock) @pytest.fixture def template(patch):",
"output = caught_output.getvalue() # assert that we got the normal",
"interactive=True) # verify that kubectl commands are specifying namespace for",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify that kubectl",
"Unless required by applicable law or agreed to in writing,",
"patch('kubernetes_helpers') @pytest.fixture def json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return",
"'namespace'} deploy.config.update(extra_config_args) with catch_stdout() as caught_output: deploy.action() output = caught_output.getvalue()",
"json_mock.load.return_value = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy(",
"SPDX-License-Identifier: EPL-2.0 # from __future__ import print_function import uuid import",
"verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"assert push_skip < deploying, deploying < inspecting if interactive: assert",
"build_output = MagicMock() build_output.decode.return_value = output_str error_output = MagicMock() error_output.decode.return_value",
"= MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd",
"the specific language governing permissions and # limitations under the",
"output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True)",
"json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"0 command = call_args[0][0] if command[0] == \"kubectl\": assert \"--namespace\"",
"'last_push_duration': 0.18889} # setup mock to induce and error during",
"applicable law or agreed to in writing, software # distributed",
">= 0 for var in (output_location, error_location)) assert output_location <",
"assert pod_connect > inspecting def test_deploy_gce(walk_mock, progress_bar, popen_mock, open_mock, template,",
"@pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def popen_mock(patch): popen_mock =",
"'last_push_duration': 0.18889} output = deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'})",
"0.18889} output = deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output,",
"0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output)",
"'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify that kubectl commands are specifying",
"0.18889} output = deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output)",
"tuple) assert len(call_args[0]) > 0 command = call_args[0][0] if command[0]",
"command[0] == \"kubectl\": assert \"--namespace\" in command def test_deploy_interactive_two_files(walk_mock, progress_bar,",
"catch_stdout() as caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue() #",
"'Pushing ') return patch('progress_bar', progress_mock) @pytest.fixture def template(patch): return patch('Template')",
"call, MagicMock from mlt.commands.deploy import DeployCommand from test_utils.io import catch_stdout",
"got the normal output, followed by the error message output_location",
"True, '--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries': retries, '--logs':False})",
"in writing, software # distributed under the License is distributed",
"governing permissions and # limitations under the License. # #",
"extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output, interactive=True) # verify that kubectl commands are",
"def progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect = lambda x, y,",
"deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar,",
"{ 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value = json_mock_data DeployCommand._update_app_run_id(run_id) assert",
"= DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push': False}) deploy_cmd.config = {'name':",
"0 for var in (output_location, error_location)) assert output_location < error_location",
"= lambda x, y, z: print( 'Pushing ') return patch('progress_bar',",
"verify_successful_deploy(output, interactive=True) # verify that kubectl commands are specifying namespace",
"assert json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template,",
"= call_args[0][0] if command[0] == \"kubectl\": assert \"--namespace\" in command",
"DeployCommand._update_app_run_id(run_id) assert json_mock_data['app_run_id'] == run_id def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock,",
"return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture",
"output = caught_output.getvalue() return output def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert",
"inspecting, pushing < pushed else: assert all(var == -1 for",
"'--interactive': interactive, '--retries': retries, '--logs':False}) deploy.config = {'name': 'app', 'namespace':",
"= deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock,",
"namespace for call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert isinstance(call_args[0],",
"@pytest.fixture def progress_bar(patch): progress_mock = MagicMock() progress_mock.duration_progress.side_effect = lambda x,",
"str(uuid.uuid4()) json_mock_data = { 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} json_mock.load.return_value =",
"verify_init(patch): return patch('config_helpers.load_config') @pytest.fixture def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar']))",
"json_mock(patch): return patch('json') @pytest.fixture def open_mock(patch): return patch('open') @pytest.fixture def",
"# from __future__ import print_function import uuid import pytest from",
"def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init,",
"= deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output,",
"build_output.decode.return_value = output_str error_output = MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value",
"that we got the normal output, followed by the error",
"'<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id = str(uuid.uuid4()) json_mock_data =",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"deploy(no_push, skip_crd_check, interactive, extra_config_args, retries=5): deploy = DeployCommand( {'deploy': True,",
"'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]} json_mock.loads.return_value = {'status': {'phase':",
"License, Version 2.0 (the \"License\"); # you may not use",
"assert isinstance(call_args[0], tuple) assert len(call_args[0]) > 0 command = call_args[0][0]",
"= caught_output.getvalue() return output def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing,",
"# You may obtain a copy of the License at",
"interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"= output.find(output_str) error_location = output.find(error_str) assert all(var >= 0 for",
"'namespace'} deploy_cmd.config.update({'gceProject': 'gcr://projectfoo'}) with catch_stdout() as caught_output: with pytest.raises(SystemExit): deploy_cmd.action()",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"catch_stdout() as caught_output: deploy.action() output = caught_output.getvalue() return output def",
"{'phase': 'Running'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo':",
"json_mock): json_mock.loads.return_value = {'status': {'phase': 'Error'}} yaml.return_value = { 'template':",
"as caught_output: deploy.action() output = caught_output.getvalue() return output def verify_successful_deploy(output,",
"under the License. # # SPDX-License-Identifier: EPL-2.0 # from __future__",
"'bar'}]} json_mock.loads.return_value = {'status': {'phase': 'Running'}} output = deploy( no_push=False,",
"@pytest.fixture def template(patch): return patch('Template') @pytest.fixture def verify_build(patch): return patch('build_helpers.verify_build')",
"the License for the specific language governing permissions and #",
"'dockerhub', '<kube_spec>': 'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock,",
"no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock,",
"{ 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=True, skip_crd_check=True,",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"assert all(var >= 0 for var in (output_location, error_location)) assert",
"either express or implied. # See the License for the",
"'Error'}} yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]}",
"(c) 2018 Intel Corporation # # Licensed under the Apache",
"MagicMock() popen_mock.return_value.poll.return_value = 0 return patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch):",
"uuid import pytest from mock import call, MagicMock from mlt.commands.deploy",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"sleep, yaml, json_mock): walk_mock.return_value = ['foo'] yaml.return_value = { 'template':",
"then pushed\"\"\" pushing = output.find('Pushing ') push_skip = output.find('Skipping image",
"caught_output.getvalue() # assert that we got the normal output, followed",
"return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch): return patch('yaml.load') def",
"pushing = output.find('Pushing ') push_skip = output.find('Skipping image push') deploying",
"0 return patch('Popen', popen_mock) @pytest.fixture def process_helpers(patch): return patch('process_helpers') @pytest.fixture",
"skip_crd_check, '--interactive': interactive, '--retries': retries, '--logs':False}) deploy.config = {'name': 'app',",
"and # limitations under the License. # # SPDX-License-Identifier: EPL-2.0",
"['foo'] yaml.return_value = { 'template': {'foo': 'bar'}, 'containers': [{'foo': 'bar'}]}",
"import pytest from mock import call, MagicMock from mlt.commands.deploy import",
"fetch_action_arg, sleep, yaml, json_mock): json_mock.loads.return_value = {'status': {'phase': 'Running'}} yaml.return_value",
"# # Copyright (c) 2018 Intel Corporation # # Licensed",
"'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} # setup mock to induce and error",
"objects by running:\\n') pushed = output.find('Pushed to ') pod_connect =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"message...\" build_output = MagicMock() build_output.decode.return_value = output_str error_output = MagicMock()",
"'r'}) verify_successful_deploy(output, interactive=True) def test_deploy_interactive_pod_not_run(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers,",
"'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"print_function import uuid import pytest from mock import call, MagicMock",
"= \"error message...\" build_output = MagicMock() build_output.decode.return_value = output_str error_output",
"are specifying namespace for call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call))",
"= deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False) def",
"') inspecting = output.find('Inspect created objects by running:\\n') pushed =",
"extra_config_args, retries=5): deploy = DeployCommand( {'deploy': True, '--no-push': no_push, '--skip-crd-check':",
"output_str error_output = MagicMock() error_output.decode.return_value = error_str popen_mock.return_value.communicate.return_value = (build_output,",
"error_str popen_mock.return_value.communicate.return_value = (build_output, error_output) deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check':",
"run_id def test_image_push_error(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build,",
"def walk_mock(patch): return patch('os.walk', MagicMock(return_value=['foo', 'bar'])) @pytest.fixture def yaml(patch): return",
"in (pushing, pushed)) assert all(var >= 0 for var in",
"= {'status': {'phase': 'Running'}} yaml.return_value = { 'template': {'foo': 'bar'},",
"test_deploy_interactive_one_file(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg,",
"__future__ import print_function import uuid import pytest from mock import",
"\"License\"); # you may not use this file except in",
"interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock, json_mock): run_id =",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject':",
"process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value = ['foo']",
"specifying namespace for call_args in process_helpers.run_popen.call_args_list: assert isinstance(call_args, type(call)) assert",
"deploy_cmd = DeployCommand({'deploy': True, '--skip-crd-check': True, '--no-push': False}) deploy_cmd.config =",
"caught_output.getvalue() return output def verify_successful_deploy(output, did_push=True, interactive=False): \"\"\"assert pushing, deploying,",
"verify_init, fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value = ['foo'] yaml.return_value =",
"# distributed under the License is distributed on an \"AS",
"deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def test_deploy_update_app_run_id(open_mock,",
"# Unless required by applicable law or agreed to in",
"popen_mock(patch): popen_mock = MagicMock() popen_mock.return_value.poll.return_value = 0 return patch('Popen', popen_mock)",
"in command def test_deploy_interactive_two_files(walk_mock, progress_bar, popen_mock, open_mock, template, kube_helpers, process_helpers,",
"the License. # # SPDX-License-Identifier: EPL-2.0 # from __future__ import",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= caught_output.getvalue() # assert that we got the normal output,",
"setup mock to induce and error during the deploy popen_mock.return_value.poll.return_value",
"MagicMock() progress_mock.duration_progress.side_effect = lambda x, y, z: print( 'Pushing ')",
"'Running'}} output = deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output,",
"= deploy( no_push=False, skip_crd_check=True, interactive=True, extra_config_args={'registry': 'dockerhub', '<kube_spec>': 'r'}) def",
"no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries': retries, '--logs':False}) deploy.config =",
"You may obtain a copy of the License at #",
"{ 'last_remote_container': 'gcr.io/app_name:container_id', 'last_push_duration': 0.18889} output = deploy( no_push=False, skip_crd_check=True,",
"call_args[0][0] if command[0] == \"kubectl\": assert \"--namespace\" in command def",
"import uuid import pytest from mock import call, MagicMock from",
"output = deploy( no_push=True, skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output, did_push=False)",
"Corporation # # Licensed under the Apache License, Version 2.0",
"= deploy( no_push=False, skip_crd_check=True, interactive=False, extra_config_args={'registry': 'dockerhub'}) verify_successful_deploy(output) def test_deploy_without_push(walk_mock,",
"= output.find('Pushed to ') pod_connect = output.find('Connecting to pod...') if",
"template, kube_helpers, process_helpers, verify_build, verify_init, fetch_action_arg, sleep, yaml, json_mock): walk_mock.return_value",
"skip_crd_check=True, interactive=False, extra_config_args={'gceProject': 'gcr://projectfoo'}) verify_successful_deploy(output) def test_deploy_docker(walk_mock, progress_bar, popen_mock, open_mock,",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"the normal output, followed by the error message output_location =",
"caught_output: with pytest.raises(SystemExit): deploy_cmd.action() output = caught_output.getvalue() # assert that",
"'--no-push': no_push, '--skip-crd-check': skip_crd_check, '--interactive': interactive, '--retries': retries, '--logs':False}) deploy.config",
"output.find('Pushing ') push_skip = output.find('Skipping image push') deploying = output.find('Deploying"
] |
[
"= vi, prob = 1, time = 0 ) kernel.scatter(",
"return pass # end of TestCase def main(): unittest.main() return",
"main() # version __id__ = \"$Id: TestCase.py 696 2010-11-09 06:23:06Z",
"= \"$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao $\" # End",
"unittestX as unittest import journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" )",
"debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" )",
"__id__ = \"$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao $\" #",
"sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei = 500 #",
"sigma_Q = \"Q/2.\" Qmin = 0; Qmax = 10 absorption_coefficient",
"in range(10): event = mcni.neutron( r = (0,0,0), v =",
"Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone =",
"\"Q/2.\" Qmin = 0; Qmax = 10 absorption_coefficient = scattering_coefficient",
"scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin,",
") ei = 500 # meV from mcni.utils import conversion",
") kernel.scatter( event ); vf = np.array(event.state.velocity) diffv = vi",
"vi, prob = 1, time = 0 ) kernel.scatter( event",
"np.array(event.state.velocity) diffv = vi - vf Q = conversion.v2k(nl.norm(diffv)) ef",
"kernel.scatter( event ); vf = np.array(event.state.velocity) diffv = vi -",
"__name__ == \"__main__\": main() # version __id__ = \"$Id: TestCase.py",
"= journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni from mccomposite import mccompositebp",
"event = mcni.neutron( r = (0,0,0), v = vi, prob",
"0; Qmax = 10 absorption_coefficient = scattering_coefficient = 1. kernel",
"Technology # (C) 2006-2010 All Rights Reserved # # {LicenseText}",
"\"__main__\": main() # version __id__ = \"$Id: TestCase.py 696 2010-11-09",
"mcni.utils import conversion vil = conversion.e2v(ei) vi = (0,0,vil) import",
"\"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni from",
"conversion vil = conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg as",
"import numpy as np for i in range(10): event =",
"# {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import",
"nl import numpy as np for i in range(10): event",
"- ef # print E, Q, event E1 = eval(E_Q)",
"= conversion.v2e(nl.norm(vf)) E = ei - ef # print E,",
"mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q = \"Q*Q/3.\"",
"journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni",
"absorption_coefficient, scattering_coefficient, ) ei = 500 # meV from mcni.utils",
"= np.array(event.state.velocity) diffv = vi - vf Q = conversion.v2k(nl.norm(diffv))",
"end of TestCase def main(): unittest.main() return if __name__ ==",
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology #",
"#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California",
"E1 = eval(E_Q) continue return pass # end of TestCase",
"standalone = True import unittestX as unittest import journal debug",
"(0,0,vil) import numpy.linalg as nl import numpy as np for",
"test(self): E_Q = \"Q*Q/3.\" S_Q = \"1\" sigma_Q = \"Q/2.\"",
"# version __id__ = \"$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao",
"2006-2010 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
"E, Q, event E1 = eval(E_Q) continue return pass #",
"Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone",
"conversion.v2e(nl.norm(vf)) E = ei - ef # print E, Q,",
"from mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q =",
"= 1, time = 0 ) kernel.scatter( event ); vf",
"= eval(E_Q) continue return pass # end of TestCase def",
"conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg as nl import numpy",
"ef # print E, Q, event E1 = eval(E_Q) continue",
"); vf = np.array(event.state.velocity) diffv = vi - vf Q",
"1, time = 0 ) kernel.scatter( event ); vf =",
"= 0; Qmax = 10 absorption_coefficient = scattering_coefficient = 1.",
"All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #",
"# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import unittestX as unittest",
"# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of Technology",
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import unittestX as unittest import",
"journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni from mccomposite import mccompositebp from",
"# (C) 2006-2010 All Rights Reserved # # {LicenseText} #",
"absorption_coefficient = scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q,",
"= 500 # meV from mcni.utils import conversion vil =",
"= 0 ) kernel.scatter( event ); vf = np.array(event.state.velocity) diffv",
"python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute",
"warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni from mccomposite import",
"mccompositebp from mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q",
"mccomposite import mccompositebp from mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def",
"= 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax,",
"TestCase def main(): unittest.main() return if __name__ == \"__main__\": main()",
"numpy as np for i in range(10): event = mcni.neutron(",
"class TestCase(unittest.TestCase): def test(self): E_Q = \"Q*Q/3.\" S_Q = \"1\"",
"unittest.main() return if __name__ == \"__main__\": main() # version __id__",
"i in range(10): event = mcni.neutron( r = (0,0,0), v",
"= True import unittestX as unittest import journal debug =",
") import mcni from mccomposite import mccompositebp from mccomponents import",
"{LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import unittestX",
"import numpy.linalg as nl import numpy as np for i",
"return if __name__ == \"__main__\": main() # version __id__ =",
"eval(E_Q) continue return pass # end of TestCase def main():",
"Qmax = 10 absorption_coefficient = scattering_coefficient = 1. kernel =",
"Qmax, absorption_coefficient, scattering_coefficient, ) ei = 500 # meV from",
"print E, Q, event E1 = eval(E_Q) continue return pass",
"from mcni.utils import conversion vil = conversion.e2v(ei) vi = (0,0,vil)",
"Institute of Technology # (C) 2006-2010 All Rights Reserved #",
"as unittest import journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning",
"Qmin = 0; Qmax = 10 absorption_coefficient = scattering_coefficient =",
"ef = conversion.v2e(nl.norm(vf)) E = ei - ef # print",
"= conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg as nl import",
"# # <NAME> # California Institute of Technology # (C)",
"E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei =",
"\"Q*Q/3.\" S_Q = \"1\" sigma_Q = \"Q/2.\" Qmin = 0;",
"# meV from mcni.utils import conversion vil = conversion.e2v(ei) vi",
"= mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, )",
"numpy.linalg as nl import numpy as np for i in",
"r = (0,0,0), v = vi, prob = 1, time",
"S_Q = \"1\" sigma_Q = \"Q/2.\" Qmin = 0; Qmax",
"== \"__main__\": main() # version __id__ = \"$Id: TestCase.py 696",
"# standalone = True import unittestX as unittest import journal",
"E_Q = \"Q*Q/3.\" S_Q = \"1\" sigma_Q = \"Q/2.\" Qmin",
"import mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q = \"Q*Q/3.\" S_Q",
"event ); vf = np.array(event.state.velocity) diffv = vi - vf",
"E = ei - ef # print E, Q, event",
"unittest import journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning =",
"\"1\" sigma_Q = \"Q/2.\" Qmin = 0; Qmax = 10",
"= scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q,",
"# # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # California Institute of",
"# # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True import unittestX as",
"import unittestX as unittest import journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\"",
"meV from mcni.utils import conversion vil = conversion.e2v(ei) vi =",
"range(10): event = mcni.neutron( r = (0,0,0), v = vi,",
"# print E, Q, event E1 = eval(E_Q) continue return",
"= \"1\" sigma_Q = \"Q/2.\" Qmin = 0; Qmax =",
"\"$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao $\" # End of",
"(C) 2006-2010 All Rights Reserved # # {LicenseText} # #",
") warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import mcni from mccomposite",
"def test(self): E_Q = \"Q*Q/3.\" S_Q = \"1\" sigma_Q =",
"v = vi, prob = 1, time = 0 )",
"# <NAME> # California Institute of Technology # (C) 2006-2010",
"for i in range(10): event = mcni.neutron( r = (0,0,0),",
"pass # end of TestCase def main(): unittest.main() return if",
"vi = (0,0,vil) import numpy.linalg as nl import numpy as",
"# # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standalone = True",
"mcni.neutron( r = (0,0,0), v = vi, prob = 1,",
"= ei - ef # print E, Q, event E1",
"TestCase.py 696 2010-11-09 06:23:06Z linjiao $\" # End of file",
"of Technology # (C) 2006-2010 All Rights Reserved # #",
"True import unittestX as unittest import journal debug = journal.debug(",
"import journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning(",
"\"Broadened_E_Q_Kernel_TestCase\" ) import mcni from mccomposite import mccompositebp from mccomponents",
"time = 0 ) kernel.scatter( event ); vf = np.array(event.state.velocity)",
"from mccomposite import mccompositebp from mccomponents import mccomponentsbp class TestCase(unittest.TestCase):",
"event E1 = eval(E_Q) continue return pass # end of",
"= (0,0,vil) import numpy.linalg as nl import numpy as np",
"TestCase(unittest.TestCase): def test(self): E_Q = \"Q*Q/3.\" S_Q = \"1\" sigma_Q",
"journal debug = journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\"",
"= journal.debug( \"Broadened_E_Q_Kernel_TestCase\" ) warning = journal.warning( \"Broadened_E_Q_Kernel_TestCase\" ) import",
"(0,0,0), v = vi, prob = 1, time = 0",
"if __name__ == \"__main__\": main() # version __id__ = \"$Id:",
"= vi - vf Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf))",
"vf Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E = ei",
"of TestCase def main(): unittest.main() return if __name__ == \"__main__\":",
"vil = conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg as nl",
"Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei = 500 # meV",
"500 # meV from mcni.utils import conversion vil = conversion.e2v(ei)",
"# end of TestCase def main(): unittest.main() return if __name__",
"main(): unittest.main() return if __name__ == \"__main__\": main() # version",
"Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E = ei -",
"prob = 1, time = 0 ) kernel.scatter( event );",
"10 absorption_coefficient = scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q,",
"vf = np.array(event.state.velocity) diffv = vi - vf Q =",
"= mcni.neutron( r = (0,0,0), v = vi, prob =",
"<NAME> # California Institute of Technology # (C) 2006-2010 All",
"ei - ef # print E, Q, event E1 =",
"import mcni from mccomposite import mccompositebp from mccomponents import mccomponentsbp",
"continue return pass # end of TestCase def main(): unittest.main()",
"= \"Q/2.\" Qmin = 0; Qmax = 10 absorption_coefficient =",
"0 ) kernel.scatter( event ); vf = np.array(event.state.velocity) diffv =",
"1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient,",
"import mccompositebp from mccomponents import mccomponentsbp class TestCase(unittest.TestCase): def test(self):",
"mccomponentsbp class TestCase(unittest.TestCase): def test(self): E_Q = \"Q*Q/3.\" S_Q =",
"np for i in range(10): event = mcni.neutron( r =",
"mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei",
"as nl import numpy as np for i in range(10):",
"import conversion vil = conversion.e2v(ei) vi = (0,0,vil) import numpy.linalg",
"conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E = ei - ef #",
"as np for i in range(10): event = mcni.neutron( r",
"# California Institute of Technology # (C) 2006-2010 All Rights",
"kernel = mccomponentsbp.create_Broadened_E_Q_Kernel( E_Q, S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient,",
"ei = 500 # meV from mcni.utils import conversion vil",
"mcni from mccomposite import mccompositebp from mccomponents import mccomponentsbp class",
"diffv = vi - vf Q = conversion.v2k(nl.norm(diffv)) ef =",
"- vf Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E =",
"vi - vf Q = conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E",
"Q, event E1 = eval(E_Q) continue return pass # end",
"def main(): unittest.main() return if __name__ == \"__main__\": main() #",
"scattering_coefficient, ) ei = 500 # meV from mcni.utils import",
"California Institute of Technology # (C) 2006-2010 All Rights Reserved",
"= (0,0,0), v = vi, prob = 1, time =",
"= 10 absorption_coefficient = scattering_coefficient = 1. kernel = mccomponentsbp.create_Broadened_E_Q_Kernel(",
"S_Q, sigma_Q, Qmin, Qmax, absorption_coefficient, scattering_coefficient, ) ei = 500",
"= conversion.v2k(nl.norm(diffv)) ef = conversion.v2e(nl.norm(vf)) E = ei - ef",
"= \"Q*Q/3.\" S_Q = \"1\" sigma_Q = \"Q/2.\" Qmin =",
"version __id__ = \"$Id: TestCase.py 696 2010-11-09 06:23:06Z linjiao $\""
] |
[
"BaseOptions class TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def __init__(self): super(TestOptions, self).__init__()",
"from .base_options import BaseOptions class TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def",
"result path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val data') self.parser.add_argument('--batch_size', default=256,",
"required=True, type=str, help='save result path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val",
"self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save",
"type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save result path') self.parser.add_argument('--max_val_samples',",
"required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save result path')",
"path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save result path') self.parser.add_argument('--max_val_samples', default=None, type=int,",
"help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save result path') self.parser.add_argument('--max_val_samples', default=None,",
"type=str, help='save result path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val data')",
"path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val data') self.parser.add_argument('--batch_size', default=256, type=int,",
"default=None, type=int, help='max val data') self.parser.add_argument('--batch_size', default=256, type=int, help='batch_size') self.is_train",
"__init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True,",
"help='max val data') self.parser.add_argument('--batch_size', default=256, type=int, help='batch_size') self.is_train = False",
"TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True,",
"self.parser.add_argument('--save_result_path', required=True, type=str, help='save result path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max",
"super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str,",
"Class\"\"\" def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path')",
".base_options import BaseOptions class TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def __init__(self):",
"self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path', required=True, type=str, help='save result",
"help='save result path') self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val data') self.parser.add_argument('--batch_size',",
"import BaseOptions class TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def __init__(self): super(TestOptions,",
"\"\"\"Test Option Class\"\"\" def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str,",
"class TestOptions(BaseOptions): \"\"\"Test Option Class\"\"\" def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path',",
"self.parser.add_argument('--max_val_samples', default=None, type=int, help='max val data') self.parser.add_argument('--batch_size', default=256, type=int, help='batch_size')",
"Option Class\"\"\" def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint",
"def __init__(self): super(TestOptions, self).__init__() self.parser.add_argument('--load_checkpoint_path', required=True, type=str, help='checkpoint path') self.parser.add_argument('--save_result_path',",
"type=int, help='max val data') self.parser.add_argument('--batch_size', default=256, type=int, help='batch_size') self.is_train ="
] |
[
"NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the generators",
"[seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new =",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap']",
"every zone by using the defined function for z in",
"* First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load']",
"VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the generators as an Excel",
"zone and sorting wrt to their seg1 heat rate Selected_line_oil",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] *",
"Third_cap = Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap, Third_cap] ramp_1 =",
"* First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2']",
"seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new =",
"st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2',",
"seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap']",
"oil_downsampler(z) #adding downsampled oil generators to create a complete list",
"sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters for the",
"downsampled oil generators to create a complete list of generators",
"seg_1, seg_2, seg_3, min_cap, ramp, Min_u, Min_d, var_om, no_load, st_cost]",
"= [First_cap, Second_cap, Third_cap] ramp_1 = First_cap ramp_2 = Second_cap",
"var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum()",
"#defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators all_slack",
"= Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap, Third_cap] ramp_1 = First_cap",
"oil generators list_labels = list(WCMA_oil.columns) list_columns = [name, types, zones,",
"= [name, types, zones, netcap, seg_1, seg_2, seg_3, min_cap, ramp,",
"and oil all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a function",
"= all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil =",
"First_min_cap = First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap",
"zone, zone] types = ['oil', 'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap']",
"ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting",
"Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2",
"Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap, Third_min_cap] Min_u = [1, 1,",
"for the downsampled oil plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap =",
"#importing generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting all",
"#creating 3 chunks wrt their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num",
"Apr 24 18:45:34 2020 @author: kakdemi \"\"\" import pandas as",
"var_om = [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load']",
"* Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new]",
"oil generators in that zone and sorting wrt to their",
"list_columns = [name, types, zones, netcap, seg_1, seg_2, seg_3, min_cap,",
"Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters",
"coding: utf-8 -*- \"\"\" Created on Fri Apr 24 18:45:34",
"seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new =",
"= var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap']",
"generators other than slack and oil all_other = all_generators[(all_generators['typ']!='oil') &",
"[1, 1, 1] Min_d = [1, 1, 1] zones =",
"= sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the",
"all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a function to downsample oil generators",
"all generators in every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil =",
"= int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant =",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] *",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap']",
"* Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2']",
"st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new =",
"SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining",
"seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new =",
"[seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 =",
"= Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap, Third_min_cap] Min_u = [1,",
"var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new =",
"st_cost] zipped_list = list(zip(list_labels, list_columns)) gen_df = dict(zipped_list) df_oils =",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] *",
"ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil",
"types, zones, netcap, seg_1, seg_2, seg_3, min_cap, ramp, Min_u, Min_d,",
"the generators as an Excel file final_generators.to_excel('generators.xlsx', sheet_name='NEISO generators (dispatch)',",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap']",
"to their seg1 heat rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df =",
"all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators other than slack and oil",
"ramp_2 = Second_cap ramp_3 = Third_cap ramp = [ramp_1, ramp_2,",
"sorting wrt to their seg1 heat rate Selected_line_oil = globals()[zone+'_oil'].copy()",
"final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df,",
"CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True)",
"the oil generators in that zone and sorting wrt to",
"First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new",
"zone by using the defined function for z in zones:",
"Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap, Third_cap] ramp_1 = First_cap ramp_2",
"var_om, no_load, st_cost] zipped_list = list(zip(list_labels, list_columns)) gen_df = dict(zipped_list)",
"sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant",
"RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the generators as",
"no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum()",
"seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3",
"= [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new",
"* First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost']",
"= [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new",
"generators list_labels = list(WCMA_oil.columns) list_columns = [name, types, zones, netcap,",
"rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True)",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] *",
"oil generators def oil_downsampler(zone): #copying the oil generators in that",
"= [1, 1, 1] Min_d = [1, 1, 1] zones",
"all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones",
"to downsample oil generators def oil_downsampler(zone): #copying the oil generators",
"= ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting",
"= oil_downsampler(z) #adding downsampled oil generators to create a complete",
"Second_min_cap, Third_min_cap] Min_u = [1, 1, 1] Min_d = [1,",
"= no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum()",
"oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all generators in every",
"Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new",
"seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 =",
"var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new =",
"all slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators other than",
"\"\"\" Created on Fri Apr 24 18:45:34 2020 @author: kakdemi",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new,",
"#creating a dataframe that includes downsampled oil generators list_labels =",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new,",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap']",
"seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2",
"Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap,",
"heat_rate = list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant",
"= all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil =",
"seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2",
"st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 =",
"globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled oil generators to create a",
"= sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters for",
"df_oils = pd.DataFrame(gen_df) return df_oils #downsampling oil generators in every",
"First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new",
"a dataframe that includes downsampled oil generators list_labels = list(WCMA_oil.columns)",
"zone+'_agg_oil_3'] #creating a dataframe that includes downsampled oil generators list_labels",
"pandas as pd #importing generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators",
"\"\"\" import pandas as pd #importing generators all_generators = pd.read_excel('generators2.xlsx',",
"var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 =",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] *",
"includes downsampled oil generators list_labels = list(WCMA_oil.columns) list_columns = [name,",
"all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a function to downsample",
"than slack and oil all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining",
"seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum()",
"var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] *",
"= list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant =",
"= list(zip(list_labels, list_columns)) gen_df = dict(zipped_list) df_oils = pd.DataFrame(gen_df) return",
"ramp_1 = First_cap ramp_2 = Second_cap ramp_3 = Third_cap ramp",
"seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new =",
"slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators other than slack",
"* Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load']",
"no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] *",
"st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new =",
"defined function for z in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding",
"num = int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant",
"#downsampling oil generators in every zone by using the defined",
"Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new",
"= Second_cap ramp_3 = Third_cap ramp = [ramp_1, ramp_2, ramp_3]",
"sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters for the downsampled oil plants",
"generators to create a complete list of generators final_generators =",
"create a complete list of generators final_generators = pd.concat([all_other, CT_agg_oil_df,",
"df_oils #downsampling oil generators in every zone by using the",
"First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new",
"a complete list of generators final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df,",
"downsampled oil plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap",
"Third_min_cap] Min_u = [1, 1, 1] Min_d = [1, 1,",
"in every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap']",
"all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy()",
"18:45:34 2020 @author: kakdemi \"\"\" import pandas as pd #importing",
"all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all generators in every zone CT_oil",
"Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new",
"3 chunks wrt their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num =",
"seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 =",
"= seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum()",
"for z in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled oil",
"= [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe that includes downsampled",
"a function to downsample oil generators def oil_downsampler(zone): #copying the",
"that includes downsampled oil generators list_labels = list(WCMA_oil.columns) list_columns =",
"no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load =",
"= sorted_df.reset_index(drop=True) #creating 3 chunks wrt their heatrates heat_rate =",
"= all_generators[all_generators['typ']=='oil'].copy() #getting all generators in every zone CT_oil =",
"seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 =",
"= Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap, Third_cap]",
"NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil",
"ramp_3] First_min_cap = First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap = Third_cap*0.35",
"SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the generators as an",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new,",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap']",
"= seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum()",
"= seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum()",
"st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3",
"= all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA']",
"slack and oil all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a",
"2020 @author: kakdemi \"\"\" import pandas as pd #importing generators",
"zone] types = ['oil', 'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap'] *",
"seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] *",
"wrt to their seg1 heat rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df",
"= First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap =",
"& (all_generators['typ']!='slack')].copy() #defining a function to downsample oil generators def",
"min_cap, ramp, Min_u, Min_d, var_om, no_load, st_cost] zipped_list = list(zip(list_labels,",
"* Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3']",
"their seg1 heat rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1'])",
"zones = [zone, zone, zone] types = ['oil', 'oil', 'oil']",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] *",
"oil plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap =",
"pd.DataFrame(gen_df) return df_oils #downsampling oil generators in every zone by",
"First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new",
"generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators other than slack and",
"= seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum()",
"* Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost']",
"parameters for the downsampled oil plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap",
"seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1",
"pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting all oil generators all_oil =",
"generators in every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy()",
"#getting all slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators other",
"Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new",
"= Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap, Third_min_cap]",
"Min_u = [1, 1, 1] Min_d = [1, 1, 1]",
"in that zone and sorting wrt to their seg1 heat",
"downsampled oil generators list_labels = list(WCMA_oil.columns) list_columns = [name, types,",
"every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil =",
"var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] *",
"WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all",
"no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3",
"oil_downsampler(zone): #copying the oil generators in that zone and sorting",
"seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] *",
"@author: kakdemi \"\"\" import pandas as pd #importing generators all_generators",
"return df_oils #downsampling oil generators in every zone by using",
"[1, 1, 1] zones = [zone, zone, zone] types =",
"1] zones = [zone, zone, zone] types = ['oil', 'oil',",
"Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new",
"name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe that includes",
"all_slack], ignore_index=True) #exporting the generators as an Excel file final_generators.to_excel('generators.xlsx',",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap']",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new,",
"zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy()",
"seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new =",
"ramp_3 = Third_cap ramp = [ramp_1, ramp_2, ramp_3] First_min_cap =",
"zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe that includes downsampled oil generators",
"all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy()",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new,",
"seg1 heat rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset",
"seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new,",
"VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones =",
"zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled oil generators to create",
"Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1",
"Fri Apr 24 18:45:34 2020 @author: kakdemi \"\"\" import pandas",
"ramp = [ramp_1, ramp_2, ramp_3] First_min_cap = First_cap*0.35 Second_min_cap =",
"all_generators[all_generators['typ']=='oil'].copy() #getting all generators in every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy()",
"= ['oil', 'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new",
"all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting",
"= var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum()",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap']",
"oil generators in every zone by using the defined function",
"[zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe that includes downsampled oil",
"= [ramp_1, ramp_2, ramp_3] First_min_cap = First_cap*0.35 Second_min_cap = Second_cap*0.35",
"var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2",
"int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy()",
"= st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum()",
"pd #importing generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting",
"* Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om']",
"CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil",
"st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3']",
"seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new =",
"Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new",
"zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators all_slack =",
"* Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new]",
"wrt their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant",
"sorted_df.reset_index(drop=True) #creating 3 chunks wrt their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1'])",
"Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1",
"= seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum()",
"First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy() Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding",
"utf-8 -*- \"\"\" Created on Fri Apr 24 18:45:34 2020",
"generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all generators in every zone",
"function for z in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled",
"generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting all oil",
"#getting all oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all generators",
"24 18:45:34 2020 @author: kakdemi \"\"\" import pandas as pd",
"= sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters for the downsampled oil",
"seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new]",
"Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new] name",
"st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe that",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 = Second_plant.loc[:,'netcap'] *",
"= seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum()",
"First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new",
"= all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil =",
"seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3",
"ramp, Min_u, Min_d, var_om, no_load, st_cost] zipped_list = list(zip(list_labels, list_columns))",
"#exporting the generators as an Excel file final_generators.to_excel('generators.xlsx', sheet_name='NEISO generators",
"'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum()",
"import pandas as pd #importing generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO",
"no_load, st_cost] zipped_list = list(zip(list_labels, list_columns)) gen_df = dict(zipped_list) df_oils",
"sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3 chunks wrt",
"their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant =",
"* Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3']",
"st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 =",
"Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new",
"oil all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a function to",
"#adding downsampled oil generators to create a complete list of",
"= st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1',",
"Third_cap ramp = [ramp_1, ramp_2, ramp_3] First_min_cap = First_cap*0.35 Second_min_cap",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] *",
"seg_2, seg_3, min_cap, ramp, Min_u, Min_d, var_om, no_load, st_cost] zipped_list",
"[st_cost_1_new, st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap']",
"seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new,",
"seg_3_2 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg2'] seg_3_2_new = seg_3_2.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_3 =",
"= var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum()",
"# -*- coding: utf-8 -*- \"\"\" Created on Fri Apr",
"no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 =",
"Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating",
"netcap, seg_1, seg_2, seg_3, min_cap, ramp, Min_u, Min_d, var_om, no_load,",
"Min_d, var_om, no_load, st_cost] zipped_list = list(zip(list_labels, list_columns)) gen_df =",
"WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the generators as an Excel file",
"-*- coding: utf-8 -*- \"\"\" Created on Fri Apr 24",
"= all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil =",
"Min_u, Min_d, var_om, no_load, st_cost] zipped_list = list(zip(list_labels, list_columns)) gen_df",
"[ramp_1, ramp_2, ramp_3] First_min_cap = First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap",
"chunks wrt their heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3)",
"var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3",
"as pd #importing generators all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)')",
"oil generators to create a complete list of generators final_generators",
"= all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy() #defining a function to downsample oil",
"seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 =",
"min_cap = [First_min_cap, Second_min_cap, Third_min_cap] Min_u = [1, 1, 1]",
"= seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new,",
"(dispatch)') #getting all oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all",
"[First_cap, Second_cap, Third_cap] ramp_1 = First_cap ramp_2 = Second_cap ramp_3",
"* First_plant.loc[:,'seg2'] seg_1_2_new = seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3']",
"using the defined function for z in zones: globals()[z+'_agg_oil_df'] =",
"First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap = [First_cap,",
"zones, netcap, seg_1, seg_2, seg_3, min_cap, ramp, Min_u, Min_d, var_om,",
"seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 =",
"seg_1 = [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new]",
"= First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap =",
"Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap = [First_cap, Second_cap, Third_cap] ramp_1",
"sheet_name='NEISO generators (dispatch)') #getting all oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy()",
"First_cap = First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum() netcap",
"sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3 chunks wrt their heatrates heat_rate",
"st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost",
"= pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df,",
"list(WCMA_oil.columns) list_columns = [name, types, zones, netcap, seg_1, seg_2, seg_3,",
"def oil_downsampler(zone): #copying the oil generators in that zone and",
"gen_df = dict(zipped_list) df_oils = pd.DataFrame(gen_df) return df_oils #downsampling oil",
"all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy()",
"['oil', 'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new =",
"generators as an Excel file final_generators.to_excel('generators.xlsx', sheet_name='NEISO generators (dispatch)', index=False)",
"var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 =",
"generators def oil_downsampler(zone): #copying the oil generators in that zone",
"all_oil[all_oil['zone']=='CT'].copy() ME_oil = all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy()",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new = var_om_2.sum()/Second_plant.loc[:,'netcap'].sum() var_om_3 = Third_plant.loc[:,'netcap'] *",
"list_columns)) gen_df = dict(zipped_list) df_oils = pd.DataFrame(gen_df) return df_oils #downsampling",
"#finding the relevant parameters for the downsampled oil plants First_cap",
"zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy()",
"Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap, Third_min_cap] Min_u",
"list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy() Second_plant = sorted_df_reset.iloc[num:num*2,:].copy()",
"kakdemi \"\"\" import pandas as pd #importing generators all_generators =",
"First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om'] var_om_2_new",
"seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om']",
"seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 =",
"the downsampled oil plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum()",
"list_labels = list(WCMA_oil.columns) list_columns = [name, types, zones, netcap, seg_1,",
"to create a complete list of generators final_generators = pd.concat([all_other,",
"= no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum()",
"downsample oil generators def oil_downsampler(zone): #copying the oil generators in",
"* First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1']",
"-*- \"\"\" Created on Fri Apr 24 18:45:34 2020 @author:",
"seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3",
"complete list of generators final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df,",
"= [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new",
"seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 =",
"ignore_index=True) #exporting the generators as an Excel file final_generators.to_excel('generators.xlsx', sheet_name='NEISO",
"* First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'var_om']",
"seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_3 =",
"seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2",
"and sorting wrt to their seg1 heat rate Selected_line_oil =",
"= [seg_1_1_new, seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3",
"the defined function for z in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z)",
"#copying the oil generators in that zone and sorting wrt",
"* Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new, var_om_3_new]",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new,",
"function to downsample oil generators def oil_downsampler(zone): #copying the oil",
"heatrates heat_rate = list(sorted_df_reset.loc[:,'seg1']) num = int(len(heat_rate)/3) First_plant = sorted_df_reset.iloc[:num,:].copy()",
"[First_min_cap, Second_min_cap, Third_min_cap] Min_u = [1, 1, 1] Min_d =",
"st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost = [st_cost_1_new, st_cost_2_new, st_cost_3_new] name =",
"list(zip(list_labels, list_columns)) gen_df = dict(zipped_list) df_oils = pd.DataFrame(gen_df) return df_oils",
"dataframe that includes downsampled oil generators list_labels = list(WCMA_oil.columns) list_columns",
"= all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack",
"no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 =",
"* Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2']",
"types = ['oil', 'oil', 'oil'] seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1']",
"z in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled oil generators",
"Second_cap, Third_cap] ramp_1 = First_cap ramp_2 = Second_cap ramp_3 =",
"var_om_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'var_om'] var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om =",
"= [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1",
"all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy()",
"all_generators = pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting all oil generators",
"* Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1']",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap']",
"NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil",
"= Third_cap ramp = [ramp_1, ramp_2, ramp_3] First_min_cap = First_cap*0.35",
"the relevant parameters for the downsampled oil plants First_cap =",
"no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load",
"[no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new =",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new = seg_3_1.sum()/Third_plant.loc[:,'netcap'].sum() seg_3_2 = Third_plant.loc[:,'netcap']",
"= Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3 chunks wrt their",
"Min_d = [1, 1, 1] zones = [zone, zone, zone]",
"= [1, 1, 1] zones = [zone, zone, zone] types",
"st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating a dataframe",
"no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2",
"Third_plant = sorted_df_reset.iloc[num*2:,:].copy() #finding the relevant parameters for the downsampled",
"all_oil[all_oil['zone']=='WCMA'].copy() #defining zones zones = ['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators",
"(all_generators['typ']!='slack')].copy() #defining a function to downsample oil generators def oil_downsampler(zone):",
"= First_plant.loc[:,'netcap'] * First_plant.loc[:,'var_om'] var_om_1_new = var_om_1.sum()/First_plant.loc[:,'netcap'].sum() var_om_2 = Second_plant.loc[:,'netcap']",
"[var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'no_load'] no_load_1_new =",
"on Fri Apr 24 18:45:34 2020 @author: kakdemi \"\"\" import",
"['CT','ME','NEMA','NH','RI','SEMA','VT','WCMA'] #getting all slack generators all_slack = all_generators[all_generators['typ']=='slack'].copy() #getting generators",
"no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 =",
"generators (dispatch)') #getting all oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting",
"= seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg2'] seg_2_2_new = seg_2_2.sum()/Second_plant.loc[:,'netcap'].sum()",
"Third_cap] ramp_1 = First_cap ramp_2 = Second_cap ramp_3 = Third_cap",
"'oil'] seg_1_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg1'] seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2",
"seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 =",
"[zone, zone, zone] types = ['oil', 'oil', 'oil'] seg_1_1 =",
"var_om_3_new = var_om_3.sum()/Third_plant.loc[:,'netcap'].sum() var_om = [var_om_1_new, var_om_2_new, var_om_3_new] no_load_1 =",
"= pd.read_excel('generators2.xlsx', sheet_name='NEISO generators (dispatch)') #getting all oil generators all_oil",
"= First_cap ramp_2 = Second_cap ramp_3 = Third_cap ramp =",
"seg_1_1_new = seg_1_1.sum()/First_plant.loc[:,'netcap'].sum() seg_1_2 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg2'] seg_1_2_new =",
"NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack], ignore_index=True) #exporting the",
"1] Min_d = [1, 1, 1] zones = [zone, zone,",
"= Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg3'] seg_3_3_new = seg_3_3.sum()/Third_plant.loc[:,'netcap'].sum() seg_1 = [seg_1_1_new,",
"First_cap ramp_2 = Second_cap ramp_3 = Third_cap ramp = [ramp_1,",
"list of generators final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df,",
"Third_min_cap = Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap, Third_min_cap] Min_u =",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum() st_cost_3 = Third_plant.loc[:,'netcap'] *",
"= Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap']",
"st_cost_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'st_cost'] st_cost_3_new = st_cost_3.sum()/Third_plant.loc[:,'netcap'].sum() st_cost =",
"1, 1] Min_d = [1, 1, 1] zones = [zone,",
"Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3 chunks wrt their heatrates",
"generators in every zone by using the defined function for",
"no_load_1_new = no_load_1.sum()/First_plant.loc[:,'netcap'].sum() no_load_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'no_load'] no_load_2_new =",
"Second_cap ramp_3 = Third_cap ramp = [ramp_1, ramp_2, ramp_3] First_min_cap",
"seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 = First_plant.loc[:,'netcap']",
"First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost'] st_cost_1_new = st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] *",
"generators final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df,",
"= all_generators[all_generators['typ']=='slack'].copy() #getting generators other than slack and oil all_other",
"= pd.DataFrame(gen_df) return df_oils #downsampling oil generators in every zone",
"ramp_2, ramp_3] First_min_cap = First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap =",
"= [st_cost_1_new, st_cost_2_new, st_cost_3_new] name = [zone+'_agg_oil_1', zone+'_agg_oil_2', zone+'_agg_oil_3'] #creating",
"globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3 chunks",
"all oil generators all_oil = all_generators[all_generators['typ']=='oil'].copy() #getting all generators in",
"[seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new, seg_2_3_new, seg_3_3_new] var_om_1 =",
"no_load = [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'st_cost']",
"plants First_cap = First_plant.loc[:,'netcap'].sum() Second_cap = Second_plant.loc[:,'netcap'].sum() Third_cap = Third_plant.loc[:,'netcap'].sum()",
"= list(WCMA_oil.columns) list_columns = [name, types, zones, netcap, seg_1, seg_2,",
"Second_min_cap = Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap = [First_min_cap, Second_min_cap,",
"generators in that zone and sorting wrt to their seg1",
"netcap = [First_cap, Second_cap, Third_cap] ramp_1 = First_cap ramp_2 =",
"= [zone, zone, zone] types = ['oil', 'oil', 'oil'] seg_1_1",
"heat rate Selected_line_oil = globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset =",
"dict(zipped_list) df_oils = pd.DataFrame(gen_df) return df_oils #downsampling oil generators in",
"= st_cost_1.sum()/First_plant.loc[:,'netcap'].sum() st_cost_2 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'st_cost'] st_cost_2_new = st_cost_2.sum()/Second_plant.loc[:,'netcap'].sum()",
"of generators final_generators = pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df,",
"[name, types, zones, netcap, seg_1, seg_2, seg_3, min_cap, ramp, Min_u,",
"#getting generators other than slack and oil all_other = all_generators[(all_generators['typ']!='oil')",
"= no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new, no_load_3_new] st_cost_1 = First_plant.loc[:,'netcap']",
"* Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new, no_load_3_new]",
"no_load_2_new = no_load_2.sum()/Second_plant.loc[:,'netcap'].sum() no_load_3 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new =",
"seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum() seg_2_1 = Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new =",
"#getting all generators in every zone CT_oil = all_oil[all_oil['zone']=='CT'].copy() ME_oil",
"Second_plant.loc[:,'seg3'] seg_2_3_new = seg_2_3.sum()/Second_plant.loc[:,'netcap'].sum() seg_3_1 = Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'seg1'] seg_3_1_new",
"all_generators[all_generators['typ']=='slack'].copy() #getting generators other than slack and oil all_other =",
"RI_oil = all_oil[all_oil['zone']=='RI'].copy() SEMA_oil = all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil",
"= dict(zipped_list) df_oils = pd.DataFrame(gen_df) return df_oils #downsampling oil generators",
"in every zone by using the defined function for z",
"by using the defined function for z in zones: globals()[z+'_agg_oil_df']",
"that zone and sorting wrt to their seg1 heat rate",
"Created on Fri Apr 24 18:45:34 2020 @author: kakdemi \"\"\"",
"Second_plant.loc[:,'netcap'] * Second_plant.loc[:,'seg1'] seg_2_1_new = seg_2_1.sum()/Second_plant.loc[:,'netcap'].sum() seg_2_2 = Second_plant.loc[:,'netcap'] *",
"other than slack and oil all_other = all_generators[(all_generators['typ']!='oil') & (all_generators['typ']!='slack')].copy()",
"First_cap*0.35 Second_min_cap = Second_cap*0.35 Third_min_cap = Third_cap*0.35 min_cap = [First_min_cap,",
"= seg_1_2.sum()/First_plant.loc[:,'netcap'].sum() seg_1_3 = First_plant.loc[:,'netcap'] * First_plant.loc[:,'seg3'] seg_1_3_new = seg_1_3.sum()/First_plant.loc[:,'netcap'].sum()",
"in zones: globals()[z+'_agg_oil_df'] = oil_downsampler(z) #adding downsampled oil generators to",
"relevant parameters for the downsampled oil plants First_cap = First_plant.loc[:,'netcap'].sum()",
"1, 1] zones = [zone, zone, zone] types = ['oil',",
"#defining a function to downsample oil generators def oil_downsampler(zone): #copying",
"pd.concat([all_other, CT_agg_oil_df, ME_agg_oil_df, NEMA_agg_oil_df, NH_agg_oil_df, RI_agg_oil_df, SEMA_agg_oil_df, VT_agg_oil_df, WCMA_agg_oil_df, all_slack],",
"= [First_min_cap, Second_min_cap, Third_min_cap] Min_u = [1, 1, 1] Min_d",
"= all_oil[all_oil['zone']=='ME'].copy() NEMA_oil = all_oil[all_oil['zone']=='NEMA'].copy() NH_oil = all_oil[all_oil['zone']=='NH'].copy() RI_oil =",
"seg_3, min_cap, ramp, Min_u, Min_d, var_om, no_load, st_cost] zipped_list =",
"seg_2_1_new, seg_3_1_new] seg_2 = [seg_1_2_new, seg_2_2_new, seg_3_2_new] seg_3 = [seg_1_3_new,",
"zipped_list = list(zip(list_labels, list_columns)) gen_df = dict(zipped_list) df_oils = pd.DataFrame(gen_df)",
"Third_plant.loc[:,'netcap'] * Third_plant.loc[:,'no_load'] no_load_3_new = no_load_3.sum()/Third_plant.loc[:,'netcap'].sum() no_load = [no_load_1_new, no_load_2_new,",
"= all_oil[all_oil['zone']=='SEMA'].copy() VT_oil = all_oil[all_oil['zone']=='VT'].copy() WCMA_oil = all_oil[all_oil['zone']=='WCMA'].copy() #defining zones",
"= globals()[zone+'_oil'].copy() sorted_df = Selected_line_oil.sort_values(by=['seg1']) sorted_df_reset = sorted_df.reset_index(drop=True) #creating 3"
] |
[
"<gh_stars>1-10 # -*- coding: utf-8 -*- \"\"\" Created on Tue",
"adore Python !\") bouton = tk . Button ( racine",
"utf-8 -*- \"\"\" Created on Tue Nov 16 19:47:41 2021",
"tk . Label ( racine , text =\"J ' adore",
", text =\" Quitter \", command = racine . destroy",
"Button ( racine , text =\" Quitter \", command =",
"bouton = tk . Button ( racine , text =\"",
"text =\" Quitter \", command = racine . destroy )",
"tkinter as tk racine = tk . Tk () label",
"racine , text =\" Quitter \", command = racine .",
"tk racine = tk . Tk () label = tk",
"19:47:41 2021 @author: User \"\"\" import tkinter as tk racine",
"@author: User \"\"\" import tkinter as tk racine = tk",
". Tk () label = tk . Label ( racine",
"= racine . destroy ) label . pack () bouton",
"=\" Quitter \", command = racine . destroy ) label",
"text =\"J ' adore Python !\") bouton = tk .",
"Created on Tue Nov 16 19:47:41 2021 @author: User \"\"\"",
"Tue Nov 16 19:47:41 2021 @author: User \"\"\" import tkinter",
"( racine , text =\" Quitter \", command = racine",
"' adore Python !\") bouton = tk . Button (",
"16 19:47:41 2021 @author: User \"\"\" import tkinter as tk",
"racine , text =\"J ' adore Python !\") bouton =",
"tk . Button ( racine , text =\" Quitter \",",
"\", command = racine . destroy ) label . pack",
". destroy ) label . pack () bouton . pack",
"Python !\") bouton = tk . Button ( racine ,",
"() label = tk . Label ( racine , text",
"racine . destroy ) label . pack () bouton .",
", text =\"J ' adore Python !\") bouton = tk",
"command = racine . destroy ) label . pack ()",
"Label ( racine , text =\"J ' adore Python !\")",
"Nov 16 19:47:41 2021 @author: User \"\"\" import tkinter as",
"( racine , text =\"J ' adore Python !\") bouton",
"label = tk . Label ( racine , text =\"J",
"-*- coding: utf-8 -*- \"\"\" Created on Tue Nov 16",
"2021 @author: User \"\"\" import tkinter as tk racine =",
"as tk racine = tk . Tk () label =",
"import tkinter as tk racine = tk . Tk ()",
"racine = tk . Tk () label = tk .",
"= tk . Label ( racine , text =\"J '",
"Tk () label = tk . Label ( racine ,",
"Quitter \", command = racine . destroy ) label .",
"\"\"\" Created on Tue Nov 16 19:47:41 2021 @author: User",
"= tk . Button ( racine , text =\" Quitter",
"User \"\"\" import tkinter as tk racine = tk .",
"= tk . Tk () label = tk . Label",
"-*- \"\"\" Created on Tue Nov 16 19:47:41 2021 @author:",
"tk . Tk () label = tk . Label (",
"# -*- coding: utf-8 -*- \"\"\" Created on Tue Nov",
"!\") bouton = tk . Button ( racine , text",
"coding: utf-8 -*- \"\"\" Created on Tue Nov 16 19:47:41",
"=\"J ' adore Python !\") bouton = tk . Button",
"\"\"\" import tkinter as tk racine = tk . Tk",
". Label ( racine , text =\"J ' adore Python",
"on Tue Nov 16 19:47:41 2021 @author: User \"\"\" import",
"destroy ) label . pack () bouton . pack ()",
". Button ( racine , text =\" Quitter \", command"
] |
[
"UpdateClickupModel = Body(...) ): clickup = jsonable_encoder(clickup) updated_clickup = await",
"clickup = jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id, clickup) return (",
"integrations data added into the database.\" ) async def add_clickup_a_integration(clickup:",
"integration\") async def delete_clickup_integration(id: str): deleted_clickup = await delete_integration(id) return",
"status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" ) ) @router.put( \"/{id}/\", response_description=\"Clickup integrations",
"clickup = await retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup integrations data",
"integrations data updated in the database.\" ) async def update_a_clickup_integration(",
") @router.put( \"/{id}/\", response_description=\"Clickup integrations data updated in the database.\"",
"= APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are retrieved.\") async def get_clickup_integrations():",
"the Clickup integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete the integration\") async",
") @router.delete(\"/{id}/\", response_description=\"Delete the integration\") async def delete_clickup_integration(id: str): deleted_clickup",
") @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async def find_clickup_integration(id): clickup =",
"updated_clickup = await update_clickup_data(id, clickup) return ( ResponseModel({\"id\": id}, \"Clickup",
"def add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup = jsonable_encoder(clickup) new_clickup =",
"retrieved.\") async def find_clickup_integration(id): clickup = await retrieve_clickup(id) return (",
"data retrieved.\") async def find_clickup_integration(id): clickup = await retrieve_clickup(id) return",
"def update_a_clickup_integration( id: str, clickup: UpdateClickupModel = Body(...) ): clickup",
"successfully\") if len(clickups) > 0 else ResponseModel(clickups, \"Empty list returned\")",
"was an error updating the Clickup integration.\", ) ) @router.delete(\"/{id}/\",",
"\"Clickup integration updated successfully\") if updated_clickup else ErrorResponseModel( \"An error",
"( ResponseModel(clickups, \"Clickup integrations data retrieved successfully\") if len(clickups) >",
"response_description=\"Clickup integrations data updated in the database.\" ) async def",
"are retrieved.\") async def get_clickup_integrations(): clickups = await retrieve_clickups() return",
"= await delete_integration(id) return ( ResponseModel( \"Integration with ID: {}",
"removed\".format(id), \"Integration deleted successfully\", ) if deleted_clickup else ErrorResponseModel( \"An",
"else ResponseModel(clickups, \"Empty list returned\") ) @router.post( \"/\", response_description=\"Clickup integrations",
"jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id, clickup) return ( ResponseModel({\"id\": id},",
"await delete_integration(id) return ( ResponseModel( \"Integration with ID: {} removed\".format(id),",
"response_description=\"Clickup data retrieved.\") async def find_clickup_integration(id): clickup = await retrieve_clickup(id)",
"returned\") ) @router.post( \"/\", response_description=\"Clickup integrations data added into the",
"delete_integration(id) return ( ResponseModel( \"Integration with ID: {} removed\".format(id), \"Integration",
"the database.\" ) async def update_a_clickup_integration( id: str, clickup: UpdateClickupModel",
"async def delete_clickup_integration(id: str): deleted_clickup = await delete_integration(id) return (",
"@router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async def find_clickup_integration(id): clickup = await",
"retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup integrations data retrieved successfully\") if",
"updated successfully\") if updated_clickup else ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND,",
"delete_clickup_integration(id: str): deleted_clickup = await delete_integration(id) return ( ResponseModel( \"Integration",
"error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" ) ) @router.put( \"/{id}/\",",
"from app.models.clickup import * from app.database.crud.clickup import * router =",
"import * router = APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are retrieved.\")",
"occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" ) ) @router.put( \"/{id}/\", response_description=\"Clickup",
"app.models.common import * from app.models.clickup import * from app.database.crud.clickup import",
"\"An error occurred\", status.HTTP_404_NOT_FOUND, \"There was an error updating the",
"if len(clickups) > 0 else ResponseModel(clickups, \"Empty list returned\") )",
"\"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration with id {0} doesn't exist\".format(id),",
"\"Clickup integrations data retrieved successfully\") if clickup else ErrorResponseModel( \"An",
"await retrieve_clickups() return ( ResponseModel(clickups, \"Clickup integrations data retrieved successfully\")",
"fastapi.encoders import jsonable_encoder from starlette.responses import JSONResponse from app.models.common import",
"= Body(...) ): clickup = jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id,",
"retrieved.\") async def get_clickup_integrations(): clickups = await retrieve_clickups() return (",
"occured\", status.HTTP_404_NOT_FOUND, \"Integration with id {0} doesn't exist\".format(id), ) )",
"else ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" )",
"* router = APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are retrieved.\") async",
"APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are retrieved.\") async def get_clickup_integrations(): clickups",
"an error updating the Clickup integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete",
"deleted_clickup else ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration with id",
"updated in the database.\" ) async def update_a_clickup_integration( id: str,",
") @router.post( \"/\", response_description=\"Clickup integrations data added into the database.\"",
"async def find_clickup_integration(id): clickup = await retrieve_clickup(id) return ( ResponseModel(clickup,",
"async def get_clickup_integrations(): clickups = await retrieve_clickups() return ( ResponseModel(clickups,",
"added into the database.\" ) async def add_clickup_a_integration(clickup: ClickupModel =",
"= jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup",
"( ResponseModel(clickup, \"Clickup integrations data retrieved successfully\") if clickup else",
"into the database.\" ) async def add_clickup_a_integration(clickup: ClickupModel = Body(...)):",
"status, Body, HTTPException from fastapi.encoders import jsonable_encoder from starlette.responses import",
"@router.post( \"/\", response_description=\"Clickup integrations data added into the database.\" )",
"await retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup integrations data retrieved successfully\")",
"ResponseModel(clickup, \"Clickup integrations data retrieved successfully\") if clickup else ErrorResponseModel(",
"import jsonable_encoder from starlette.responses import JSONResponse from app.models.common import *",
"await add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup integration created successfully.\", status.HTTP_201_CREATED,",
"): clickup = jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id, clickup) return",
"list returned\") ) @router.post( \"/\", response_description=\"Clickup integrations data added into",
"ResponseModel(clickups, \"Clickup integrations data retrieved successfully\") if len(clickups) > 0",
"ResponseModel( \"Integration with ID: {} removed\".format(id), \"Integration deleted successfully\", )",
"clickup else ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\"",
"updating the Clickup integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete the integration\")",
"occurred\", status.HTTP_404_NOT_FOUND, \"There was an error updating the Clickup integration.\",",
"ClickupModel = Body(...)): clickup = jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup)",
"update_a_clickup_integration( id: str, clickup: UpdateClickupModel = Body(...) ): clickup =",
"import * from app.models.clickup import * from app.database.crud.clickup import *",
"deleted successfully\", ) if deleted_clickup else ErrorResponseModel( \"An error occured\",",
"= Body(...)): clickup = jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup) return",
"import * from app.database.crud.clickup import * router = APIRouter() @router.get(\"/\",",
"return ( ResponseModel(clickup, \"Clickup integrations data retrieved successfully\") if clickup",
"id: str, clickup: UpdateClickupModel = Body(...) ): clickup = jsonable_encoder(clickup)",
"{} removed\".format(id), \"Integration deleted successfully\", ) if deleted_clickup else ErrorResponseModel(",
"from fastapi import APIRouter, status, Body, HTTPException from fastapi.encoders import",
"find_clickup_integration(id): clickup = await retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup integrations",
"the integration\") async def delete_clickup_integration(id: str): deleted_clickup = await delete_integration(id)",
"clickups = await retrieve_clickups() return ( ResponseModel(clickups, \"Clickup integrations data",
"data retrieved successfully\") if len(clickups) > 0 else ResponseModel(clickups, \"Empty",
"0 else ResponseModel(clickups, \"Empty list returned\") ) @router.post( \"/\", response_description=\"Clickup",
"ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" ) )",
"from app.database.crud.clickup import * router = APIRouter() @router.get(\"/\", response_description=\"Clickup integrations",
"the database.\" ) async def add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup",
"\"/{id}/\", response_description=\"Clickup integrations data updated in the database.\" ) async",
"= await update_clickup_data(id, clickup) return ( ResponseModel({\"id\": id}, \"Clickup integration",
"in the database.\" ) async def update_a_clickup_integration( id: str, clickup:",
") async def add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup = jsonable_encoder(clickup)",
"= jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id, clickup) return ( ResponseModel({\"id\":",
"else ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND, \"There was an error",
"@router.delete(\"/{id}/\", response_description=\"Delete the integration\") async def delete_clickup_integration(id: str): deleted_clickup =",
"response_description=\"Clickup integrations are retrieved.\") async def get_clickup_integrations(): clickups = await",
") ) @router.delete(\"/{id}/\", response_description=\"Delete the integration\") async def delete_clickup_integration(id: str):",
"router = APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are retrieved.\") async def",
"@router.get(\"/\", response_description=\"Clickup integrations are retrieved.\") async def get_clickup_integrations(): clickups =",
"def get_clickup_integrations(): clickups = await retrieve_clickups() return ( ResponseModel(clickups, \"Clickup",
"ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND, \"There was an error updating",
"import APIRouter, status, Body, HTTPException from fastapi.encoders import jsonable_encoder from",
") ) @router.put( \"/{id}/\", response_description=\"Clickup integrations data updated in the",
"return ( ResponseModel({\"id\": id}, \"Clickup integration updated successfully\") if updated_clickup",
"len(clickups) > 0 else ResponseModel(clickups, \"Empty list returned\") ) @router.post(",
"app.database.crud.clickup import * router = APIRouter() @router.get(\"/\", response_description=\"Clickup integrations are",
"status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async def find_clickup_integration(id): clickup",
"= await retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup integrations data retrieved",
"response_description=\"Delete the integration\") async def delete_clickup_integration(id: str): deleted_clickup = await",
"ResponseModel( new_clickup, \"clickup integration created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup",
"Body, HTTPException from fastapi.encoders import jsonable_encoder from starlette.responses import JSONResponse",
"database.\" ) async def update_a_clickup_integration( id: str, clickup: UpdateClickupModel =",
"successfully\") if updated_clickup else ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND, \"There",
"ID: {} removed\".format(id), \"Integration deleted successfully\", ) if deleted_clickup else",
"fastapi import APIRouter, status, Body, HTTPException from fastapi.encoders import jsonable_encoder",
"str): deleted_clickup = await delete_integration(id) return ( ResponseModel( \"Integration with",
"successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async def find_clickup_integration(id):",
") async def update_a_clickup_integration( id: str, clickup: UpdateClickupModel = Body(...)",
"with ID: {} removed\".format(id), \"Integration deleted successfully\", ) if deleted_clickup",
") if deleted_clickup else ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration",
"doesn't exist.\" ) ) @router.put( \"/{id}/\", response_description=\"Clickup integrations data updated",
"\"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't exist.\" ) ) @router.put(",
"app.models.clickup import * from app.database.crud.clickup import * router = APIRouter()",
"database.\" ) async def add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup =",
"starlette.responses import JSONResponse from app.models.common import * from app.models.clickup import",
"str, clickup: UpdateClickupModel = Body(...) ): clickup = jsonable_encoder(clickup) updated_clickup",
"add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup = jsonable_encoder(clickup) new_clickup = await",
"deleted_clickup = await delete_integration(id) return ( ResponseModel( \"Integration with ID:",
"def find_clickup_integration(id): clickup = await retrieve_clickup(id) return ( ResponseModel(clickup, \"Clickup",
"get_clickup_integrations(): clickups = await retrieve_clickups() return ( ResponseModel(clickups, \"Clickup integrations",
"\"Integration doesn't exist.\" ) ) @router.put( \"/{id}/\", response_description=\"Clickup integrations data",
"await update_clickup_data(id, clickup) return ( ResponseModel({\"id\": id}, \"Clickup integration updated",
"return ( ResponseModel(clickups, \"Clickup integrations data retrieved successfully\") if len(clickups)",
"HTTPException from fastapi.encoders import jsonable_encoder from starlette.responses import JSONResponse from",
"integrations are retrieved.\") async def get_clickup_integrations(): clickups = await retrieve_clickups()",
"integrations data retrieved successfully\") if clickup else ErrorResponseModel( \"An error",
"retrieved successfully\") if clickup else ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND,",
"update_clickup_data(id, clickup) return ( ResponseModel({\"id\": id}, \"Clickup integration updated successfully\")",
"integration created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async",
"from app.models.common import * from app.models.clickup import * from app.database.crud.clickup",
"jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup integration",
"if clickup else ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration doesn't",
"ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration with id {0} doesn't",
"integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete the integration\") async def delete_clickup_integration(id:",
"integrations data retrieved successfully\") if len(clickups) > 0 else ResponseModel(clickups,",
"updated_clickup else ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND, \"There was an",
"( ResponseModel({\"id\": id}, \"Clickup integration updated successfully\") if updated_clickup else",
"return ( ResponseModel( \"Integration with ID: {} removed\".format(id), \"Integration deleted",
"clickup: UpdateClickupModel = Body(...) ): clickup = jsonable_encoder(clickup) updated_clickup =",
"\"Clickup integrations data retrieved successfully\") if len(clickups) > 0 else",
"ResponseModel(clickups, \"Empty list returned\") ) @router.post( \"/\", response_description=\"Clickup integrations data",
"successfully\", ) if deleted_clickup else ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND,",
"Clickup integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete the integration\") async def",
"else ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration with id {0}",
"\"Integration deleted successfully\", ) if deleted_clickup else ErrorResponseModel( \"An error",
"\"There was an error updating the Clickup integration.\", ) )",
"APIRouter, status, Body, HTTPException from fastapi.encoders import jsonable_encoder from starlette.responses",
"( ResponseModel( \"Integration with ID: {} removed\".format(id), \"Integration deleted successfully\",",
"new_clickup, \"clickup integration created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data",
"return ResponseModel( new_clickup, \"clickup integration created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\",",
"def delete_clickup_integration(id: str): deleted_clickup = await delete_integration(id) return ( ResponseModel(",
"error occured\", status.HTTP_404_NOT_FOUND, \"Integration with id {0} doesn't exist\".format(id), )",
"Body(...) ): clickup = jsonable_encoder(clickup) updated_clickup = await update_clickup_data(id, clickup)",
"\"Empty list returned\") ) @router.post( \"/\", response_description=\"Clickup integrations data added",
"from fastapi.encoders import jsonable_encoder from starlette.responses import JSONResponse from app.models.common",
"\"clickup integration created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\")",
"> 0 else ResponseModel(clickups, \"Empty list returned\") ) @router.post( \"/\",",
"exist.\" ) ) @router.put( \"/{id}/\", response_description=\"Clickup integrations data updated in",
"clickup) return ( ResponseModel({\"id\": id}, \"Clickup integration updated successfully\") if",
"response_description=\"Clickup integrations data added into the database.\" ) async def",
"if updated_clickup else ErrorResponseModel( \"An error occurred\", status.HTTP_404_NOT_FOUND, \"There was",
"* from app.database.crud.clickup import * router = APIRouter() @router.get(\"/\", response_description=\"Clickup",
"created successfully.\", status.HTTP_201_CREATED, ) @router.get(\"/{id}/\", response_description=\"Clickup data retrieved.\") async def",
"retrieve_clickups() return ( ResponseModel(clickups, \"Clickup integrations data retrieved successfully\") if",
"* from app.models.clickup import * from app.database.crud.clickup import * router",
"error occurred\", status.HTTP_404_NOT_FOUND, \"There was an error updating the Clickup",
"async def add_clickup_a_integration(clickup: ClickupModel = Body(...)): clickup = jsonable_encoder(clickup) new_clickup",
"async def update_a_clickup_integration( id: str, clickup: UpdateClickupModel = Body(...) ):",
"ResponseModel({\"id\": id}, \"Clickup integration updated successfully\") if updated_clickup else ErrorResponseModel(",
"jsonable_encoder from starlette.responses import JSONResponse from app.models.common import * from",
"@router.put( \"/{id}/\", response_description=\"Clickup integrations data updated in the database.\" )",
"= await add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup integration created successfully.\",",
"JSONResponse from app.models.common import * from app.models.clickup import * from",
"data retrieved successfully\") if clickup else ErrorResponseModel( \"An error occured.\",",
"data updated in the database.\" ) async def update_a_clickup_integration( id:",
"status.HTTP_404_NOT_FOUND, \"There was an error updating the Clickup integration.\", )",
"error updating the Clickup integration.\", ) ) @router.delete(\"/{id}/\", response_description=\"Delete the",
"import JSONResponse from app.models.common import * from app.models.clickup import *",
"add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup integration created successfully.\", status.HTTP_201_CREATED, )",
"\"/\", response_description=\"Clickup integrations data added into the database.\" ) async",
"from starlette.responses import JSONResponse from app.models.common import * from app.models.clickup",
"integration updated successfully\") if updated_clickup else ErrorResponseModel( \"An error occurred\",",
"data added into the database.\" ) async def add_clickup_a_integration(clickup: ClickupModel",
"\"Integration with ID: {} removed\".format(id), \"Integration deleted successfully\", ) if",
"id}, \"Clickup integration updated successfully\") if updated_clickup else ErrorResponseModel( \"An",
"Body(...)): clickup = jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup) return ResponseModel(",
"retrieved successfully\") if len(clickups) > 0 else ResponseModel(clickups, \"Empty list",
"clickup = jsonable_encoder(clickup) new_clickup = await add_new_clickup(clickup) return ResponseModel( new_clickup,",
"= await retrieve_clickups() return ( ResponseModel(clickups, \"Clickup integrations data retrieved",
"new_clickup = await add_new_clickup(clickup) return ResponseModel( new_clickup, \"clickup integration created",
"successfully\") if clickup else ErrorResponseModel( \"An error occured.\", status.HTTP_404_NOT_FOUND, \"Integration",
"if deleted_clickup else ErrorResponseModel( \"An error occured\", status.HTTP_404_NOT_FOUND, \"Integration with"
] |
[
"ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights =",
"/ \".cellfinder\" logging.info(\"Detecting cell candidates\") points = detect.main( signal_array, start_plane,",
"\"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\"",
"I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"]",
"being imported before it's warnings are silenced \"\"\" import os",
"libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for message in tf_suppress_log_messages: suppress_specific_logs(\"tensorflow\",",
"ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20,",
"ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights = prep.prep_classification( trained_model,",
"n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10,",
"prep.prep_classification( trained_model, model_weights, install_path, model, n_free_cpus ) if len(points) >",
"signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2,",
"1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000,",
"ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ):",
"from cellfinder_core.tools import prep from pathlib import Path home =",
"detect.main( signal_array, start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction,",
"lines of logs such as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44]",
"tensorflow being imported before it's warnings are silenced \"\"\" import",
"def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines of logs such as:",
"logs such as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened",
"end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16,",
"\"multiprocessing can interact badly with TensorFlow\" ] def main( signal_array,",
"imlib.general.logging import suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing can interact badly",
"from pathlib import Path home = Path.home() install_path = home",
"len(points) > 0: logging.info(\"Running classification\") points = classify.main( points, signal_array,",
"cube_width, cube_depth, trained_model, model_weights, network_depth, ) else: logging.info(\"No candidates, skipping",
"cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect from cellfinder_core.classify",
"= home / \".cellfinder\" logging.info(\"Detecting cell candidates\") points = detect.main(",
"voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh,",
"ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\",",
"trained_model, model_weights, network_depth, ) else: logging.info(\"No candidates, skipping classification\") return",
"\"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for message in tf_suppress_log_messages: suppress_specific_logs(\"tensorflow\", message)",
"cellfinder_core.detect import detect from cellfinder_core.classify import classify from cellfinder_core.tools import",
"model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6,",
"Successfully opened dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for",
"imported before it's warnings are silenced \"\"\" import os import",
"background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5,",
"\".cellfinder\" logging.info(\"Detecting cell candidates\") points = detect.main( signal_array, start_plane, end_plane,",
"tf_suppress_log_messages = [ \"multiprocessing can interact badly with TensorFlow\" ]",
"log_sigma_size, n_sds_above_mean_thresh, ) model_weights = prep.prep_classification( trained_model, model_weights, install_path, model,",
"n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights = prep.prep_classification( trained_model, model_weights, install_path,",
"TensorFlow\" ] def main( signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None,",
"= detect.main( signal_array, start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size,",
"cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect from",
"import suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing can interact badly with",
"soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, )",
"logging from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing can",
"# logging.info(\"Saving classified cells\") # save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\"",
"such as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic",
"logging.info(\"Saving classified cells\") # save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents",
"n_free_cpus ) if len(points) > 0: logging.info(\"Running classification\") points =",
"warnings are silenced \"\"\" import os import logging from imlib.general.logging",
"import classify from cellfinder_core.tools import prep from pathlib import Path",
"classification\") return points # logging.info(\"Saving classified cells\") # save_cells(points, classified_points_path)",
"are silenced \"\"\" import os import logging from imlib.general.logging import",
"suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines of logs such as: \"2019-10-24",
"classify.main( points, signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width,",
"cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect",
"model_weights = prep.prep_classification( trained_model, model_weights, install_path, model, n_free_cpus ) if",
") else: logging.info(\"No candidates, skipping classification\") return points # logging.info(\"Saving",
"with TensorFlow\" ] def main( signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1,",
"\"\"\" Prevents many lines of logs such as: \"2019-10-24 16:54:41.363978:",
"suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing can interact badly with TensorFlow\"",
"max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights",
"classified cells\") # save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many",
"max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import",
"can interact badly with TensorFlow\" ] def main( signal_array, background_array,",
"network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4,",
"import os import logging from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages =",
"model_weights, network_depth, ) else: logging.info(\"No candidates, skipping classification\") return points",
"points = classify.main( points, signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size,",
"0: logging.info(\"Running classification\") points = classify.main( points, signal_array, background_array, n_free_cpus,",
"classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines of logs such",
"cube_height, cube_width, cube_depth, trained_model, model_weights, network_depth, ) else: logging.info(\"No candidates,",
"= prep.prep_classification( trained_model, model_weights, install_path, model, n_free_cpus ) if len(points)",
"classification\") points = classify.main( points, signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes,",
"skipping classification\") return points # logging.info(\"Saving classified cells\") # save_cells(points,",
"model_weights, install_path, model, n_free_cpus ) if len(points) > 0: logging.info(\"Running",
"functions to prevent tensorflow being imported before it's warnings are",
"classify from cellfinder_core.tools import prep from pathlib import Path home",
"import Path home = Path.home() install_path = home / \".cellfinder\"",
"background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth, trained_model, model_weights,",
"] def main( signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None,",
"candidates, skipping classification\") return points # logging.info(\"Saving classified cells\") #",
"of logs such as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully",
"Prevents many lines of logs such as: \"2019-10-24 16:54:41.363978: I",
"home / \".cellfinder\" logging.info(\"Detecting cell candidates\") points = detect.main( signal_array,",
"install_path, model, n_free_cpus ) if len(points) > 0: logging.info(\"Running classification\")",
"logging.info(\"Running classification\") points = classify.main( points, signal_array, background_array, n_free_cpus, voxel_sizes,",
"badly with TensorFlow\" ] def main( signal_array, background_array, voxel_sizes, start_plane=0,",
"= [ \"multiprocessing can interact badly with TensorFlow\" ] def",
"n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth, trained_model, model_weights, network_depth,",
"/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"",
"dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for message in",
"network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth, trained_model, model_weights, network_depth, ) else:",
"home = Path.home() install_path = home / \".cellfinder\" logging.info(\"Detecting cell",
"cell candidates\") points = detect.main( signal_array, start_plane, end_plane, voxel_sizes, soma_diameter,",
"prevent tensorflow being imported before it's warnings are silenced \"\"\"",
"within functions to prevent tensorflow being imported before it's warnings",
"voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1,",
"batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2,",
"16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\" \"\"\"",
"detect from cellfinder_core.classify import classify from cellfinder_core.tools import prep from",
"= Path.home() install_path = home / \".cellfinder\" logging.info(\"Detecting cell candidates\")",
"interact badly with TensorFlow\" ] def main( signal_array, background_array, voxel_sizes,",
"model, n_free_cpus ) if len(points) > 0: logging.info(\"Running classification\") points",
"start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1],",
"trained_model, model_weights, install_path, model, n_free_cpus ) if len(points) > 0:",
"1], soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50,",
"logging.info(\"No candidates, skipping classification\") return points # logging.info(\"Saving classified cells\")",
"n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from",
"end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size,",
"def main( signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\",",
"signal_array, start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor,",
"else: logging.info(\"No candidates, skipping classification\") return points # logging.info(\"Saving classified",
") model_weights = prep.prep_classification( trained_model, model_weights, install_path, model, n_free_cpus )",
"library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for message in tf_suppress_log_messages:",
"import logging from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing",
"points = detect.main( signal_array, start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size,",
"voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth, trained_model, model_weights, network_depth, )",
"cells\") # save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines",
"# save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines of",
"before it's warnings are silenced \"\"\" import os import logging",
"candidates\") points = detect.main( signal_array, start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size,",
"batch_size, cube_height, cube_width, cube_depth, trained_model, model_weights, network_depth, ) else: logging.info(\"No",
"import prep from pathlib import Path home = Path.home() install_path",
"N.B imports are within functions to prevent tensorflow being imported",
"are within functions to prevent tensorflow being imported before it's",
"imports are within functions to prevent tensorflow being imported before",
"prep from pathlib import Path home = Path.home() install_path =",
"pathlib import Path home = Path.home() install_path = home /",
"cellfinder_core.classify import classify from cellfinder_core.tools import prep from pathlib import",
"install_path = home / \".cellfinder\" logging.info(\"Detecting cell candidates\") points =",
"\"\"\" N.B imports are within functions to prevent tensorflow being",
"points # logging.info(\"Saving classified cells\") # save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages):",
"model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6, ball_z_size=15,",
"tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] =",
"<filename>cellfinder_core/main.py<gh_stars>1-10 \"\"\" N.B imports are within functions to prevent tensorflow",
"signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth, trained_model,",
"soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights = prep.prep_classification( trained_model, model_weights,",
"cube_depth, trained_model, model_weights, network_depth, ) else: logging.info(\"No candidates, skipping classification\")",
"start_plane, end_plane, voxel_sizes, soma_diameter, max_cluster_size, ball_xy_size, ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus,",
"return points # logging.info(\"Saving classified cells\") # save_cells(points, classified_points_path) def",
"ball_z_size, ball_overlap_fraction, soma_spread_factor, n_free_cpus, log_sigma_size, n_sds_above_mean_thresh, ) model_weights = prep.prep_classification(",
"to prevent tensorflow being imported before it's warnings are silenced",
"os import logging from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages = [",
"> 0: logging.info(\"Running classification\") points = classify.main( points, signal_array, background_array,",
"): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect from cellfinder_core.classify import classify",
"it's warnings are silenced \"\"\" import os import logging from",
"from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages = [ \"multiprocessing can interact",
"as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default /dso_loader.cc:44] Successfully opened dynamic library",
"soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect",
"import detect from cellfinder_core.classify import classify from cellfinder_core.tools import prep",
"soma_diameter=16, ball_xy_size=6, ball_z_size=15, ball_overlap_fraction=0.6, log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50,",
"opened dynamic library libcuda.so.1\" \"\"\" os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" for message",
"trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32, n_free_cpus=2, network_voxel_sizes=[5, 1, 1], soma_diameter=16, ball_xy_size=6,",
"from cellfinder_core.detect import detect from cellfinder_core.classify import classify from cellfinder_core.tools",
"Path home = Path.home() install_path = home / \".cellfinder\" logging.info(\"Detecting",
"logging.info(\"Detecting cell candidates\") points = detect.main( signal_array, start_plane, end_plane, voxel_sizes,",
"points, signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height, cube_width, cube_depth,",
"save_cells(points, classified_points_path) def suppress_tf_logging(tf_suppress_log_messages): \"\"\" Prevents many lines of logs",
"\"\"\" import os import logging from imlib.general.logging import suppress_specific_logs tf_suppress_log_messages",
"network_depth, ) else: logging.info(\"No candidates, skipping classification\") return points #",
"silenced \"\"\" import os import logging from imlib.general.logging import suppress_specific_logs",
"many lines of logs such as: \"2019-10-24 16:54:41.363978: I tensorflow/stream_executor/platform/default",
"main( signal_array, background_array, voxel_sizes, start_plane=0, end_plane=-1, trained_model=None, model_weights=None, model=\"resnet50_tv\", batch_size=32,",
"network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect from cellfinder_core.classify import",
"from cellfinder_core.classify import classify from cellfinder_core.tools import prep from pathlib",
"Path.home() install_path = home / \".cellfinder\" logging.info(\"Detecting cell candidates\") points",
"= classify.main( points, signal_array, background_array, n_free_cpus, voxel_sizes, network_voxel_sizes, batch_size, cube_height,",
"cellfinder_core.tools import prep from pathlib import Path home = Path.home()",
") if len(points) > 0: logging.info(\"Running classification\") points = classify.main(",
"n_sds_above_mean_thresh, ) model_weights = prep.prep_classification( trained_model, model_weights, install_path, model, n_free_cpus",
"[ \"multiprocessing can interact badly with TensorFlow\" ] def main(",
"log_sigma_size=0.2, n_sds_above_mean_thresh=10, soma_spread_factor=1.4, max_cluster_size=100000, cube_width=50, cube_height=50, cube_depth=20, network_depth=\"50\", ): suppress_tf_logging(tf_suppress_log_messages)",
"suppress_tf_logging(tf_suppress_log_messages) from cellfinder_core.detect import detect from cellfinder_core.classify import classify from",
"if len(points) > 0: logging.info(\"Running classification\") points = classify.main( points,"
] |
[
"= \\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u:",
"flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if number",
"\"youtube\" if \"yt\" in episode else \"facebook\" ) return flask.render_template(template,",
"static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] =",
"os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\")",
"found\" elif number > len(EPISODES): return \"coming soon\" else: episode",
"number] template = \"pages/episode/%s.html\" % ( \"youtube\" if \"yt\" in",
"dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\")",
"yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"]",
"1: return \"not found\" elif number > len(EPISODES): return \"coming",
"app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda str,",
"import dateutil.parser import flask import json import os import time",
"return \"coming soon\" else: episode = EPISODES[len(EPISODES) - number] template",
"\"not found\" elif number > len(EPISODES): return \"coming soon\" else:",
"lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u) ASSETS",
"home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number):",
"yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda",
"\"assets\") @app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\")",
"- number] template = \"pages/episode/%s.html\" % ( \"youtube\" if \"yt\"",
"@app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def",
"coding=utf-8 import dateutil.parser import flask import json import os import",
"number < 1: return \"not found\" elif number > len(EPISODES):",
"else: episode = EPISODES[len(EPISODES) - number] template = \"pages/episode/%s.html\" %",
"favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home(): return",
"urllib import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\",",
"# coding=utf-8 import dateutil.parser import flask import json import os",
"> len(EPISODES): return \"coming soon\" else: episode = EPISODES[len(EPISODES) -",
"% ( \"youtube\" if \"yt\" in episode else \"facebook\" )",
"= \"pages/episode/%s.html\" % ( \"youtube\" if \"yt\" in episode else",
"in episode else \"facebook\" ) return flask.render_template(template, number=number, episode=episode, episodes=EPISODES)",
"return \"not found\" elif number > len(EPISODES): return \"coming soon\"",
"import json import os import time import urllib import yaml",
"= EPISODES[len(EPISODES) - number] template = \"pages/episode/%s.html\" % ( \"youtube\"",
"EPISODES[len(EPISODES) - number] template = \"pages/episode/%s.html\" % ( \"youtube\" if",
"flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt)",
"template = \"pages/episode/%s.html\" % ( \"youtube\" if \"yt\" in episode",
"json import os import time import urllib import yaml EPISODES",
"dateutil.parser import flask import json import os import time import",
"app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\")",
"def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def",
"elif number > len(EPISODES): return \"coming soon\" else: episode =",
"\"pages/episode/%s.html\" % ( \"youtube\" if \"yt\" in episode else \"facebook\"",
"= yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\",
"def episode(number): if number < 1: return \"not found\" elif",
"u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon(): return",
"playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if number <",
"ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory( ASSETS,",
"@app.route(\"/episod/<int:number>\") def episode(number): if number < 1: return \"not found\"",
"episode = EPISODES[len(EPISODES) - number] template = \"pages/episode/%s.html\" % (",
"< 1: return \"not found\" elif number > len(EPISODES): return",
"= flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda str, fmt:",
"episode(number): if number < 1: return \"not found\" elif number",
"mimetype=\"image/icon\") @app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug)",
"\\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u)",
"return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if",
"soon\" else: episode = EPISODES[len(EPISODES) - number] template = \"pages/episode/%s.html\"",
"autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if number < 1: return",
"import urllib import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__,",
"time import urllib import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app =",
"fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path,",
"number > len(EPISODES): return \"coming soon\" else: episode = EPISODES[len(EPISODES)",
"if \"yt\" in episode else \"facebook\" ) return flask.render_template(template, number=number,",
"static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] = \\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"]",
"= os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\",",
"if number < 1: return \"not found\" elif number >",
"EPISODES = yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\") app.jinja_env.filters[\"strftime\"] =",
"import time import urllib import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app",
"import os import time import urllib import yaml EPISODES =",
"flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"],",
"episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if number < 1:",
"flask import json import os import time import urllib import",
"\"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not",
"lambda u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon():",
"@app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES, autoplay=not app.debug) @app.route(\"/episod/<int:number>\")",
"os import time import urllib import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read())",
"app.jinja_env.filters[\"strftime\"] = \\ lambda str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda",
"return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\",",
"import flask import json import os import time import urllib",
"= lambda u: urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def",
"( \"youtube\" if \"yt\" in episode else \"facebook\" ) return",
"app.debug) @app.route(\"/episod/<int:number>\") def episode(number): if number < 1: return \"not",
"len(EPISODES): return \"coming soon\" else: episode = EPISODES[len(EPISODES) - number]",
"ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home(): return flask.render_template(\"pages/home.html\", playlist=os.environ[\"PLAYLIST\"], episodes=EPISODES,",
"urllib.quote_plus(u) ASSETS = os.path.join(app.root_path, \"assets\") @app.route(\"/favicon.ico\") def favicon(): return flask.send_from_directory(",
"\"coming soon\" else: episode = EPISODES[len(EPISODES) - number] template =",
"str, fmt: dateutil.parser.parse(str).strftime(fmt) app.jinja_env.filters[\"quote_plus\"] = lambda u: urllib.quote_plus(u) ASSETS =",
"import yaml EPISODES = yaml.load(open(\"episodes.yaml\").read()) app = flask.Flask(__name__, static_path=\"/assets\", static_folder=\"assets\")",
"\"yt\" in episode else \"facebook\" ) return flask.render_template(template, number=number, episode=episode,",
"def favicon(): return flask.send_from_directory( ASSETS, \"favicon.ico\", mimetype=\"image/icon\") @app.route(\"/\") def home():"
] |
[
"reduce(operator.mul, range(1, number+1)) def digits(number): yield from (int(digit) for digit",
"1 return reduce(operator.mul, range(1, number+1)) def digits(number): yield from (int(digit)",
"* import operator def factorial(number): assert number >= 1 return",
"import * import operator def factorial(number): assert number >= 1",
"return reduce(operator.mul, range(1, number+1)) def digits(number): yield from (int(digit) for",
"assert number >= 1 return reduce(operator.mul, range(1, number+1)) def digits(number):",
"number >= 1 return reduce(operator.mul, range(1, number+1)) def digits(number): yield",
">= 1 return reduce(operator.mul, range(1, number+1)) def digits(number): yield from",
"number+1)) def digits(number): yield from (int(digit) for digit in str(number))",
"def digits(number): yield from (int(digit) for digit in str(number)) print(sum(digits(factorial(100))))",
"range(1, number+1)) def digits(number): yield from (int(digit) for digit in",
"factorial(number): assert number >= 1 return reduce(operator.mul, range(1, number+1)) def",
"import operator def factorial(number): assert number >= 1 return reduce(operator.mul,",
"operator def factorial(number): assert number >= 1 return reduce(operator.mul, range(1,",
"from functools import * import operator def factorial(number): assert number",
"def factorial(number): assert number >= 1 return reduce(operator.mul, range(1, number+1))",
"python3 from functools import * import operator def factorial(number): assert",
"functools import * import operator def factorial(number): assert number >=",
"#!/usr/bin/env python3 from functools import * import operator def factorial(number):"
] |
[
"totally, may be we should keep it keypoints = map_coco_to_personlab(keypoints)",
"original_points[:,:,2]=1 # we reuse 3rd column in completely different way",
"0., 1. ]] ) center2center = np.array( [[ 1., 0.,",
"numpy as np from math import cos, sin, pi import",
"is hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0]",
"-center_y ], [ 0., 0., 1. ]] ) rotate =",
"= width + self.crop[0] center_y = height + self.crop[1] center2zero",
"original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp,",
"0., -center_x], [ 0., 1., -center_y ], [ 0., 0.,",
"cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need to understand this,",
"became left leg, and vice versa if aug.flip: tmpLeft =",
"[[ 1., 0., config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2 ], [",
"= random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\",
"transform(img, masks, keypoints, aug=AugmentSelection.random()): # warp picture and mask M",
"__init__(self, flip=False, degree = 0., crop = (0,0), scale =",
"cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in",
"cos(self.degree / 180. * pi ) B = self.scale *",
"cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat = np.stack(output_transform_targets, axis=-1) #",
"points #TODO: joint could be cropped by augmentation, in this",
"config import config, TransformationParams from data_prep import map_coco_to_personlab class AugmentSelection:",
"could be cropped by augmentation, in this case we should",
"keypoints original_points[:,:,2]=1 # we reuse 3rd column in completely different",
"unrandom(): flip = False degree = 0. scale = 1.",
"scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the main",
"= height + self.crop[1] center2zero = np.array( [[ 1., 0.,",
"else 1. x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.)",
"TransformationParams.target_dist / self.scale (width, height) = center center_x = width",
"of main person divided by 368, caclulated in generate_hdf5.py #",
"flip = False degree = 0. scale = 1. x_offset",
"is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer: @staticmethod",
"this case we should mark it as invisible. #update: may",
"#TODO: joint could be cropped by augmentation, in this case",
"aug.flip: tmpLeft = keypoints[:, config.LEFT_KP, :] tmpRight = keypoints[:, config.RIGHT_KP,",
"= 0 # we just made image flip, i.e. right",
"for i in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC,",
"(x_offset,y_offset), scale) @staticmethod def unrandom(): flip = False degree =",
"crop #shift actually self.scale = scale @staticmethod def random(): flip",
"], [ 0., 0., 1. ]] ) # order of",
"= np.array( [[ 1., 0., -center_x], [ 0., 1., -center_y",
"config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp = np.logical_or(cropped_kp,",
"reuse 3rd column in completely different way here, it is",
"0, 0, 1. ] ]) scale = np.array( [[ scale_size,",
"AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod def unrandom(): flip = False",
"1., config.IMAGE_SHAPE[0]//2 ], [ 0., 0., 1. ]] ) #",
">= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp =",
"keypoints[:, config.LEFT_KP, :] = tmpRight keypoints[:, config.RIGHT_KP, :] = tmpLeft",
"= self.scale * sin(self.degree / 180. * pi ) #",
"import random from config import config, TransformationParams from data_prep import",
"be used to transform joint coordinates afterwards A = self.scale",
"], [ 0, 0, 1. ] ]) scale = np.array(",
"lot of cpu and make code significantly shorter # same",
"removed part sliced more than half totally, may be we",
"in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0)",
"concat = np.stack(output_transform_targets, axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks",
":] = tmpLeft # print keypoints return img, masks, keypoints",
"img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need to understand",
"degree = 0., crop = (0,0), scale = 1.): self.flip",
"leg just became left leg, and vice versa if aug.flip:",
"scale_size = TransformationParams.target_dist / scale_self * self.scale scale_size = TransformationParams.target_dist",
"actually, original code removed part sliced more than half totally,",
"combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer: @staticmethod def transform(img,",
"i in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT,",
"borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]): out_masks[:,:,i] =",
"key points #TODO: joint could be cropped by augmentation, in",
"TransformationParams from data_prep import map_coco_to_personlab class AugmentSelection: def __init__(self, flip=False,",
"completely different way here, it is hack converted_points = np.matmul(M,",
"be we don't need it actually, original code removed part",
"joint could be cropped by augmentation, in this case we",
"one affine matrix. # this saves lot of cpu and",
"y_offset = 0 return AugmentSelection(flip, degree, (x_offset,y_offset), scale) def affine(self,",
"np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp =",
"[[ A, B, 0 ], [ -B, A, 0 ],",
"= keypoints.copy() # print keypoints original_points[:,:,2]=1 # we reuse 3rd",
"0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp, 2] =",
"-center_x], [ 0., 1., -center_y ], [ 0., 0., 1.",
"@staticmethod def unrandom(): flip = False degree = 0. scale",
"config.IMAGE_SHAPE[0]//2 ], [ 0., 0., 1. ]] ) # order",
"A, B, 0 ], [ -B, A, 0 ], [",
"and vice versa if aug.flip: tmpLeft = keypoints[:, config.LEFT_KP, :]",
"\\ if random.uniform(0.,1.) < TransformationParams.scale_prob else 1. x_offset = int(random.uniform(-1.,1.)",
"self.scale * cos(self.degree / 180. * pi ) B =",
"= degree #rotate self.crop = crop #shift actually self.scale =",
"import cos, sin, pi import cv2 import random from config",
"just became left leg, and vice versa if aug.flip: tmpLeft",
"* sin(self.degree / 180. * pi ) # scale_size =",
"person divided by 368, caclulated in generate_hdf5.py # print(img.shape) #",
"center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the main idea: we will",
"-1 if self.flip else 1., 0., 0. ], [ 0.,",
"half totally, may be we should keep it keypoints =",
"def transform(img, masks, keypoints, aug=AugmentSelection.random()): # warp picture and mask",
"self.scale scale_size = TransformationParams.target_dist / self.scale (width, height) = center",
"cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for",
"* TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.)",
"0. ], [ 0., 1., 0. ], [ 0., 0.,",
"= center center_x = width + self.crop[0] center_y = height",
"import map_coco_to_personlab class AugmentSelection: def __init__(self, flip=False, degree = 0.,",
"= 1.): self.flip = flip self.degree = degree #rotate self.crop",
"[ 0., 1., -center_y ], [ 0., 0., 1. ]]",
"]) scale = np.array( [[ scale_size, 0, 0 ], [",
"M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i",
"(config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need to understand this, scale_provided[0] is",
"0., 0., 1. ]] ) # order of combination is",
"# print keypoints original_points[:,:,2]=1 # we reuse 3rd column in",
"(x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the",
"0., crop = (0,0), scale = 1.): self.flip = flip",
"0 # we just made image flip, i.e. right leg",
"it as invisible. #update: may be we don't need it",
"map_coco_to_personlab class AugmentSelection: def __init__(self, flip=False, degree = 0., crop",
"degree #rotate self.crop = crop #shift actually self.scale = scale",
"way here, it is hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points",
"data_prep import map_coco_to_personlab class AugmentSelection: def __init__(self, flip=False, degree =",
"scale_size = TransformationParams.target_dist / self.scale (width, height) = center center_x",
"= tmpRight keypoints[:, config.RIGHT_KP, :] = tmpLeft # print keypoints",
"# TODO: need to understand this, scale_provided[0] is height of",
"-B, A, 0 ], [ 0, 0, 1. ] ])",
"masks, keypoints, aug=AugmentSelection.random()): # warp picture and mask M =",
"0, 1. ] ]) flip = np.array( [[ -1 if",
"# concat = np.stack(output_transform_targets, axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2 #",
"keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp",
"AugmentSelection(flip, degree, (x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.):",
"return AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod def unrandom(): flip =",
"degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min",
"1., -center_y ], [ 0., 0., 1. ]] ) rotate",
"/ scale_self * self.scale scale_size = TransformationParams.target_dist / self.scale (width,",
"= 0 return AugmentSelection(flip, degree, (x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2,",
"class AugmentSelection: def __init__(self, flip=False, degree = 0., crop =",
"TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod def unrandom(): flip",
"1., 0., 0. ], [ 0., 1., 0. ], [",
"= np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2",
"(TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) < TransformationParams.scale_prob else 1.",
"transform joint coordinates afterwards A = self.scale * cos(self.degree /",
"keypoints.copy() # print keypoints original_points[:,:,2]=1 # we reuse 3rd column",
"np from math import cos, sin, pi import cv2 import",
"A, 0 ], [ 0, 0, 1. ] ]) scale",
"TransformationParams.scale_prob else 1. x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset =",
"used to transform joint coordinates afterwards A = self.scale *",
"order of combination is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2]",
"transformations with one affine matrix. # this saves lot of",
"pi import cv2 import random from config import config, TransformationParams",
"= cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat =",
"np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape,",
"], [ -B, A, 0 ], [ 0, 0, 1.",
"cv2 import random from config import config, TransformationParams from data_prep",
"False degree = 0. scale = 1. x_offset = 0",
"(width, height) = center center_x = width + self.crop[0] center_y",
"self.degree = degree #rotate self.crop = crop #shift actually self.scale",
"with one affine matrix. # this saves lot of cpu",
"config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the main idea: we will do",
"scale) @staticmethod def unrandom(): flip = False degree = 0.",
"0, 0 ], [ 0, scale_size, 0 ], [ 0,",
"config.RIGHT_KP, :] = tmpLeft # print keypoints return img, masks,",
"random.uniform(0.,1.) < TransformationParams.scale_prob else 1. x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max);",
"in enumerate(input_transform_targets): img = cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127))",
"368, caclulated in generate_hdf5.py # print(img.shape) # for i, img",
"cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp, 2] = 0",
"scale = 1. x_offset = 0 y_offset = 0 return",
"int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod def",
"], [ 0., 0., 1. ]] ) rotate = np.array(",
"= np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp",
"2] = 0 # we just made image flip, i.e.",
"# masks = cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks",
"# warp picture and mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape",
"is height of main person divided by 368, caclulated in",
"scale_self * self.scale scale_size = TransformationParams.target_dist / self.scale (width, height)",
"def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the main idea:",
">= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp =",
"make code significantly shorter # same affine matrix could be",
"borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks # warp key points #TODO:",
"original code removed part sliced more than half totally, may",
"understand this, scale_provided[0] is height of main person divided by",
"# we just made image flip, i.e. right leg just",
") # order of combination is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero)",
"random from config import config, TransformationParams from data_prep import map_coco_to_personlab",
"center2center = np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2], [ 0., 1.,",
"degree, (x_offset,y_offset), scale) @staticmethod def unrandom(): flip = False degree",
"range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks",
"leg, and vice versa if aug.flip: tmpLeft = keypoints[:, config.LEFT_KP,",
"0., config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2 ], [ 0., 0.,",
"# fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks, M, cv_shape,",
"[ 0, scale_size, 0 ], [ 0, 0, 1. ]",
"axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks, M,",
") # scale_size = TransformationParams.target_dist / scale_self * self.scale scale_size",
"self.flip else 1., 0., 0. ], [ 0., 1., 0.",
"]] ) # order of combination is reversed combined =",
"crop = (0,0), scale = 1.): self.flip = flip self.degree",
"pi ) # scale_size = TransformationParams.target_dist / scale_self * self.scale",
"import numpy as np from math import cos, sin, pi",
"def random(): flip = random.uniform(0.,1.) > TransformationParams.flip_prob degree = random.uniform(-1.,1.)",
"case we should mark it as invisible. #update: may be",
"= TransformationParams.target_dist / self.scale (width, height) = center center_x =",
"]) flip = np.array( [[ -1 if self.flip else 1.,",
"degree = 0. scale = 1. x_offset = 0 y_offset",
"/ 180. * pi ) B = self.scale * sin(self.degree",
"idea: we will do all image transformations with one affine",
"from config import config, TransformationParams from data_prep import map_coco_to_personlab class",
"self.scale (width, height) = center center_x = width + self.crop[0]",
"cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks # warp key",
"invisible. #update: may be we don't need it actually, original",
"enumerate(input_transform_targets): img = cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) #",
"scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) < TransformationParams.scale_prob",
"= flip self.degree = degree #rotate self.crop = crop #shift",
"< 0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp, 2]",
"random.uniform(0.,1.) > TransformationParams.flip_prob degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale =",
"may be we don't need it actually, original code removed",
"= np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M,",
"converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1]",
"# same affine matrix could be used to transform joint",
"center_x = width + self.crop[0] center_y = height + self.crop[1]",
"width + self.crop[0] center_y = height + self.crop[1] center2zero =",
"Transformer: @staticmethod def transform(img, masks, keypoints, aug=AugmentSelection.random()): # warp picture",
"made image flip, i.e. right leg just became left leg,",
"keypoints[:, config.RIGHT_KP, :] = tmpLeft # print keypoints return img,",
"return combined[0:2] class Transformer: @staticmethod def transform(img, masks, keypoints, aug=AugmentSelection.random()):",
"cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >=",
"borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]): out_masks[:,:,i]",
"= np.array( [[ A, B, 0 ], [ -B, A,",
"* pi ) B = self.scale * sin(self.degree / 180.",
"int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip,",
"else 1., 0., 0. ], [ 0., 1., 0. ],",
"we just made image flip, i.e. right leg just became",
"joint coordinates afterwards A = self.scale * cos(self.degree / 180.",
"np.array( [[ scale_size, 0, 0 ], [ 0, scale_size, 0",
"TransformationParams.target_dist / scale_self * self.scale scale_size = TransformationParams.target_dist / self.scale",
"@staticmethod def transform(img, masks, keypoints, aug=AugmentSelection.random()): # warp picture and",
"hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >=",
"0., 1. ]] ) # order of combination is reversed",
"= center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer: @staticmethod def transform(img, masks,",
"AugmentSelection: def __init__(self, flip=False, degree = 0., crop = (0,0),",
"center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer: @staticmethod def transform(img, masks, keypoints,",
"reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer: @staticmethod def",
"scale @staticmethod def random(): flip = random.uniform(0.,1.) > TransformationParams.flip_prob degree",
"return AugmentSelection(flip, degree, (x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) ,",
"sin, pi import cv2 import random from config import config,",
"by 368, caclulated in generate_hdf5.py # print(img.shape) # for i,",
"part sliced more than half totally, may be we should",
"rotate = np.array( [[ A, B, 0 ], [ -B,",
"config.LEFT_KP, :] = tmpRight keypoints[:, config.RIGHT_KP, :] = tmpLeft #",
"0. ], [ 0., 0., 1. ]] ) center2center =",
"we reuse 3rd column in completely different way here, it",
"center2zero = np.array( [[ 1., 0., -center_x], [ 0., 1.,",
"we should mark it as invisible. #update: may be we",
"def __init__(self, flip=False, degree = 0., crop = (0,0), scale",
"[ 0., 0., 1. ]] ) # order of combination",
"math import cos, sin, pi import cv2 import random from",
"scale = 1.): self.flip = flip self.degree = degree #rotate",
"center_y = height + self.crop[1] center2zero = np.array( [[ 1.,",
"need it actually, original code removed part sliced more than",
"be we should keep it keypoints = map_coco_to_personlab(keypoints) original_points =",
"TODO: need to understand this, scale_provided[0] is height of main",
"need to understand this, scale_provided[0] is height of main person",
"cpu and make code significantly shorter # same affine matrix",
"flip=False, degree = 0., crop = (0,0), scale = 1.):",
"height) = center center_x = width + self.crop[0] center_y =",
"borderValue=0) masks = out_masks # warp key points #TODO: joint",
"cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat = np.stack(output_transform_targets,",
"]] ) rotate = np.array( [[ A, B, 0 ],",
"[[ scale_size, 0, 0 ], [ 0, scale_size, 0 ],",
"= aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need",
"#rotate self.crop = crop #shift actually self.scale = scale @staticmethod",
"keypoints[:,:,1] < 0) keypoints[cropped_kp, 2] = 0 # we just",
"1. ] ]) scale = np.array( [[ scale_size, 0, 0",
"and mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0])",
"flip = random.uniform(0.,1.) > TransformationParams.flip_prob degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree",
"i, img in enumerate(input_transform_targets): img = cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC,",
"= 0., crop = (0,0), scale = 1.): self.flip =",
"0 ], [ -B, A, 0 ], [ 0, 0,",
"self.crop = crop #shift actually self.scale = scale @staticmethod def",
"B, 0 ], [ -B, A, 0 ], [ 0,",
"= np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] <",
"[ 0., 0., 1. ]] ) rotate = np.array( [[",
"= keypoints[:, config.LEFT_KP, :] tmpRight = keypoints[:, config.RIGHT_KP, :] keypoints[:,",
"scale_self=1.): # the main idea: we will do all image",
"more than half totally, may be we should keep it",
"flip, i.e. right leg just became left leg, and vice",
"(0,0), scale = 1.): self.flip = flip self.degree = degree",
"def unrandom(): flip = False degree = 0. scale =",
"# print(img.shape) # for i, img in enumerate(input_transform_targets): img =",
"same affine matrix could be used to transform joint coordinates",
"0 return AugmentSelection(flip, degree, (x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2)",
"column in completely different way here, it is hack converted_points",
"as np from math import cos, sin, pi import cv2",
"= np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp, 2] = 0 #",
") rotate = np.array( [[ A, B, 0 ], [",
":] keypoints[:, config.LEFT_KP, :] = tmpRight keypoints[:, config.RIGHT_KP, :] =",
"if random.uniform(0.,1.) < TransformationParams.scale_prob else 1. x_offset = int(random.uniform(-1.,1.) *",
"], [ 0, 0, 1. ] ]) flip = np.array(",
"self.flip = flip self.degree = degree #rotate self.crop = crop",
"code significantly shorter # same affine matrix could be used",
":] tmpRight = keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :] =",
"# the main idea: we will do all image transformations",
"to transform joint coordinates afterwards A = self.scale * cos(self.degree",
"pi ) B = self.scale * sin(self.degree / 180. *",
"[[ 1., 0., -center_x], [ 0., 1., -center_y ], [",
"np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2 ],",
"0., 0., 1. ]] ) center2center = np.array( [[ 1.,",
"np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp, 2] = 0 # we",
"np.array( [[ -1 if self.flip else 1., 0., 0. ],",
"#shift actually self.scale = scale @staticmethod def random(): flip =",
"for i, img in enumerate(input_transform_targets): img = cv2.warpAffine(img, M, cv_shape,",
"np.array( [[ A, B, 0 ], [ -B, A, 0",
"all image transformations with one affine matrix. # this saves",
"np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] < 0)",
"this saves lot of cpu and make code significantly shorter",
"[[ -1 if self.flip else 1., 0., 0. ], [",
"self.crop[0] center_y = height + self.crop[1] center2zero = np.array( [[",
"# scale_size = TransformationParams.target_dist / scale_self * self.scale scale_size =",
"do all image transformations with one affine matrix. # this",
"tmpRight keypoints[:, config.RIGHT_KP, :] = tmpLeft # print keypoints return",
"be cropped by augmentation, in this case we should mark",
"scale_size, 0, 0 ], [ 0, scale_size, 0 ], [",
"> TransformationParams.flip_prob degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max",
"tmpLeft = keypoints[:, config.LEFT_KP, :] tmpRight = keypoints[:, config.RIGHT_KP, :]",
"M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat = np.stack(output_transform_targets, axis=-1)",
"caclulated in generate_hdf5.py # print(img.shape) # for i, img in",
"0, 1. ] ]) scale = np.array( [[ scale_size, 0,",
"1., 0. ], [ 0., 0., 1. ]] ) center2center",
"mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) #",
"TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) <",
"combination is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class Transformer:",
"sliced more than half totally, may be we should keep",
"1. ] ]) flip = np.array( [[ -1 if self.flip",
"/ self.scale (width, height) = center center_x = width +",
"config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2 ], [ 0., 0., 1.",
") B = self.scale * sin(self.degree / 180. * pi",
"cos, sin, pi import cv2 import random from config import",
"# we reuse 3rd column in completely different way here,",
"scale_provided[0] is height of main person divided by 368, caclulated",
"1. ]] ) rotate = np.array( [[ A, B, 0",
"out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks =",
"here, it is hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp",
"flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat = np.stack(output_transform_targets, axis=-1) # fix",
"* self.scale scale_size = TransformationParams.target_dist / self.scale (width, height) =",
", scale_self=1.): # the main idea: we will do all",
"fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC,",
"mark it as invisible. #update: may be we don't need",
"just made image flip, i.e. right leg just became left",
"img in enumerate(input_transform_targets): img = cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT,",
") center2center = np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2], [ 0.,",
"borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat = np.stack(output_transform_targets, axis=-1) # fix from",
"= np.stack(output_transform_targets, axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks =",
"i.e. right leg just became left leg, and vice versa",
"B = self.scale * sin(self.degree / 180. * pi )",
"img = cv2.warpAffine(img, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=(127,127,127)) # concat",
"it is hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1]) keypoints[:,:,0:2]=converted_points cropped_kp =",
"by augmentation, in this case we should mark it as",
"affine matrix. # this saves lot of cpu and make",
"[ 0., 1., config.IMAGE_SHAPE[0]//2 ], [ 0., 0., 1. ]]",
"to understand this, scale_provided[0] is height of main person divided",
"import config, TransformationParams from data_prep import map_coco_to_personlab class AugmentSelection: def",
"in completely different way here, it is hack converted_points =",
"<reponame>ghafran/KerasPersonLab import numpy as np from math import cos, sin,",
"height + self.crop[1] center2zero = np.array( [[ 1., 0., -center_x],",
"degree, (x_offset,y_offset), scale) def affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): #",
"significantly shorter # same affine matrix could be used to",
"0 ], [ 0, 0, 1. ] ]) scale =",
"we should keep it keypoints = map_coco_to_personlab(keypoints) original_points = keypoints.copy()",
"borderValue=(127,127,127)) # concat = np.stack(output_transform_targets, axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2",
"in this case we should mark it as invisible. #update:",
"+ self.crop[0] center_y = height + self.crop[1] center2zero = np.array(",
"should keep it keypoints = map_coco_to_personlab(keypoints) original_points = keypoints.copy() #",
"afterwards A = self.scale * cos(self.degree / 180. * pi",
"/ 180. * pi ) # scale_size = TransformationParams.target_dist /",
"random(): flip = random.uniform(0.,1.) > TransformationParams.flip_prob degree = random.uniform(-1.,1.) *",
"0. scale = 1. x_offset = 0 y_offset = 0",
"np.array( [[ 1., 0., -center_x], [ 0., 1., -center_y ],",
"self.scale * sin(self.degree / 180. * pi ) # scale_size",
"* pi ) # scale_size = TransformationParams.target_dist / scale_self *",
"np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] < 0)",
"1. ]] ) center2center = np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2],",
"keypoints[:, config.LEFT_KP, :] tmpRight = keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP,",
"] ]) flip = np.array( [[ -1 if self.flip else",
"original_points = keypoints.copy() # print keypoints original_points[:,:,2]=1 # we reuse",
"keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp",
"picture and mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1],",
"config.IMAGE_SHAPE[0]) # TODO: need to understand this, scale_provided[0] is height",
"self.crop[1] center2zero = np.array( [[ 1., 0., -center_x], [ 0.,",
"flip = np.array( [[ -1 if self.flip else 1., 0.,",
"affine matrix could be used to transform joint coordinates afterwards",
"keypoints = map_coco_to_personlab(keypoints) original_points = keypoints.copy() # print keypoints original_points[:,:,2]=1",
"< TransformationParams.scale_prob else 1. x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset",
"cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] < 0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1]",
"# this saves lot of cpu and make code significantly",
"it actually, original code removed part sliced more than half",
"config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :] = tmpRight keypoints[:, config.RIGHT_KP, :]",
"* TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip, degree,",
"center center_x = width + self.crop[0] center_y = height +",
"main person divided by 368, caclulated in generate_hdf5.py # print(img.shape)",
"print(img.shape) # for i, img in enumerate(input_transform_targets): img = cv2.warpAffine(img,",
"keypoints[:,:,0:2]=converted_points cropped_kp = keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1]",
"= cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks",
"= self.scale * cos(self.degree / 180. * pi ) B",
"shorter # same affine matrix could be used to transform",
"* cos(self.degree / 180. * pi ) B = self.scale",
"0, 0, 1. ] ]) flip = np.array( [[ -1",
"keypoints, aug=AugmentSelection.random()): # warp picture and mask M = aug.affine(center=(img.shape[1]//2,",
"[ 0., 1., 0. ], [ 0., 0., 1. ]]",
"= 1. x_offset = 0 y_offset = 0 return AugmentSelection(flip,",
"matrix. # this saves lot of cpu and make code",
"masks = cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks =",
"], [ 0, scale_size, 0 ], [ 0, 0, 1.",
"out_masks # warp key points #TODO: joint could be cropped",
"1. x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) *",
"different way here, it is hack converted_points = np.matmul(M, original_points.transpose([0,2,1])).transpose([0,2,1])",
"if self.flip else 1., 0., 0. ], [ 0., 1.,",
"import cv2 import random from config import config, TransformationParams from",
"map_coco_to_personlab(keypoints) original_points = keypoints.copy() # print keypoints original_points[:,:,2]=1 # we",
"coordinates afterwards A = self.scale * cos(self.degree / 180. *",
"print keypoints original_points[:,:,2]=1 # we reuse 3rd column in completely",
"than half totally, may be we should keep it keypoints",
"it keypoints = map_coco_to_personlab(keypoints) original_points = keypoints.copy() # print keypoints",
"], [ 0., 1., 0. ], [ 0., 0., 1.",
"scale_size, 0 ], [ 0, 0, 1. ] ]) flip",
"height of main person divided by 368, caclulated in generate_hdf5.py",
"cv2.warpAffine(masks[:,:,i], M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks #",
"= int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return",
"], [ 0., 0., 1. ]] ) center2center = np.array(",
"@staticmethod def random(): flip = random.uniform(0.,1.) > TransformationParams.flip_prob degree =",
"0., 1. ]] ) rotate = np.array( [[ A, B,",
"= (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need to understand this, scale_provided[0]",
"sin(self.degree / 180. * pi ) # scale_size = TransformationParams.target_dist",
"aug=AugmentSelection.random()): # warp picture and mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2))",
"as invisible. #update: may be we don't need it actually,",
"= crop #shift actually self.scale = scale @staticmethod def random():",
"warp picture and mask M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape =",
"= (0,0), scale = 1.): self.flip = flip self.degree =",
"versa if aug.flip: tmpLeft = keypoints[:, config.LEFT_KP, :] tmpRight =",
"180. * pi ) # scale_size = TransformationParams.target_dist / scale_self",
"from math import cos, sin, pi import cv2 import random",
"= np.array( [[ -1 if self.flip else 1., 0., 0.",
"y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset), scale)",
"M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks # warp",
"< 0) keypoints[cropped_kp, 2] = 0 # we just made",
"from https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT,",
"180. * pi ) B = self.scale * sin(self.degree /",
"flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) masks = out_masks # warp key points",
"keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :] = tmpRight keypoints[:, config.RIGHT_KP,",
"random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if",
":] = tmpRight keypoints[:, config.RIGHT_KP, :] = tmpLeft # print",
"0., 0. ], [ 0., 1., 0. ], [ 0.,",
"flip self.degree = degree #rotate self.crop = crop #shift actually",
"affine(self, center=(config.IMAGE_SHAPE[1]//2, config.IMAGE_SHAPE[0]//2) , scale_self=1.): # the main idea: we",
"combined[0:2] class Transformer: @staticmethod def transform(img, masks, keypoints, aug=AugmentSelection.random()): #",
"# order of combination is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return",
"[ 0, 0, 1. ] ]) flip = np.array( [[",
"config.LEFT_KP, :] tmpRight = keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :]",
"class Transformer: @staticmethod def transform(img, masks, keypoints, aug=AugmentSelection.random()): # warp",
"will do all image transformations with one affine matrix. #",
"0., 1., config.IMAGE_SHAPE[0]//2 ], [ 0., 0., 1. ]] )",
"saves lot of cpu and make code significantly shorter #",
"divided by 368, caclulated in generate_hdf5.py # print(img.shape) # for",
"= (TransformationParams.scale_max - TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) < TransformationParams.scale_prob else",
"TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) < TransformationParams.scale_prob else 1. x_offset =",
"masks = out_masks # warp key points #TODO: joint could",
"warp key points #TODO: joint could be cropped by augmentation,",
"we don't need it actually, original code removed part sliced",
"1., 0., config.IMAGE_SHAPE[1]//2], [ 0., 1., config.IMAGE_SHAPE[0]//2 ], [ 0.,",
"= 0. scale = 1. x_offset = 0 y_offset =",
"]] ) center2center = np.array( [[ 1., 0., config.IMAGE_SHAPE[1]//2], [",
"= int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod",
"vice versa if aug.flip: tmpLeft = keypoints[:, config.LEFT_KP, :] tmpRight",
"should mark it as invisible. #update: may be we don't",
"= map_coco_to_personlab(keypoints) original_points = keypoints.copy() # print keypoints original_points[:,:,2]=1 #",
"= keypoints[:,:,0] >= config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0])",
"cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0]",
"don't need it actually, original code removed part sliced more",
"cropped by augmentation, in this case we should mark it",
"could be used to transform joint coordinates afterwards A =",
"scale = np.array( [[ scale_size, 0, 0 ], [ 0,",
"0., 0., 1. ]] ) rotate = np.array( [[ A,",
"1., 0., -center_x], [ 0., 1., -center_y ], [ 0.,",
"out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]): out_masks[:,:,i] = cv2.warpAffine(masks[:,:,i],",
"= 0 y_offset = 0 return AugmentSelection(flip, degree, (x_offset,y_offset), scale)",
"main idea: we will do all image transformations with one",
"keep it keypoints = map_coco_to_personlab(keypoints) original_points = keypoints.copy() # print",
"+ self.crop[1] center2zero = np.array( [[ 1., 0., -center_x], [",
"0) keypoints[cropped_kp, 2] = 0 # we just made image",
"of combination is reversed combined = center2center.dot(flip).dot(scale).dot(rotate).dot(center2zero) return combined[0:2] class",
"= np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,0] <",
"1. ]] ) # order of combination is reversed combined",
"if aug.flip: tmpLeft = keypoints[:, config.LEFT_KP, :] tmpRight = keypoints[:,",
"keypoints[:,:,0] < 0) cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] < 0) keypoints[cropped_kp,",
"= scale @staticmethod def random(): flip = random.uniform(0.,1.) > TransformationParams.flip_prob",
"from data_prep import map_coco_to_personlab class AugmentSelection: def __init__(self, flip=False, degree",
"A = self.scale * cos(self.degree / 180. * pi )",
"flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],)) for i in range(masks.shape[-1]):",
"= random.uniform(0.,1.) > TransformationParams.flip_prob degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale",
"the main idea: we will do all image transformations with",
"actually self.scale = scale @staticmethod def random(): flip = random.uniform(0.,1.)",
"aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO: need to",
"#update: may be we don't need it actually, original code",
"- TransformationParams.scale_min)*random.uniform(0.,1.)+TransformationParams.scale_min \\ if random.uniform(0.,1.) < TransformationParams.scale_prob else 1. x_offset",
"[ -B, A, 0 ], [ 0, 0, 1. ]",
"[ 0., 0., 1. ]] ) center2center = np.array( [[",
"# warp key points #TODO: joint could be cropped by",
"code removed part sliced more than half totally, may be",
"x_offset = 0 y_offset = 0 return AugmentSelection(flip, degree, (x_offset,y_offset),",
"np.stack(output_transform_targets, axis=-1) # fix from https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks,",
"= out_masks # warp key points #TODO: joint could be",
"image transformations with one affine matrix. # this saves lot",
"= False degree = 0. scale = 1. x_offset =",
"this, scale_provided[0] is height of main person divided by 368,",
"0, scale_size, 0 ], [ 0, 0, 1. ] ])",
"in generate_hdf5.py # print(img.shape) # for i, img in enumerate(input_transform_targets):",
"x_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max);",
"[ 0, 0, 1. ] ]) scale = np.array( [[",
"matrix could be used to transform joint coordinates afterwards A",
"right leg just became left leg, and vice versa if",
"0., 1., 0. ], [ 0., 0., 1. ]] )",
"keypoints[cropped_kp, 2] = 0 # we just made image flip,",
"https://github.com/octiapp/KerasPersonLab/issues/2 # masks = cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0)",
"TransformationParams.center_perterb_max); y_offset = int(random.uniform(-1.,1.) * TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset),",
"* TransformationParams.center_perterb_max); return AugmentSelection(flip, degree, (x_offset,y_offset), scale) @staticmethod def unrandom():",
"= cv2.warpAffine(masks, M, cv_shape, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue=0) out_masks = np.zeros(cv_shape[::-1]+(masks.shape[-1],))",
"= keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :] = tmpRight keypoints[:,",
"tmpRight = keypoints[:, config.RIGHT_KP, :] keypoints[:, config.LEFT_KP, :] = tmpRight",
"= np.array( [[ scale_size, 0, 0 ], [ 0, scale_size,",
"3rd column in completely different way here, it is hack",
"0., 1., -center_y ], [ 0., 0., 1. ]] )",
"augmentation, in this case we should mark it as invisible.",
"we will do all image transformations with one affine matrix.",
"0 ], [ 0, scale_size, 0 ], [ 0, 0,",
"left leg, and vice versa if aug.flip: tmpLeft = keypoints[:,",
"# for i, img in enumerate(input_transform_targets): img = cv2.warpAffine(img, M,",
"0 ], [ 0, 0, 1. ] ]) flip =",
"M = aug.affine(center=(img.shape[1]//2, img.shape[0]//2)) cv_shape = (config.IMAGE_SHAPE[1], config.IMAGE_SHAPE[0]) # TODO:",
"and make code significantly shorter # same affine matrix could",
"generate_hdf5.py # print(img.shape) # for i, img in enumerate(input_transform_targets): img",
"= TransformationParams.target_dist / scale_self * self.scale scale_size = TransformationParams.target_dist /",
"self.scale = scale @staticmethod def random(): flip = random.uniform(0.,1.) >",
"of cpu and make code significantly shorter # same affine",
"1. x_offset = 0 y_offset = 0 return AugmentSelection(flip, degree,",
"] ]) scale = np.array( [[ scale_size, 0, 0 ],",
"config, TransformationParams from data_prep import map_coco_to_personlab class AugmentSelection: def __init__(self,",
"image flip, i.e. right leg just became left leg, and",
"1.): self.flip = flip self.degree = degree #rotate self.crop =",
"TransformationParams.flip_prob degree = random.uniform(-1.,1.) * TransformationParams.max_rotate_degree scale = (TransformationParams.scale_max -",
"may be we should keep it keypoints = map_coco_to_personlab(keypoints) original_points",
"config.IMAGE_SHAPE[1] cropped_kp = np.logical_or(cropped_kp, keypoints[:,:,1] >= config.IMAGE_SHAPE[0]) cropped_kp = np.logical_or(cropped_kp,",
"0 y_offset = 0 return AugmentSelection(flip, degree, (x_offset,y_offset), scale) def"
] |
[
"(C) 2020 MIZUNO Tadahaya' __version__ = '1.0.3' __license__ = 'MIT'",
"FET from .gsea import GSEA from .ssgsea import ssGSEA __copyright__",
"__copyright__ = 'Copyright (C) 2020 MIZUNO Tadahaya' __version__ = '1.0.3'",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Dec",
"from .binom import BT from .connect import Connect from .fet",
"Tadahaya' __version__ = '1.0.3' __license__ = 'MIT' __author__ = '<NAME>'",
"25 15:46:32 2019 @author: tadahaya \"\"\" from .binom import BT",
"utf-8 -*- \"\"\" Created on Wed Dec 25 15:46:32 2019",
"'1.0.3' __license__ = 'MIT' __author__ = '<NAME>' __author_email__ = '<EMAIL>'",
"from .ssgsea import ssGSEA __copyright__ = 'Copyright (C) 2020 MIZUNO",
"@author: tadahaya \"\"\" from .binom import BT from .connect import",
".binom import BT from .connect import Connect from .fet import",
"Connect from .fet import FET from .gsea import GSEA from",
"\"\"\" from .binom import BT from .connect import Connect from",
"2020 MIZUNO Tadahaya' __version__ = '1.0.3' __license__ = 'MIT' __author__",
"= '1.0.3' __license__ = 'MIT' __author__ = '<NAME>' __author_email__ =",
"GSEA from .ssgsea import ssGSEA __copyright__ = 'Copyright (C) 2020",
"BT from .connect import Connect from .fet import FET from",
"import Connect from .fet import FET from .gsea import GSEA",
"import GSEA from .ssgsea import ssGSEA __copyright__ = 'Copyright (C)",
"__version__ = '1.0.3' __license__ = 'MIT' __author__ = '<NAME>' __author_email__",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Dec 25",
"Dec 25 15:46:32 2019 @author: tadahaya \"\"\" from .binom import",
".gsea import GSEA from .ssgsea import ssGSEA __copyright__ = 'Copyright",
"'Copyright (C) 2020 MIZUNO Tadahaya' __version__ = '1.0.3' __license__ =",
".fet import FET from .gsea import GSEA from .ssgsea import",
"import BT from .connect import Connect from .fet import FET",
".connect import Connect from .fet import FET from .gsea import",
"Created on Wed Dec 25 15:46:32 2019 @author: tadahaya \"\"\"",
"15:46:32 2019 @author: tadahaya \"\"\" from .binom import BT from",
".ssgsea import ssGSEA __copyright__ = 'Copyright (C) 2020 MIZUNO Tadahaya'",
"tadahaya \"\"\" from .binom import BT from .connect import Connect",
"coding: utf-8 -*- \"\"\" Created on Wed Dec 25 15:46:32",
"MIZUNO Tadahaya' __version__ = '1.0.3' __license__ = 'MIT' __author__ =",
"import ssGSEA __copyright__ = 'Copyright (C) 2020 MIZUNO Tadahaya' __version__",
"from .fet import FET from .gsea import GSEA from .ssgsea",
"\"\"\" Created on Wed Dec 25 15:46:32 2019 @author: tadahaya",
"Wed Dec 25 15:46:32 2019 @author: tadahaya \"\"\" from .binom",
"from .connect import Connect from .fet import FET from .gsea",
"import FET from .gsea import GSEA from .ssgsea import ssGSEA",
"on Wed Dec 25 15:46:32 2019 @author: tadahaya \"\"\" from",
"= 'Copyright (C) 2020 MIZUNO Tadahaya' __version__ = '1.0.3' __license__",
"from .gsea import GSEA from .ssgsea import ssGSEA __copyright__ =",
"ssGSEA __copyright__ = 'Copyright (C) 2020 MIZUNO Tadahaya' __version__ =",
"-*- \"\"\" Created on Wed Dec 25 15:46:32 2019 @author:",
"2019 @author: tadahaya \"\"\" from .binom import BT from .connect"
] |
[
"Caillou and ZeusHay; :license: MIT, see LICENSE for more details.",
"* from .params import * from .notify import * from",
"Helper Files ~~~~~~~~~~~~~~~~~~~ All Helper Files used in Selfium project;",
"import * from .getGuild import * from .params import *",
"2021 - Caillou and ZeusHay; :license: MIT, see LICENSE for",
"(c) 2021 - Caillou and ZeusHay; :license: MIT, see LICENSE",
".getUser import * from .getGuild import * from .params import",
".notify import * from .sendEmbed import * from .isStaff import",
"ZeusHay; :license: MIT, see LICENSE for more details. \"\"\" from",
"Selfium Helper Files ~~~~~~~~~~~~~~~~~~~ All Helper Files used in Selfium",
"used in Selfium project; :copyright: (c) 2021 - Caillou and",
"MIT, see LICENSE for more details. \"\"\" from .getUser import",
"Helper Files used in Selfium project; :copyright: (c) 2021 -",
"import * from .notify import * from .sendEmbed import *",
"from .params import * from .notify import * from .sendEmbed",
"project; :copyright: (c) 2021 - Caillou and ZeusHay; :license: MIT,",
"LICENSE for more details. \"\"\" from .getUser import * from",
"\"\"\" Selfium Helper Files ~~~~~~~~~~~~~~~~~~~ All Helper Files used in",
"from .notify import * from .sendEmbed import * from .isStaff",
"- Caillou and ZeusHay; :license: MIT, see LICENSE for more",
"Files used in Selfium project; :copyright: (c) 2021 - Caillou",
"All Helper Files used in Selfium project; :copyright: (c) 2021",
"Files ~~~~~~~~~~~~~~~~~~~ All Helper Files used in Selfium project; :copyright:",
"* from .getGuild import * from .params import * from",
"\"\"\" from .getUser import * from .getGuild import * from",
":license: MIT, see LICENSE for more details. \"\"\" from .getUser",
"~~~~~~~~~~~~~~~~~~~ All Helper Files used in Selfium project; :copyright: (c)",
"from .getGuild import * from .params import * from .notify",
".getGuild import * from .params import * from .notify import",
"more details. \"\"\" from .getUser import * from .getGuild import",
"<filename>app/helpers/__init__.py \"\"\" Selfium Helper Files ~~~~~~~~~~~~~~~~~~~ All Helper Files used",
"import * from .sendEmbed import * from .isStaff import *",
":copyright: (c) 2021 - Caillou and ZeusHay; :license: MIT, see",
"and ZeusHay; :license: MIT, see LICENSE for more details. \"\"\"",
"in Selfium project; :copyright: (c) 2021 - Caillou and ZeusHay;",
"see LICENSE for more details. \"\"\" from .getUser import *",
"import * from .params import * from .notify import *",
"* from .notify import * from .sendEmbed import * from",
"details. \"\"\" from .getUser import * from .getGuild import *",
".params import * from .notify import * from .sendEmbed import",
"Selfium project; :copyright: (c) 2021 - Caillou and ZeusHay; :license:",
"for more details. \"\"\" from .getUser import * from .getGuild",
"from .getUser import * from .getGuild import * from .params"
] |
[
"cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr(",
"args.max_img_len, 1], # v_mask [-1, args.max_seq_len, 1], # t_mask [-1,",
"args.max_seq_len], # input_mask [-1, args.max_img_len, 1], # v_mask [-1, args.max_seq_len,",
"% (args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\"",
"= UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text,",
"probs def init_delta(input, mask, shape, name='text'): real_seq_len = fluid.layers.shape(input)[1] fake",
"\"cls_out_b_0\"] feats = fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr(",
"v in graph_vars.items(): v.persistable = False return pyreader, graph_vars def",
"2.0 (the \"License\"); # you may not use this file",
"2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under",
"kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence (See SMART, Sec 3.1) q_logits:",
"(1 - exceed_mask) delta = delta * reweights delta_grad.stop_gradient=True return",
"fluid.layers.mean(x=ce_loss) / adv_step return loss, logits, probs def init_delta(input, mask,",
"0, 0, 0, 0, 0, 0] pyreader = fluid.layers.py_reader( capacity=70,",
"= init_delta(image_embedding, v_mask, image_emb_shape, name='img') else: text_delta, image_delta = None,",
"{\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input = {\"image_embedding\": image_embedding,",
"logit_image) cur_loss = loss_pure + loss_text + loss_image + kl_adv_text_loss",
"delta_grad / delta_norm # projection if adv_max_norm > 0: exceed_mask",
"= [\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0],",
"[-1, args.max_seq_len, 1], # sent_ids [-1, args.max_img_len + args.max_seq_len, args.max_img_len",
"import glue_eval from collections import OrderedDict from utils.utils import print_eval_log",
"reweights delta_grad.stop_gradient=True return delta loss = None for iter in",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']] image_delta",
"__future__ import division from __future__ import print_function import os import",
"probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss) /",
"% (args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time)) ret = OrderedDict() ret['phase']",
"kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq =",
"\\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8))",
"= UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text =",
"= cur_loss if loss is None else loss + cur_loss",
"division from __future__ import print_function import os import glob import",
"ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss)",
"and # limitations under the License. \"\"\"Model for visual_entailment.\"\"\" from",
"= [-1, args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids, t_mask, text_emb_shape, name='text')",
"limitations under the License. \"\"\"Model for visual_entailment.\"\"\" from __future__ import",
"starts=[0], ends=real_seq_len) delta = delta * mask_slice mag = adv_init_mag",
"time.sleep(1) continue else: break all_mats = [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\"",
"import paddle.fluid as fluid from model.unimo_finetune import UNIMOModel from eval",
"adv_step return loss, logits, probs def init_delta(input, mask, shape, name='text'):",
"ret['used_time'] = round(time_end - time_begin, 4) metrics = OrderedDict() metrics[\"simple_accuracy\"]",
"use this file except in compliance with the License. #",
"import UNIMOModel from eval import glue_eval from collections import OrderedDict",
"tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer =",
"pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids,",
"+ (1 - exceed_mask) delta = delta * reweights delta_grad.stop_gradient=True",
"p = fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)),",
"else: break all_mats = [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir,",
"projection if adv_max_norm > 0: exceed_mask = (delta_norm > adv_max_norm).astype('float32')",
"UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text = UNIMOModel(",
"# pos_ids [-1, args.max_seq_len, 1], # sent_ids [-1, args.max_img_len +",
"permissions and # limitations under the License. \"\"\"Model for visual_entailment.\"\"\"",
"kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure + loss_text + loss_image +",
"init_delta(input, mask, shape, name='text'): real_seq_len = fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\",",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1,",
"\\ = fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\":",
"cur_time)) ret = OrderedDict() ret['phase'] = eval_phase ret['loss'] = -1",
"License. # You may obtain a copy of the License",
"import print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence (See SMART,",
"all_mat = [] test_pyreader.start() time_begin = time.time() fetch_list = [graph_vars[\"probs\"].name,",
"return vat_loss def create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes =",
"delta_norm) * exceed_mask + (1 - exceed_mask) delta = delta",
"for iter in range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config,",
"1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines() if len(ret) !=",
"under the License is distributed on an \"AS IS\" BASIS,",
"size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs =",
"loss = fluid.layers.mean(x=ce_loss) / adv_step return loss, logits, probs def",
"text_delta, image_delta = None, None def pgd_with_l2(loss, delta): # grad",
"from eval import glue_eval from collections import OrderedDict from utils.utils",
"License for the specific language governing permissions and # limitations",
"logits p_logits: delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits)",
"delta = fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta = delta *",
"weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output()",
"eval_phase, dev_count, gpu_id) np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir,",
"+ cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs)",
"kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss =",
"= \\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step >",
"[\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)),",
"- fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)),",
"ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics)) return ret else:",
"= fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.)))",
"= [] test_pyreader.start() time_begin = time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name]",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"[-1, args.max_seq_len, 1], # t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding",
"\"\"\" symmetric KL-divergence (See SMART, Sec 3.1) q_logits: logits p_logits:",
"= delta * mag return delta if is_train: text_emb_shape =",
"0: exceed_mask = (delta_norm > adv_max_norm).astype('float32') reweights = (adv_max_norm /",
"ret = os.popen('find %s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir,",
"cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.*",
"3.1) q_logits: logits p_logits: delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits) p",
"exe, test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat = []",
"p_logits): \"\"\" symmetric KL-divergence (See SMART, Sec 3.1) q_logits: logits",
"logits = fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1],",
"'float32','float32', 'int64'] lod_levels = [0, 0, 0, 0, 0, 0,",
"probs_pure, \"accuracy\": accuracy, \"labels\": labels, \"num_seqs\": num_seqs } for k,",
"-1) kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss",
"[[-1, args.max_seq_len, 1], # src_ids [-1, args.max_seq_len, 1], # pos_ids",
"args.adv_init_mag assert adv_step > 0 and adv_init_mag > 0 def",
"* reweights delta_grad.stop_gradient=True return delta loss = None for iter",
"h_image_image) if is_train: text_delta = pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image,",
"args.max_seq_len, 1], # pos_ids [-1, args.max_seq_len, 1], # sent_ids [-1,",
"from __future__ import absolute_import from __future__ import division from __future__",
"= None for iter in range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids,",
"in compliance with the License. # You may obtain a",
"[-1, args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask, image_emb_shape, name='img') else:",
"= delta + adv_lr * delta_grad / delta_norm # projection",
"software # distributed under the License is distributed on an",
"OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics in metrics: ret_metric =",
"os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir,",
"'float32', 'float32','float32', 'int64'] lod_levels = [0, 0, 0, 0, 0,",
"graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start() time_begin",
"as fluid from model.unimo_finetune import UNIMOModel from eval import glue_eval",
"str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" %",
"init_delta(image_embedding, v_mask, image_emb_shape, name='img') else: text_delta, image_delta = None, None",
"size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout(",
"= np.array(all_mat) time_end = time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir,",
"mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1,",
"else: text_delta, image_delta = None, None def pgd_with_l2(loss, delta): #",
"min=float(1e-8)) # pgd delta = delta + adv_lr * delta_grad",
"0, 0] pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name,",
"axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1]",
"vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure,",
"args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step > 0 and adv_init_mag",
"image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss",
"np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1, 1)) mat",
"adv_init_mag > 0 def get_loss_and_logits(text_feats, image_feats): feats = text_feats +",
"print_function import os import glob import time import numpy as",
"time import numpy as np import paddle.fluid as fluid from",
"fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q) -",
"name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats, dropout_prob=0.1,",
"delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta = delta +",
"pos_ids [-1, args.max_seq_len, 1], # sent_ids [-1, args.max_img_len + args.max_seq_len,",
"np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count, gpu_id)",
"if len(ret) != dev_count: time.sleep(1) continue else: break all_mats =",
"dev_count)) for cur_save_file in save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats",
"[-1, 1] # labels ] dtypes = ['int64', 'int64', 'int64',",
"param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy(",
"> 0 def get_loss_and_logits(text_feats, image_feats): feats = text_feats + image_feats",
"None, None def pgd_with_l2(loss, delta): # grad delta_grad = fluid.backward.gradients(loss,",
"axes=[1], starts=[0], ends=real_seq_len) delta = delta * mask_slice mag =",
"all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break all_mat = np.array(all_mat) time_end =",
"\"loss\": loss, \"probs\": probs_pure, \"accuracy\": accuracy, \"labels\": labels, \"num_seqs\": num_seqs",
"= OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics in metrics: ret_metric",
"loss is None else loss + cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64')",
"/ adv_step return loss, logits, probs def init_delta(input, mask, shape,",
"pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image)",
"axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds, np_labels],",
"None def pgd_with_l2(loss, delta): # grad delta_grad = fluid.backward.gradients(loss, delta)[0]",
"governing permissions and # limitations under the License. \"\"\"Model for",
"h_text_image) loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta",
"fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta = delta * mask_slice mag",
"def pgd_with_l2(loss, delta): # grad delta_grad = fluid.backward.gradients(loss, delta)[0] #",
"vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text",
"args.max_seq_len, 1], # sent_ids [-1, args.max_img_len + args.max_seq_len, args.max_img_len +",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"eval import glue_eval from collections import OrderedDict from utils.utils import",
"'int64', 'int64', 'float32', 'float32', 'float32', 'float32','float32', 'int64'] lod_levels = [0,",
"def init_delta(input, mask, shape, name='text'): real_seq_len = fluid.layers.shape(input)[1] fake =",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"q_logits: logits p_logits: delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits) p =",
"def create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len,",
"graph_vars = { \"loss\": loss, \"probs\": probs_pure, \"accuracy\": accuracy, \"labels\":",
"except fluid.core.EOFException: test_pyreader.reset() break all_mat = np.array(all_mat) time_end = time.time()",
"# input_mask [-1, args.max_img_len, 1], # v_mask [-1, args.max_seq_len, 1],",
"glue_eval.simple_accuracy if args.eval_mertrics in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:,",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"- exceed_mask) delta = delta * reweights delta_grad.stop_gradient=True return delta",
"to in writing, software # distributed under the License is",
"in range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing",
"(args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase, dev_count, args.eval_dir,",
"# See the License for the specific language governing permissions",
"pos_ids} image_input = {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr, norm_type,",
"probs_image = get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta = pgd_with_l2(loss_text, text_delta)",
"% (args.eval_dir, eval_phase, dev_count)).readlines() if len(ret) != dev_count: time.sleep(1) continue",
"* (fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p)",
"= fluid.layers.mean(x=ce_loss) / adv_step return loss, logits, probs def init_delta(input,",
"mat = np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break",
"dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start() time_begin = time.time()",
"or agreed to in writing, software # distributed under the",
"loss = cur_loss if loss is None else loss +",
"metrics = OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics in metrics:",
"\"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file, all_mat) tmp_file =",
"required by applicable law or agreed to in writing, software",
"emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image = UNIMOModel( image_adv_delta=image_delta,",
"dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask, v_mask, t_mask,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"0, 0, 0, 0, 0, 0, 0, 0] pyreader =",
"input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs",
"= fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids,",
"exceed_mask + (1 - exceed_mask) delta = delta * reweights",
"fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss) / adv_step return",
"with the License. # You may obtain a copy of",
"num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars =",
"= [-1, args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask, image_emb_shape, name='img')",
"total=num_seqs) graph_vars = { \"loss\": loss, \"probs\": probs_pure, \"accuracy\": accuracy,",
"args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step > 0 and adv_init_mag >",
"dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc( input=feats, size=args.num_labels,",
"cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr(",
"as np import paddle.fluid as fluid from model.unimo_finetune import UNIMOModel",
"(args.eval_dir, eval_phase, dev_count)).readlines() if len(ret) != dev_count: time.sleep(1) continue else:",
"shape, name='text'): real_seq_len = fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32')",
"= fluid.backward.gradients(loss, delta)[0] # l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\",
"sent_ids [-1, args.max_img_len + args.max_seq_len, args.max_img_len + args.max_seq_len], # input_mask",
"real_seq_len = fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice =",
"input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats =",
"dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc( input=feats,",
"-name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines() if len(ret) != dev_count:",
"delta): # grad delta_grad = fluid.backward.gradients(loss, delta)[0] # l2 norm",
"mask, shape, name='text'): real_seq_len = fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape,",
"return delta if is_train: text_emb_shape = [-1, args.max_seq_len, config['hidden_size']] text_delta",
"__future__ import print_function import os import glob import time import",
"from model.unimo_finetune import UNIMOModel from eval import glue_eval from collections",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file, all_mat)",
"norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True))",
"(c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed",
"distributed under the License is distributed on an \"AS IS\"",
"accuracy, \"labels\": labels, \"num_seqs\": num_seqs } for k, v in",
"%s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time)) ret =",
"and adv_init_mag > 0 def get_loss_and_logits(text_feats, image_feats): feats = text_feats",
"accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars = { \"loss\": loss,",
"= time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try: np_probs,",
"symmetric KL-divergence (See SMART, Sec 3.1) q_logits: logits p_logits: delta_logits",
"= fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p",
"name='img') else: text_delta, image_delta = None, None def pgd_with_l2(loss, delta):",
"dim=1, keep_dim=True) * shape[-1] # l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask,",
"= delta * mask_slice mag = adv_init_mag / fluid.layers.sqrt(length) delta",
"express or implied. # See the License for the specific",
"kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure +",
"-maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines() if len(ret)",
"except in compliance with the License. # You may obtain",
"max=1.0) delta = fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta = delta",
"[-1, args.max_img_len, 1], # v_mask [-1, args.max_seq_len, 1], # t_mask",
"= -1 ret['data_num'] = all_mats.shape[0] ret['used_time'] = round(time_end - time_begin,",
"delta_norm # projection if adv_max_norm > 0: exceed_mask = (delta_norm",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss =",
"not use this file except in compliance with the License.",
"logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text,",
"emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input =",
"is None else loss + cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy",
"text_delta = pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss =",
"> 0 and adv_init_mag > 0 def get_loss_and_logits(text_feats, image_feats): feats",
"logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text,",
"label=labels, total=num_seqs) graph_vars = { \"loss\": loss, \"probs\": probs_pure, \"accuracy\":",
"writing, software # distributed under the License is distributed on",
"adv_init_mag / fluid.layers.sqrt(length) delta = delta * mag return delta",
"you may not use this file except in compliance with",
"get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image,",
"lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask, v_mask, t_mask, image_embedding,",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"(args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer = open(tmp_file, \"w\") tmp_writer.close() if",
"else loss + cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure,",
"(fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def",
"fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids,",
"fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1],",
"in graph_vars.items(): v.persistable = False return pyreader, graph_vars def evaluate(args,",
"loss + cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels,",
"tmp_writer.close() if gpu_id == 0: while True: ret = os.popen('find",
"\"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines() if len(ret) != dev_count: time.sleep(1)",
"[] test_pyreader.start() time_begin = time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while",
"# src_ids [-1, args.max_seq_len, 1], # pos_ids [-1, args.max_seq_len, 1],",
"for cur_save_file in save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats =",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"= fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta = fluid.layers.slice(delta, axes=[1], starts=[0],",
"image_delta = init_delta(image_embedding, v_mask, image_emb_shape, name='img') else: text_delta, image_delta =",
"factor=2), dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta",
"kl_adv_image_loss loss = cur_loss if loss is None else loss",
"%s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase,",
"%s/%s\" % (args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time)) ret = OrderedDict()",
"ret['loss'] = -1 ret['data_num'] = all_mats.shape[0] ret['used_time'] = round(time_end -",
"text_emb_shape, name='text') image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding,",
"collections import OrderedDict from utils.utils import print_eval_log def kl_divergence_with_logits(q_logits, p_logits):",
"\"\"\" q = fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta =",
"* shape[-1] # l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0,",
"from utils.utils import print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence",
"if is_train: text_emb_shape = [-1, args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids,",
"image_loc, labels) \\ = fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\":",
"loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text =",
"shapes = [[-1, args.max_seq_len, 1], # src_ids [-1, args.max_seq_len, 1],",
"length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1] # l2 norm",
"= loss_pure + loss_text + loss_image + kl_adv_text_loss + kl_adv_image_loss",
"grad delta_grad = fluid.backward.gradients(loss, delta)[0] # l2 norm delta_norm =",
"= fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta = delta + adv_lr",
"loss_pure + loss_text + loss_image + kl_adv_text_loss + kl_adv_image_loss loss",
"args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask, image_emb_shape, name='img') else: text_delta,",
"iter in range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input,",
"1)) np_labels = np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds, np_labels], axis=1)",
"import numpy as np import paddle.fluid as fluid from model.unimo_finetune",
"evaluate(args, exe, test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat =",
"t_mask, text_emb_shape, name='text') image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']] image_delta =",
"= (delta_norm > adv_max_norm).astype('float32') reweights = (adv_max_norm / delta_norm) *",
"pos_ids, sent_ids, input_mask, v_mask, t_mask, image_embedding, image_loc, labels) \\ =",
"emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image = vl_pure.get_pooled_output()",
"for k, v in graph_vars.items(): v.persistable = False return pyreader,",
"> adv_max_norm).astype('float32') reweights = (adv_max_norm / delta_norm) * exceed_mask +",
"time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file,",
"for visual_entailment.\"\"\" from __future__ import absolute_import from __future__ import division",
"image_loc} adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag = \\ args.adv_step, args.adv_lr,",
"\"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer = open(tmp_file, \"w\")",
"UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image =",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats,",
"name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss",
"name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask, v_mask, t_mask, image_embedding, image_loc,",
"sent_ids, \"pos_embedding\": pos_ids} image_input = {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step,",
"h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text,",
"the License is distributed on an \"AS IS\" BASIS, #",
"break all_mat = np.array(all_mat) time_end = time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\"",
"Sec 3.1) q_logits: logits p_logits: delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits)",
"ret['phase'] = eval_phase ret['loss'] = -1 ret['data_num'] = all_mats.shape[0] ret['used_time']",
"os import glob import time import numpy as np import",
"fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats",
"fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta = fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len)",
"None for iter in range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask,",
"adv_lr * delta_grad / delta_norm # projection if adv_max_norm >",
"input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids,",
"+ args.max_seq_len, args.max_img_len + args.max_seq_len], # input_mask [-1, args.max_img_len, 1],",
"labels) \\ = fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids,",
"x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits = fluid.layers.fc(",
"= open(tmp_file, \"w\") tmp_writer.close() if gpu_id == 0: while True:",
"= fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1] # l2 norm delta",
"+ args.max_seq_len], # input_mask [-1, args.max_img_len, 1], # v_mask [-1,",
"axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break all_mat = np.array(all_mat) time_end",
"all_mat = np.array(all_mat) time_end = time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" %",
"delta = delta * mag return delta if is_train: text_emb_shape",
"tmp_writer = open(tmp_file, \"w\") tmp_writer.close() if gpu_id == 0: while",
"fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm,",
"= get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image) if",
"def get_loss_and_logits(text_feats, image_feats): feats = text_feats + image_feats cls_params_name =",
"fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars = { \"loss\": loss, \"probs\": probs_pure,",
"* exceed_mask + (1 - exceed_mask) delta = delta *",
"OrderedDict from utils.utils import print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric",
"vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text,",
"# image_loc [-1, 1] # labels ] dtypes = ['int64',",
"= vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure =",
"= [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count)) for",
"ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1] # l2",
"shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask, v_mask,",
"= eval_phase ret['loss'] = -1 ret['data_num'] = all_mats.shape[0] ret['used_time'] =",
"\"labels\": labels, \"num_seqs\": num_seqs } for k, v in graph_vars.items():",
"adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag = \\ args.adv_step, args.adv_lr, args.norm_type,",
"np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv",
"law or agreed to in writing, software # distributed under",
"try: np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1))",
"bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name",
"shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length =",
"!= dev_count: time.sleep(1) continue else: break all_mats = [] save_files",
"config['hidden_size']] text_delta = init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape = [-1,",
"+ kl_adv_text_loss + kl_adv_image_loss loss = cur_loss if loss is",
"% (args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer = open(tmp_file, \"w\") tmp_writer.close()",
"import print_function import os import glob import time import numpy",
"exceed_mask = (delta_norm > adv_max_norm).astype('float32') reweights = (adv_max_norm / delta_norm)",
"= str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\"",
"test_pyreader.start() time_begin = time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True:",
"= fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)), -1)",
"mag return delta if is_train: text_emb_shape = [-1, args.max_seq_len, config['hidden_size']]",
"time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try: np_probs, np_labels",
"loss, logits, probs def init_delta(input, mask, shape, name='text'): real_seq_len =",
"dtypes = ['int64', 'int64', 'int64', 'float32', 'float32', 'float32', 'float32','float32', 'int64']",
"UNIMOModel from eval import glue_eval from collections import OrderedDict from",
"fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try: np_probs, np_labels =",
"cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars",
"delta_grad = fluid.backward.gradients(loss, delta)[0] # l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad,",
"np import paddle.fluid as fluid from model.unimo_finetune import UNIMOModel from",
"= fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True)) delta_norm =",
"] dtypes = ['int64', 'int64', 'int64', 'float32', 'float32', 'float32', 'float32','float32',",
"args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len, 5], # image_loc [-1,",
"exceed_mask) delta = delta * reweights delta_grad.stop_gradient=True return delta loss",
"h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure",
"may obtain a copy of the License at # #",
"* mask_slice mag = adv_init_mag / fluid.layers.sqrt(length) delta = delta",
"* delta_grad / delta_norm # projection if adv_max_norm > 0:",
"1], # v_mask [-1, args.max_seq_len, 1], # t_mask [-1, args.max_img_len,",
"= None, None def pgd_with_l2(loss, delta): # grad delta_grad =",
"gpu_id=0): \"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start() time_begin = time.time() fetch_list",
"+ loss_text + loss_image + kl_adv_text_loss + kl_adv_image_loss loss =",
"pgd delta = delta + adv_lr * delta_grad / delta_norm",
"= delta * reweights delta_grad.stop_gradient=True return delta loss = None",
"False return pyreader, graph_vars def evaluate(args, exe, test_pyreader, graph_vars, eval_phase,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input",
"OrderedDict() ret['phase'] = eval_phase ret['loss'] = -1 ret['data_num'] = all_mats.shape[0]",
"SMART, Sec 3.1) q_logits: logits p_logits: delta_logits \"\"\" q =",
"fluid.backward.gradients(loss, delta)[0] # l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0],",
"= np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except",
"pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len, 1], # src_ids",
"1], # src_ids [-1, args.max_seq_len, 1], # pos_ids [-1, args.max_seq_len,",
"+ adv_lr * delta_grad / delta_norm # projection if adv_max_norm",
"may not use this file except in compliance with the",
"image_input = {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr, norm_type, adv_max_norm,",
"h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image)",
"p_logits: delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp",
"image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag = \\",
"= init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']]",
"def evaluate(args, exe, test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat",
"(args.eval_dir, eval_phase, dev_count)) for cur_save_file in save_files: mat = np.load(cur_save_file).tolist()",
"cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time))",
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. #",
"# t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len, 5],",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"this file except in compliance with the License. # You",
"image_input=image_input, weight_sharing=args.weight_sharing ) vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config,",
"= fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits",
"fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)), -1)",
"graph_vars.items(): v.persistable = False return pyreader, graph_vars def evaluate(args, exe,",
"import absolute_import from __future__ import division from __future__ import print_function",
"get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta = pgd_with_l2(loss_text, text_delta) image_delta =",
"bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True)",
"h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# grad delta_grad = fluid.backward.gradients(loss, delta)[0] # l2 norm delta_norm",
"# # Licensed under the Apache License, Version 2.0 (the",
"= [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try: np_probs, np_labels = exe.run(fetch_list=fetch_list)",
"= {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input = {\"image_embedding\":",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"return_softmax=True) loss = fluid.layers.mean(x=ce_loss) / adv_step return loss, logits, probs",
"round(time_end - time_begin, 4) metrics = OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy",
"keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta = delta",
") h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text,",
"+ loss_image + kl_adv_text_loss + kl_adv_image_loss loss = cur_loss if",
"args.eval_mertrics in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric)",
"= os.popen('find %s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase,",
"glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count)) for cur_save_file in save_files: mat",
"args.max_seq_len, args.max_img_len + args.max_seq_len], # input_mask [-1, args.max_img_len, 1], #",
"[-1, args.max_seq_len, 1], # pos_ids [-1, args.max_seq_len, 1], # sent_ids",
"0, 0, 0, 0] pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes,",
"loss_image + kl_adv_text_loss + kl_adv_image_loss loss = cur_loss if loss",
"args.max_img_len + args.max_seq_len], # input_mask [-1, args.max_img_len, 1], # v_mask",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"adv_max_norm > 0: exceed_mask = (delta_norm > adv_max_norm).astype('float32') reweights =",
"# v_mask [-1, args.max_seq_len, 1], # t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]],",
"(See SMART, Sec 3.1) q_logits: logits p_logits: delta_logits \"\"\" q",
"\"loc_embedding\": image_loc} adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag = \\ args.adv_step,",
"is_train: text_delta = pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss",
"fluid from model.unimo_finetune import UNIMOModel from eval import glue_eval from",
"= OrderedDict() ret['phase'] = eval_phase ret['loss'] = -1 ret['data_num'] =",
"logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure + loss_text",
"5], # image_loc [-1, 1] # labels ] dtypes =",
"1] # labels ] dtypes = ['int64', 'int64', 'int64', 'float32',",
"loss_text + loss_image + kl_adv_text_loss + kl_adv_image_loss loss = cur_loss",
"= fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars = {",
"np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException:",
"= [\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0],",
"name='text') image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask,",
"ret['data_num'] = all_mats.shape[0] ret['used_time'] = round(time_end - time_begin, 4) metrics",
"print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence (See SMART, Sec",
"= [0, 0, 0, 0, 0, 0, 0, 0, 0]",
"# projection if adv_max_norm > 0: exceed_mask = (delta_norm >",
"Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # #",
"eval_phase, dev_count, args.eval_dir, cur_time)) ret = OrderedDict() ret['phase'] = eval_phase",
"(delta_norm > adv_max_norm).astype('float32') reweights = (adv_max_norm / delta_norm) * exceed_mask",
"h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image =",
"gpu_id == 0: while True: ret = os.popen('find %s -maxdepth",
"from collections import OrderedDict from utils.utils import print_eval_log def kl_divergence_with_logits(q_logits,",
"True: try: np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1,",
"delta = delta * mask_slice mag = adv_init_mag / fluid.layers.sqrt(length)",
"args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step > 0 and",
"pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text)",
"image_loc [-1, 1] # labels ] dtypes = ['int64', 'int64',",
"[] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count)) for cur_save_file",
"time_end = time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count,",
"fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p *",
"[\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)),",
"vat_loss def create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes = [[-1,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image)",
"under the License. \"\"\"Model for visual_entailment.\"\"\" from __future__ import absolute_import",
"= pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure,",
"return delta loss = None for iter in range(adv_step): vl_pure",
"break all_mats = [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase,",
"create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len, 1],",
"delta * mag return delta if is_train: text_emb_shape = [-1,",
"args.max_img_len, 5], # image_loc [-1, 1] # labels ] dtypes",
"= glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count)) for cur_save_file in save_files:",
"= \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer = open(tmp_file,",
"open(tmp_file, \"w\") tmp_writer.close() if gpu_id == 0: while True: ret",
"args.adv_max_norm, args.adv_init_mag assert adv_step > 0 and adv_init_mag > 0",
"or implied. # See the License for the specific language",
"Rights Reserved. # # Licensed under the Apache License, Version",
"fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta = delta + adv_lr *",
") vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing",
"-1 ret['data_num'] = all_mats.shape[0] ret['used_time'] = round(time_end - time_begin, 4)",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"adv_lr, norm_type, adv_max_norm, adv_init_mag = \\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm,",
"weight_sharing=args.weight_sharing ) vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input,",
"time_begin = time.time() fetch_list = [graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try:",
"eval_phase ret['loss'] = -1 ret['data_num'] = all_mats.shape[0] ret['used_time'] = round(time_end",
"model.unimo_finetune import UNIMOModel from eval import glue_eval from collections import",
"\"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start() time_begin = time.time() fetch_list =",
"test_pyreader.reset() break all_mat = np.array(all_mat) time_end = time.time() save_file =",
"eval_phase, dev_count)).readlines() if len(ret) != dev_count: time.sleep(1) continue else: break",
"= fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask,",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"delta loss = None for iter in range(adv_step): vl_pure =",
"np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\"",
"= np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break all_mat",
"utils.utils import print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence (See",
"np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break all_mat = np.array(all_mat)",
"= fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss) / adv_step",
"/ delta_norm) * exceed_mask + (1 - exceed_mask) delta =",
"pgd_with_l2(loss, delta): # grad delta_grad = fluid.backward.gradients(loss, delta)[0] # l2",
"% (args.eval_dir, eval_phase, dev_count)) for cur_save_file in save_files: mat =",
"fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args, config,",
"emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text = UNIMOModel( text_adv_delta=text_delta,",
"adv_max_norm, adv_init_mag = \\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert",
"fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1] # l2 norm delta =",
"name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name =",
") vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing",
"(the \"License\"); # you may not use this file except",
"config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask,",
"# you may not use this file except in compliance",
"save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats) cur_time =",
"feats = fluid.layers.fc( input=feats, size=2048, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1],",
"= kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure + loss_text + loss_image",
"loss, \"probs\": probs_pure, \"accuracy\": accuracy, \"labels\": labels, \"num_seqs\": num_seqs }",
"mask_slice mag = adv_init_mag / fluid.layers.sqrt(length) delta = delta *",
"\"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len, 1], # src_ids [-1, args.max_seq_len,",
"use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask, v_mask, t_mask, image_embedding, image_loc, labels)",
"src_ids [-1, args.max_seq_len, 1], # pos_ids [-1, args.max_seq_len, 1], #",
"capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True) (src_ids, pos_ids, sent_ids, input_mask,",
"vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing )",
"probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image)",
"dev_count)).readlines() if len(ret) != dev_count: time.sleep(1) continue else: break all_mats",
"name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits,",
"in save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats) cur_time",
"get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image) if is_train:",
"= vl_pure.get_pooled_output() h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output()",
"gpu_id) tmp_writer = open(tmp_file, \"w\") tmp_writer.close() if gpu_id == 0:",
"\\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step > 0",
"delta * mask_slice mag = adv_init_mag / fluid.layers.sqrt(length) delta =",
"assert adv_step > 0 and adv_init_mag > 0 def get_loss_and_logits(text_feats,",
"input_mask [-1, args.max_img_len, 1], # v_mask [-1, args.max_seq_len, 1], #",
"# # Unless required by applicable law or agreed to",
"[-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len, 5], # image_loc",
"args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape =",
"\"accuracy\": accuracy, \"labels\": labels, \"num_seqs\": num_seqs } for k, v",
"visual_entailment.\"\"\" from __future__ import absolute_import from __future__ import division from",
"os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time)) ret",
"(args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" %",
"delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta = fluid.layers.slice(delta, axes=[1],",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"0 and adv_init_mag > 0 def get_loss_and_logits(text_feats, image_feats): feats =",
"num_seqs } for k, v in graph_vars.items(): v.persistable = False",
"0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics))",
"0] pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=pyreader_name, use_double_buffer=True)",
"= fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q)",
"dev_count, gpu_id) np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase,",
"Version 2.0 (the \"License\"); # you may not use this",
"image_emb_shape, name='img') else: text_delta, image_delta = None, None def pgd_with_l2(loss,",
"= fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1])",
"delta + adv_lr * delta_grad / delta_norm # projection if",
"[-1, args.max_img_len + args.max_seq_len, args.max_img_len + args.max_seq_len], # input_mask [-1,",
"text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image = UNIMOModel(",
"(adv_max_norm / delta_norm) * exceed_mask + (1 - exceed_mask) delta",
"# labels ] dtypes = ['int64', 'int64', 'int64', 'float32', 'float32',",
"t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len, 5], #",
"= get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta = pgd_with_l2(loss_text, text_delta) image_delta",
"import os import glob import time import numpy as np",
"(src_ids, pos_ids, sent_ids, input_mask, v_mask, t_mask, image_embedding, image_loc, labels) \\",
"= [[-1, args.max_seq_len, 1], # src_ids [-1, args.max_seq_len, 1], #",
"__future__ import absolute_import from __future__ import division from __future__ import",
"feats = text_feats + image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats",
"implied. # See the License for the specific language governing",
"if args.eval_mertrics in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1])",
"h_pure_image) loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image",
"\"w\") tmp_writer.close() if gpu_id == 0: while True: ret =",
"initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels,",
"k, v in graph_vars.items(): v.persistable = False return pyreader, graph_vars",
"labels, \"num_seqs\": num_seqs } for k, v in graph_vars.items(): v.persistable",
"norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta = fluid.layers.slice(delta,",
"\"probs\": probs_pure, \"accuracy\": accuracy, \"labels\": labels, \"num_seqs\": num_seqs } for",
"['int64', 'int64', 'int64', 'float32', 'float32', 'float32', 'float32','float32', 'int64'] lod_levels =",
"np_labels = np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist())",
"by applicable law or agreed to in writing, software #",
"adv_init_mag = \\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag assert adv_step",
"= exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1,",
"= fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True)",
"logits, probs def init_delta(input, mask, shape, name='text'): real_seq_len = fluid.layers.shape(input)[1]",
"args.eval_dir, cur_time)) ret = OrderedDict() ret['phase'] = eval_phase ret['loss'] =",
"shape=fake.shape, min=-1.0, max=1.0) delta = fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta",
"= adv_init_mag / fluid.layers.sqrt(length) delta = delta * mag return",
"paddle.fluid as fluid from model.unimo_finetune import UNIMOModel from eval import",
"= text_feats + image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats =",
"in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret)",
"1], # pos_ids [-1, args.max_seq_len, 1], # sent_ids [-1, args.max_img_len",
"- time_begin, 4) metrics = OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if",
"mag = adv_init_mag / fluid.layers.sqrt(length) delta = delta * mag",
"-1]), factor=2), dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd",
"image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image =",
"all_mats.extend(mat) all_mats = np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\" %",
"def kl_divergence_with_logits(q_logits, p_logits): \"\"\" symmetric KL-divergence (See SMART, Sec 3.1)",
"+ image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc( input=feats,",
"/ fluid.layers.sqrt(length) delta = delta * mag return delta if",
"range(adv_step): vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing )",
"(fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq = fluid.layers.reduce_sum(p * (fluid.layers.log(p) -",
"text_emb_shape = [-1, args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids, t_mask, text_emb_shape,",
"* (fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss",
"reweights = (adv_max_norm / delta_norm) * exceed_mask + (1 -",
"image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text, h_text_image =",
"eval_phase, dev_count, gpu_id) tmp_writer = open(tmp_file, \"w\") tmp_writer.close() if gpu_id",
"gpu_id) np.save(save_file, all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count,",
"[fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) #",
"if is_train: text_delta = pgd_with_l2(loss_text, text_delta) image_delta = pgd_with_l2(loss_image, image_delta)",
"len(ret) != dev_count: time.sleep(1) continue else: break all_mats = []",
"is_train=True): \"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len, 1], # src_ids [-1,",
"initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\")",
"image_embedding, image_loc, labels) \\ = fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids,",
"[graph_vars[\"probs\"].name, graph_vars[\"labels\"].name] while True: try: np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds",
"= np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1, 1)) mat =",
"= ['int64', 'int64', 'int64', 'float32', 'float32', 'float32', 'float32','float32', 'int64'] lod_levels",
"eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start() time_begin =",
"[0, 0, 0, 0, 0, 0, 0, 0, 0] pyreader",
"fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.))) ce_loss,",
"* mag return delta if is_train: text_emb_shape = [-1, args.max_seq_len,",
"save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count)) for cur_save_file in",
"License. \"\"\"Model for visual_entailment.\"\"\" from __future__ import absolute_import from __future__",
"v_mask [-1, args.max_seq_len, 1], # t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], #",
"sent_ids, input_mask, v_mask, t_mask, image_embedding, image_loc, labels) \\ = fluid.layers.read_file(pyreader)",
"initializer=fluid.initializer.Constant(0.))) feats = fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\",",
"\"pos_embedding\": pos_ids} image_input = {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr,",
"image_input=image_input, weight_sharing=args.weight_sharing ) vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config,",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"text_delta) image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss",
"glob import time import numpy as np import paddle.fluid as",
"numpy as np import paddle.fluid as fluid from model.unimo_finetune import",
"fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes",
"cur_save_file in save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats)",
"time_begin, 4) metrics = OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics",
"delta = delta * reweights delta_grad.stop_gradient=True return delta loss =",
"= get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image,",
"fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) *",
"the specific language governing permissions and # limitations under the",
"language governing permissions and # limitations under the License. \"\"\"Model",
"applicable law or agreed to in writing, software # distributed",
"= fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq)",
"PaddlePaddle Authors. All Rights Reserved. # # Licensed under the",
"= vl_image.get_pooled_output() loss_pure, logit_pure, probs_pure = get_loss_and_logits(h_pure_text, h_pure_image) loss_text, logit_text,",
"os.popen('find %s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines()",
"% (args.eval_dir, cur_time)) os.system(\"mv %s/%s.trainers_%d.* %s/%s\" % (args.eval_dir, eval_phase, dev_count,",
"# l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta",
"np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1, 1)) mat = np.concatenate([np_preds,",
"True: ret = os.popen('find %s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' %",
"= np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir",
"1], # sent_ids [-1, args.max_img_len + args.max_seq_len, args.max_img_len + args.max_seq_len],",
"text_delta = init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape = [-1, args.max_img_len,",
"== 0: while True: ret = os.popen('find %s -maxdepth 1",
"in writing, software # distributed under the License is distributed",
"/ delta_norm # projection if adv_max_norm > 0: exceed_mask =",
"1], # t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len,",
"= fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\": src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids}",
"np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels",
"logit_image, probs_image = get_loss_and_logits(h_image_text, h_image_image) if is_train: text_delta = pgd_with_l2(loss_text,",
"t_mask, image_embedding, image_loc, labels) \\ = fluid.layers.read_file(pyreader) emb_ids = {\"word_embedding\":",
"all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics)) return",
"from __future__ import division from __future__ import print_function import os",
"\"num_seqs\": num_seqs } for k, v in graph_vars.items(): v.persistable =",
"fluid.layers.create_tensor(dtype='int64') accuracy = fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars = { \"loss\":",
"pyreader, graph_vars def evaluate(args, exe, test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0):",
"KL-divergence (See SMART, Sec 3.1) q_logits: logits p_logits: delta_logits \"\"\"",
"{ \"loss\": loss, \"probs\": probs_pure, \"accuracy\": accuracy, \"labels\": labels, \"num_seqs\":",
"import glob import time import numpy as np import paddle.fluid",
"cur_loss if loss is None else loss + cur_loss num_seqs",
"} for k, v in graph_vars.items(): v.persistable = False return",
"fluid.core.EOFException: test_pyreader.reset() break all_mat = np.array(all_mat) time_end = time.time() save_file",
"graph_vars[\"labels\"].name] while True: try: np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds =",
"input_mask, v_mask, t_mask, image_embedding, image_loc, labels) \\ = fluid.layers.read_file(pyreader) emb_ids",
"UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image",
"= { \"loss\": loss, \"probs\": probs_pure, \"accuracy\": accuracy, \"labels\": labels,",
"fluid.layers.sqrt(length) delta = delta * mag return delta if is_train:",
"graph_vars def evaluate(args, exe, test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\"",
"= time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count, gpu_id)",
"image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc( input=feats, size=2048,",
"starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice, dim=1, keep_dim=True) * shape[-1] #",
"ret = OrderedDict() ret['phase'] = eval_phase ret['loss'] = -1 ret['data_num']",
"image_emb_shape = [-1, args.max_img_len, config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask, image_emb_shape,",
"= np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir, cur_time))",
"delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2), dim=1, keep_dim=True)) delta_norm",
"if gpu_id == 0: while True: ret = os.popen('find %s",
"= round(time_end - time_begin, 4) metrics = OrderedDict() metrics[\"simple_accuracy\"] =",
"delta if is_train: text_emb_shape = [-1, args.max_seq_len, config['hidden_size']] text_delta =",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\" shapes = [[-1, args.max_seq_len, 1], #",
"q = fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q *",
"= metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported",
"License, Version 2.0 (the \"License\"); # you may not use",
"lod_levels = [0, 0, 0, 0, 0, 0, 0, 0,",
"1]) ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics)) return ret",
"# You may obtain a copy of the License at",
"delta_logits \"\"\" q = fluid.layers.softmax(input=q_logits) p = fluid.layers.softmax(input=p_logits) kl_qp =",
"args.max_seq_len, 1], # t_mask [-1, args.max_img_len, config[\"image_embedding_size\"]], # image_embedding [-1,",
"config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask,",
"= fluid.layers.accuracy(input=probs_pure, label=labels, total=num_seqs) graph_vars = { \"loss\": loss, \"probs\":",
"fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"] logits =",
"- fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args,",
"kl_adv_text_loss + kl_adv_image_loss loss = cur_loss if loss is None",
"text_feats + image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"] feats = fluid.layers.fc(",
"= glue_eval.simple_accuracy if args.eval_mertrics in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0],",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"shape[-1] # l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0)",
"cur_loss = loss_pure + loss_text + loss_image + kl_adv_text_loss +",
"while True: try: np_probs, np_labels = exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs,",
"Authors. All Rights Reserved. # # Licensed under the Apache",
"dev_count: time.sleep(1) continue else: break all_mats = [] save_files =",
"0 def get_loss_and_logits(text_feats, image_feats): feats = text_feats + image_feats cls_params_name",
"kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure + loss_text +",
"image_feats): feats = text_feats + image_feats cls_params_name = [\"cls_out_w_0\", \"cls_out_b_0\"]",
"eval_phase, dev_count)) for cur_save_file in save_files: mat = np.load(cur_save_file).tolist() all_mats.extend(mat)",
"args.max_seq_len, 1], # src_ids [-1, args.max_seq_len, 1], # pos_ids [-1,",
"name='text'): real_seq_len = fluid.layers.shape(input)[1] fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice",
"> 0: exceed_mask = (delta_norm > adv_max_norm).astype('float32') reweights = (adv_max_norm",
"get_loss_and_logits(text_feats, image_feats): feats = text_feats + image_feats cls_params_name = [\"cls_out_w_0\",",
"image_delta = None, None def pgd_with_l2(loss, delta): # grad delta_grad",
"\"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input = {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc}",
"vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing )",
"args.max_img_len + args.max_seq_len, args.max_img_len + args.max_seq_len], # input_mask [-1, args.max_img_len,",
"loss_text, logit_text, probs_text = get_loss_and_logits(h_text_text, h_text_image) loss_image, logit_image, probs_image =",
"= fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr( name=cls_params_name[1], initializer=fluid.initializer.Constant(0.)))",
"while True: ret = os.popen('find %s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"'",
"min=-1.0, max=1.0) delta = fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta =",
"vl_pure = UNIMOModel( emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text",
"l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape, min=-1.0, max=1.0) delta =",
"= UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_image",
"all_mats.shape[0] ret['used_time'] = round(time_end - time_begin, 4) metrics = OrderedDict()",
"dev_count, gpu_id) tmp_writer = open(tmp_file, \"w\") tmp_writer.close() if gpu_id ==",
"metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else:",
"v_mask, image_emb_shape, name='img') else: text_delta, image_delta = None, None def",
"weight_sharing=args.weight_sharing ) vl_image = UNIMOModel( image_adv_delta=image_delta, emb_ids=emb_ids, input_mask=input_mask, config=config, image_input=image_input,",
"0: while True: ret = os.popen('find %s -maxdepth 1 -name",
"the License for the specific language governing permissions and #",
"ret_metric = metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else: raise",
"ends=real_seq_len) delta = delta * mask_slice mag = adv_init_mag /",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"loss = None for iter in range(adv_step): vl_pure = UNIMOModel(",
"dim=1, keep_dim=True)) delta_norm = fluid.layers.clamp(delta_norm, min=float(1e-8)) # pgd delta =",
"either express or implied. # See the License for the",
"adv_step > 0 and adv_init_mag > 0 def get_loss_and_logits(text_feats, image_feats):",
"feats = fluid.layers.dropout( x=feats, dropout_prob=0.1, dropout_implementation=\"upscale_in_train\") cls_params_name = [\"cls_out_w_1\", \"cls_out_b_1\"]",
"'float32', 'float32', 'float32','float32', 'int64'] lod_levels = [0, 0, 0, 0,",
"print_eval_log(ret) else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics)) return ret else: return",
"-1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args, config, pyreader_name=\"train_reader\",",
"config[\"image_embedding_size\"]], # image_embedding [-1, args.max_img_len, 5], # image_loc [-1, 1]",
"delta)[0] # l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]),",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"1)) mat = np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset()",
"all_mats = [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" % (args.eval_dir, eval_phase, dev_count))",
"0, 0, 0, 0, 0, 0, 0] pyreader = fluid.layers.py_reader(",
"dev_count, args.eval_dir, cur_time)) ret = OrderedDict() ret['phase'] = eval_phase ret['loss']",
"%s -maxdepth 1 -name \"%s.trainers_%d.part_*.finish\"' % (args.eval_dir, eval_phase, dev_count)).readlines() if",
"else: raise ValueError('unsupported metric {}'.format(args.eval_mertrics)) return ret else: return None",
"None else loss + cur_loss num_seqs = fluid.layers.create_tensor(dtype='int64') accuracy =",
"dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length = fluid.layers.reduce_sum(mask_slice,",
"return loss, logits, probs def init_delta(input, mask, shape, name='text'): real_seq_len",
"[-1, args.max_img_len, 5], # image_loc [-1, 1] # labels ]",
"'float32', 'float32', 'float32', 'float32','float32', 'int64'] lod_levels = [0, 0, 0,",
"# l2 norm delta_norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.pow(fluid.layers.reshape(delta_grad, \\ [fluid.layers.shape(delta_grad)[0], -1]), factor=2),",
"all_mats = np.array(all_mats) cur_time = str(int(time.time())) os.system(\"mkdir %s/%s\" % (args.eval_dir,",
"if adv_max_norm > 0: exceed_mask = (delta_norm > adv_max_norm).astype('float32') reweights",
"# image_embedding [-1, args.max_img_len, 5], # image_loc [-1, 1] #",
"'int64'] lod_levels = [0, 0, 0, 0, 0, 0, 0,",
"metrics[args.eval_mertrics](all_mats[:, 0], all_mats[:, 1]) ret.update(ret_metric) print_eval_log(ret) else: raise ValueError('unsupported metric",
"= kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure, logit_image) cur_loss = loss_pure",
"metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics in metrics: ret_metric = metrics[args.eval_mertrics](all_mats[:,",
"# limitations under the License. \"\"\"Model for visual_entailment.\"\"\" from __future__",
"logits=logits, label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss) / adv_step return loss,",
"label=labels, return_softmax=True) loss = fluid.layers.mean(x=ce_loss) / adv_step return loss, logits,",
"= fluid.layers.slice(delta, axes=[1], starts=[0], ends=real_seq_len) delta = delta * mask_slice",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"import division from __future__ import print_function import os import glob",
"= False return pyreader, graph_vars def evaluate(args, exe, test_pyreader, graph_vars,",
"return pyreader, graph_vars def evaluate(args, exe, test_pyreader, graph_vars, eval_phase, dev_count=1,",
"delta * reweights delta_grad.stop_gradient=True return delta loss = None for",
"= pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss = kl_divergence_with_logits(logit_pure,",
"[-1, args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids, t_mask, text_emb_shape, name='text') image_emb_shape",
"exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels = np_labels.reshape((-1, 1))",
"= \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase, dev_count, gpu_id) np.save(save_file, all_mat) tmp_file",
"= {\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag",
"+ kl_adv_image_loss loss = cur_loss if loss is None else",
"absolute_import from __future__ import division from __future__ import print_function import",
"test_pyreader, graph_vars, eval_phase, dev_count=1, gpu_id=0): \"\"\"evaluate\"\"\" all_mat = [] test_pyreader.start()",
"delta_grad.stop_gradient=True return delta loss = None for iter in range(adv_step):",
"continue else: break all_mats = [] save_files = glob.glob(\"%s/%s.trainers_%d.part_*.npy\" %",
"input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) vl_text = UNIMOModel( text_adv_delta=text_delta, emb_ids=emb_ids,",
"mat = np.load(cur_save_file).tolist() all_mats.extend(mat) all_mats = np.array(all_mats) cur_time = str(int(time.time()))",
"\"cls_out_b_1\"] logits = fluid.layers.fc( input=feats, size=args.num_labels, param_attr=fluid.ParamAttr( name=cls_params_name[0], initializer=fluid.initializer.TruncatedNormal(scale=0.02)), bias_attr=fluid.ParamAttr(",
"v.persistable = False return pyreader, graph_vars def evaluate(args, exe, test_pyreader,",
"vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args, config, pyreader_name=\"train_reader\", is_train=True):",
"keep_dim=True) * shape[-1] # l2 norm delta = fluid.layers.uniform_random_batch_size_like(mask, shape=fake.shape,",
"\"License\"); # you may not use this file except in",
"0, 0, 0, 0, 0] pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes,",
"# sent_ids [-1, args.max_img_len + args.max_seq_len, args.max_img_len + args.max_seq_len], #",
"= (adv_max_norm / delta_norm) * exceed_mask + (1 - exceed_mask)",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"np_labels = exe.run(fetch_list=fetch_list) np_preds = np.argmax(np_probs, axis=1).reshape((-1, 1)) np_labels =",
"{\"image_embedding\": image_embedding, \"loc_embedding\": image_loc} adv_step, adv_lr, norm_type, adv_max_norm, adv_init_mag =",
"adv_max_norm).astype('float32') reweights = (adv_max_norm / delta_norm) * exceed_mask + (1",
"config['image_embedding_size']] image_delta = init_delta(image_embedding, v_mask, image_emb_shape, name='img') else: text_delta, image_delta",
"h_text_text, h_text_image = vl_text.get_pooled_output() h_image_text, h_image_image = vl_image.get_pooled_output() loss_pure, logit_pure,",
"= fluid.layers.mean(x=kl_qp+kl_pq) return vat_loss def create_model(args, config, pyreader_name=\"train_reader\", is_train=True): \"\"\"create_model\"\"\"",
"# pgd delta = delta + adv_lr * delta_grad /",
"from __future__ import print_function import os import glob import time",
"initializer=fluid.initializer.Constant(0.))) ce_loss, probs = fluid.layers.softmax_with_cross_entropy( logits=logits, label=labels, return_softmax=True) loss =",
"# distributed under the License is distributed on an \"AS",
"fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0], ends=fluid.layers.shape(mask)[1]) length",
"\"\"\"Model for visual_entailment.\"\"\" from __future__ import absolute_import from __future__ import",
"is_train: text_emb_shape = [-1, args.max_seq_len, config['hidden_size']] text_delta = init_delta(src_ids, t_mask,",
"glue_eval from collections import OrderedDict from utils.utils import print_eval_log def",
"fake = fluid.layers.data(name=name+\"_fake\", shape=shape, dtype='float32') mask_slice = fluid.layers.slice(mask, axes=[1], starts=[0],",
"# Unless required by applicable law or agreed to in",
"4) metrics = OrderedDict() metrics[\"simple_accuracy\"] = glue_eval.simple_accuracy if args.eval_mertrics in",
"np.array(all_mat) time_end = time.time() save_file = \"%s/%s.trainers_%d.part_%d.npy\" % (args.eval_dir, eval_phase,",
"(args.eval_dir, eval_phase, dev_count, args.eval_dir, cur_time)) ret = OrderedDict() ret['phase'] =",
"image_embedding [-1, args.max_img_len, 5], # image_loc [-1, 1] # labels",
"all_mat) tmp_file = \"%s/%s.trainers_%d.part_%d.finish\" % (args.eval_dir, eval_phase, dev_count, gpu_id) tmp_writer",
"= all_mats.shape[0] ret['used_time'] = round(time_end - time_begin, 4) metrics =",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"input_mask=input_mask, config=config, image_input=image_input, weight_sharing=args.weight_sharing ) h_pure_text, h_pure_image = vl_pure.get_pooled_output() h_text_text,",
"labels ] dtypes = ['int64', 'int64', 'int64', 'float32', 'float32', 'float32',",
"<gh_stars>1000+ # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.",
"the License. \"\"\"Model for visual_entailment.\"\"\" from __future__ import absolute_import from",
"delta = delta + adv_lr * delta_grad / delta_norm #",
"0, 0, 0] pyreader = fluid.layers.py_reader( capacity=70, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels,",
"You may obtain a copy of the License at #",
"v_mask, t_mask, image_embedding, image_loc, labels) \\ = fluid.layers.read_file(pyreader) emb_ids =",
"np.concatenate([np_preds, np_labels], axis=1) all_mat.extend(mat.tolist()) except fluid.core.EOFException: test_pyreader.reset() break all_mat =",
"import OrderedDict from utils.utils import print_eval_log def kl_divergence_with_logits(q_logits, p_logits): \"\"\"",
"src_ids, \"sent_embedding\": sent_ids, \"pos_embedding\": pos_ids} image_input = {\"image_embedding\": image_embedding, \"loc_embedding\":",
"fluid.layers.reduce_sum(p * (fluid.layers.log(p) - fluid.layers.log(q)), -1) vat_loss = fluid.layers.mean(x=kl_qp+kl_pq) return",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"import time import numpy as np import paddle.fluid as fluid",
"fluid.layers.softmax(input=p_logits) kl_qp = fluid.layers.reduce_sum(q * (fluid.layers.log(q) - fluid.layers.log(p)), -1) kl_pq",
"'int64', 'float32', 'float32', 'float32', 'float32','float32', 'int64'] lod_levels = [0, 0,",
"norm_type, adv_max_norm, adv_init_mag = \\ args.adv_step, args.adv_lr, args.norm_type, args.adv_max_norm, args.adv_init_mag",
"image_delta = pgd_with_l2(loss_image, image_delta) kl_adv_text_loss = kl_divergence_with_logits(logit_pure, logit_text) kl_adv_image_loss =",
"if loss is None else loss + cur_loss num_seqs ="
] |
[
"faust import Record class RssFeed(Record, serializer='json'): feed_source: str title: str",
"= None tags: list = None comments: str = None",
"class Tweet(Record, serializer=\"json\"): tweet_id: str text: str created_at: str metrics:",
"= None comments: str = None content: list = None",
"= None class RedditPost(Record, serializer='json'): id: str title: str author:",
"str place: str = None hashtags: list = None class",
"str title: str author: dict created: str score: int upvote_ratio:",
"= None author: str = None summary: str = None",
"str metrics: dict author: dict trend: str place: str =",
"authors: list = None tags: list = None comments: str",
"upvote_ratio: float reddit: dict domain: str = None url: str",
"source: dict = None class TwitterTrend(Record, serializer='json'): pass class Tweet(Record,",
"str = None author: str = None summary: str =",
"list = None class RedditPost(Record, serializer='json'): id: str title: str",
"author: str = None summary: str = None published_parsed: list",
"float reddit: dict domain: str = None url: str =",
"RedditPost(Record, serializer='json'): id: str title: str author: dict created: str",
"RssFeed(Record, serializer='json'): feed_source: str title: str link: str published: str",
"None url: str = None comments: list = None keywords:",
"reddit: dict domain: str = None url: str = None",
"metrics: dict author: dict trend: str place: str = None",
"class RssFeed(Record, serializer='json'): feed_source: str title: str link: str published:",
"dict author: dict trend: str place: str = None hashtags:",
"class TwitterTrend(Record, serializer='json'): pass class Tweet(Record, serializer=\"json\"): tweet_id: str text:",
"score: int upvote_ratio: float reddit: dict domain: str = None",
"dict = None class TwitterTrend(Record, serializer='json'): pass class Tweet(Record, serializer=\"json\"):",
"None class RedditPost(Record, serializer='json'): id: str title: str author: dict",
"list = None tags: list = None comments: str =",
"str text: str created_at: str metrics: dict author: dict trend:",
"created_at: str metrics: dict author: dict trend: str place: str",
"str = None content: list = None source: dict =",
"<filename>src/records.py from faust import Record class RssFeed(Record, serializer='json'): feed_source: str",
"pass class Tweet(Record, serializer=\"json\"): tweet_id: str text: str created_at: str",
"str = None hashtags: list = None class RedditPost(Record, serializer='json'):",
"str published: str = None author: str = None summary:",
"id: str title: str author: dict created: str score: int",
"serializer=\"json\"): tweet_id: str text: str created_at: str metrics: dict author:",
"tweet_id: str text: str created_at: str metrics: dict author: dict",
"published: str = None author: str = None summary: str",
"serializer='json'): id: str title: str author: dict created: str score:",
"None tags: list = None comments: str = None content:",
"str created_at: str metrics: dict author: dict trend: str place:",
"dict created: str score: int upvote_ratio: float reddit: dict domain:",
"= None url: str = None comments: list = None",
"list = None source: dict = None class TwitterTrend(Record, serializer='json'):",
"dict domain: str = None url: str = None comments:",
"None authors: list = None tags: list = None comments:",
"list = None comments: str = None content: list =",
"title: str link: str published: str = None author: str",
"str = None url: str = None comments: list =",
"= None summary: str = None published_parsed: list = None",
"content: list = None source: dict = None class TwitterTrend(Record,",
"= None source: dict = None class TwitterTrend(Record, serializer='json'): pass",
"class RedditPost(Record, serializer='json'): id: str title: str author: dict created:",
"summary: str = None published_parsed: list = None authors: list",
"None published_parsed: list = None authors: list = None tags:",
"= None content: list = None source: dict = None",
"TwitterTrend(Record, serializer='json'): pass class Tweet(Record, serializer=\"json\"): tweet_id: str text: str",
"str = None published_parsed: list = None authors: list =",
"hashtags: list = None class RedditPost(Record, serializer='json'): id: str title:",
"int upvote_ratio: float reddit: dict domain: str = None url:",
"title: str author: dict created: str score: int upvote_ratio: float",
"import Record class RssFeed(Record, serializer='json'): feed_source: str title: str link:",
"= None comments: list = None keywords: list = None",
"None comments: str = None content: list = None source:",
"str = None comments: list = None keywords: list =",
"trend: str place: str = None hashtags: list = None",
"str title: str link: str published: str = None author:",
"link: str published: str = None author: str = None",
"tags: list = None comments: str = None content: list",
"str author: dict created: str score: int upvote_ratio: float reddit:",
"domain: str = None url: str = None comments: list",
"= None published_parsed: list = None authors: list = None",
"feed_source: str title: str link: str published: str = None",
"= None authors: list = None tags: list = None",
"list = None authors: list = None tags: list =",
"published_parsed: list = None authors: list = None tags: list",
"author: dict trend: str place: str = None hashtags: list",
"None author: str = None summary: str = None published_parsed:",
"str = None summary: str = None published_parsed: list =",
"None content: list = None source: dict = None class",
"url: str = None comments: list = None keywords: list",
"serializer='json'): feed_source: str title: str link: str published: str =",
"comments: str = None content: list = None source: dict",
"None hashtags: list = None class RedditPost(Record, serializer='json'): id: str",
"None summary: str = None published_parsed: list = None authors:",
"= None hashtags: list = None class RedditPost(Record, serializer='json'): id:",
"place: str = None hashtags: list = None class RedditPost(Record,",
"None class TwitterTrend(Record, serializer='json'): pass class Tweet(Record, serializer=\"json\"): tweet_id: str",
"text: str created_at: str metrics: dict author: dict trend: str",
"str score: int upvote_ratio: float reddit: dict domain: str =",
"None source: dict = None class TwitterTrend(Record, serializer='json'): pass class",
"str link: str published: str = None author: str =",
"= None class TwitterTrend(Record, serializer='json'): pass class Tweet(Record, serializer=\"json\"): tweet_id:",
"Record class RssFeed(Record, serializer='json'): feed_source: str title: str link: str",
"serializer='json'): pass class Tweet(Record, serializer=\"json\"): tweet_id: str text: str created_at:",
"author: dict created: str score: int upvote_ratio: float reddit: dict",
"from faust import Record class RssFeed(Record, serializer='json'): feed_source: str title:",
"created: str score: int upvote_ratio: float reddit: dict domain: str",
"Tweet(Record, serializer=\"json\"): tweet_id: str text: str created_at: str metrics: dict",
"dict trend: str place: str = None hashtags: list ="
] |
[
"len(result): result.append([]) result[level].append(node.val) if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right,",
"List[List[int]] \"\"\" if not root: return [] stack = [(root,",
"= None # self.right = None class Solution: def levelOrder(self,",
"[] stack = [(root, 0)] result = [] while stack:",
"x # self.left = None # self.right = None class",
"None # self.right = None class Solution: def levelOrder(self, root):",
"def levelOrder(self, root): \"\"\" :type root: TreeNode :rtype: List[List[int]] \"\"\"",
"level == len(result): result.append([]) result[level].append(node.val) if node.left: stack.append((node.left, level+1)) if",
"Definition for a binary tree node. # class TreeNode: #",
"TreeNode :rtype: List[List[int]] \"\"\" if not root: return [] stack",
"class Solution: def levelOrder(self, root): \"\"\" :type root: TreeNode :rtype:",
"not root: return [] stack = [(root, 0)] result =",
"if not root: return [] stack = [(root, 0)] result",
"# class TreeNode: # def __init__(self, x): # self.val =",
"(node, level) = stack.pop(0) if level == len(result): result.append([]) result[level].append(node.val)",
"result.append([]) result[level].append(node.val) if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1))",
"# self.val = x # self.left = None # self.right",
"[(root, 0)] result = [] while stack: (node, level) =",
"node. # class TreeNode: # def __init__(self, x): # self.val",
"a binary tree node. # class TreeNode: # def __init__(self,",
"self.left = None # self.right = None class Solution: def",
"= None class Solution: def levelOrder(self, root): \"\"\" :type root:",
"self.val = x # self.left = None # self.right =",
"def __init__(self, x): # self.val = x # self.left =",
"TreeNode: # def __init__(self, x): # self.val = x #",
"== len(result): result.append([]) result[level].append(node.val) if node.left: stack.append((node.left, level+1)) if node.right:",
"= stack.pop(0) if level == len(result): result.append([]) result[level].append(node.val) if node.left:",
"Solution: def levelOrder(self, root): \"\"\" :type root: TreeNode :rtype: List[List[int]]",
":type root: TreeNode :rtype: List[List[int]] \"\"\" if not root: return",
"0)] result = [] while stack: (node, level) = stack.pop(0)",
"class TreeNode: # def __init__(self, x): # self.val = x",
"for a binary tree node. # class TreeNode: # def",
"tree node. # class TreeNode: # def __init__(self, x): #",
"return [] stack = [(root, 0)] result = [] while",
"stack.pop(0) if level == len(result): result.append([]) result[level].append(node.val) if node.left: stack.append((node.left,",
"if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) return result",
"= x # self.left = None # self.right = None",
"while stack: (node, level) = stack.pop(0) if level == len(result):",
"# Definition for a binary tree node. # class TreeNode:",
"binary tree node. # class TreeNode: # def __init__(self, x):",
"# def __init__(self, x): # self.val = x # self.left",
"__init__(self, x): # self.val = x # self.left = None",
":rtype: List[List[int]] \"\"\" if not root: return [] stack =",
"stack = [(root, 0)] result = [] while stack: (node,",
"node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) return result #------------------------------------------------------------------------------",
"levelOrder(self, root): \"\"\" :type root: TreeNode :rtype: List[List[int]] \"\"\" if",
"# self.left = None # self.right = None class Solution:",
"if level == len(result): result.append([]) result[level].append(node.val) if node.left: stack.append((node.left, level+1))",
"[] while stack: (node, level) = stack.pop(0) if level ==",
"root: return [] stack = [(root, 0)] result = []",
"# self.right = None class Solution: def levelOrder(self, root): \"\"\"",
"stack: (node, level) = stack.pop(0) if level == len(result): result.append([])",
"None class Solution: def levelOrder(self, root): \"\"\" :type root: TreeNode",
"\"\"\" if not root: return [] stack = [(root, 0)]",
"x): # self.val = x # self.left = None #",
"self.right = None class Solution: def levelOrder(self, root): \"\"\" :type",
"result[level].append(node.val) if node.left: stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) return",
"\"\"\" :type root: TreeNode :rtype: List[List[int]] \"\"\" if not root:",
"= [(root, 0)] result = [] while stack: (node, level)",
"#!/usr/bin/python3 #------------------------------------------------------------------------------ # Definition for a binary tree node. #",
"result = [] while stack: (node, level) = stack.pop(0) if",
"= [] while stack: (node, level) = stack.pop(0) if level",
"level) = stack.pop(0) if level == len(result): result.append([]) result[level].append(node.val) if",
"root): \"\"\" :type root: TreeNode :rtype: List[List[int]] \"\"\" if not",
"#------------------------------------------------------------------------------ # Definition for a binary tree node. # class",
"stack.append((node.left, level+1)) if node.right: stack.append((node.right, level+1)) return result #------------------------------------------------------------------------------ #Testing",
"root: TreeNode :rtype: List[List[int]] \"\"\" if not root: return []"
] |
[
"setuptools import setup, find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\"",
"], dependency_links=[ ], extras_require={ \"tests\": [ \"flake8\", \"autopep8\", ] }",
"setup, find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[",
"from setuptools import setup, find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[",
"install_requires=[ \"fitbit\" ], dependency_links=[ ], extras_require={ \"tests\": [ \"flake8\", \"autopep8\",",
"dependency_links=[ ], extras_require={ \"tests\": [ \"flake8\", \"autopep8\", ] } )",
"setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[ ], extras_require={",
"python3 from setuptools import setup, find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(),",
"packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[ ], extras_require={ \"tests\": [ \"flake8\",",
"name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[ ], extras_require={ \"tests\":",
"version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[ ], extras_require={ \"tests\": [",
"import setup, find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ],",
"\"fitbit\" ], dependency_links=[ ], extras_require={ \"tests\": [ \"flake8\", \"autopep8\", ]",
"#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name=\"\", version=\"0.01\",",
"find_packages setup( name=\"\", version=\"0.01\", packages=find_packages(), install_requires=[ \"fitbit\" ], dependency_links=[ ],",
"<gh_stars>0 #!/usr/bin/env python3 from setuptools import setup, find_packages setup( name=\"\","
] |
[
"import sys sys.path.append(\"../\") from src.app.sigma import SigmaConverter if __name__ ==",
"sys.path.append(\"../\") from src.app.sigma import SigmaConverter if __name__ == \"__main__\": sigmaconverter",
"<filename>src/main.py import sys sys.path.append(\"../\") from src.app.sigma import SigmaConverter if __name__",
"sys sys.path.append(\"../\") from src.app.sigma import SigmaConverter if __name__ == \"__main__\":",
"from src.app.sigma import SigmaConverter if __name__ == \"__main__\": sigmaconverter =",
"import SigmaConverter if __name__ == \"__main__\": sigmaconverter = SigmaConverter() sigmaconverter.read_from_file()",
"src.app.sigma import SigmaConverter if __name__ == \"__main__\": sigmaconverter = SigmaConverter()",
"SigmaConverter if __name__ == \"__main__\": sigmaconverter = SigmaConverter() sigmaconverter.read_from_file() sigmaconverter.write_to_excel()"
] |
[
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('processes', '0131_auto_20201107_2316'),",
"Migration(migrations.Migration): dependencies = [ ('processes', '0131_auto_20201107_2316'), ] operations = [",
"2.2.14 on 2020-11-08 05:40 from django.db import migrations class Migration(migrations.Migration):",
"migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id = scheduling_run_environment_id WHERE run_environment_id IS",
"operations = [ migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id = scheduling_run_environment_id",
"class Migration(migrations.Migration): dependencies = [ ('processes', '0131_auto_20201107_2316'), ] operations =",
"[ migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id = scheduling_run_environment_id WHERE run_environment_id",
"] operations = [ migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id =",
"[ ('processes', '0131_auto_20201107_2316'), ] operations = [ migrations.RunSQL( \"UPDATE processes_workflow",
"= [ migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id = scheduling_run_environment_id WHERE",
"('processes', '0131_auto_20201107_2316'), ] operations = [ migrations.RunSQL( \"UPDATE processes_workflow SET",
"by Django 2.2.14 on 2020-11-08 05:40 from django.db import migrations",
"\"UPDATE processes_workflow SET run_environment_id = scheduling_run_environment_id WHERE run_environment_id IS NULL;\",",
"dependencies = [ ('processes', '0131_auto_20201107_2316'), ] operations = [ migrations.RunSQL(",
"= [ ('processes', '0131_auto_20201107_2316'), ] operations = [ migrations.RunSQL( \"UPDATE",
"Django 2.2.14 on 2020-11-08 05:40 from django.db import migrations class",
"'0131_auto_20201107_2316'), ] operations = [ migrations.RunSQL( \"UPDATE processes_workflow SET run_environment_id",
"# Generated by Django 2.2.14 on 2020-11-08 05:40 from django.db",
"run_environment_id = scheduling_run_environment_id WHERE run_environment_id IS NULL;\", reverse_sql='', ), ]",
"2020-11-08 05:40 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"Generated by Django 2.2.14 on 2020-11-08 05:40 from django.db import",
"SET run_environment_id = scheduling_run_environment_id WHERE run_environment_id IS NULL;\", reverse_sql='', ),",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('processes',",
"processes_workflow SET run_environment_id = scheduling_run_environment_id WHERE run_environment_id IS NULL;\", reverse_sql='',",
"05:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"on 2020-11-08 05:40 from django.db import migrations class Migration(migrations.Migration): dependencies",
"migrations class Migration(migrations.Migration): dependencies = [ ('processes', '0131_auto_20201107_2316'), ] operations",
"import migrations class Migration(migrations.Migration): dependencies = [ ('processes', '0131_auto_20201107_2316'), ]"
] |
[
":] + np.arange(attack.shape[0] - window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None, :]",
"min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ############## windows ################### window_size = 12",
"100 hidden_size = 100 latent_size = 40 # w_size =",
"= 7919 BATCH_SIZE = 200 N_EPOCHS = 100 hidden_size =",
"windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0],",
"y_pred = (y_pred - y_pred.min()) / (y_pred.max() - y_pred.min()) threshold",
"windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0],",
"- y_pred.min()) / (y_pred.max() - y_pred.min()) threshold = ROC(y_test, y_pred)",
"feature_size # z_size = windows_normal.shape[1] * hidden_size # window_size *",
"device = get_default_device() # Read data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\")",
"pd.DataFrame(x_scaled) ############## windows ################### window_size = 12 # np.arange(window_size)[None, :]",
"# 数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x = normal.values x_scaled =",
"float64 for i in list(attack): attack[i] = attack[i].apply(lambda x: str(x).replace(\",\",",
"attack.astype(float) x = attack.values x_scaled = min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled)",
"= windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader",
"# , nrows=1000) labels = [float(label != 'Normal') for label",
"= attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform all columns into float64",
"hidden_size, latent_size, former_step=3) model = to_device(model, device) val_loss, train_loss =",
"results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred - y_pred.min()) / (y_pred.max() - y_pred.min())",
"shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3)",
"test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0)",
"/ (y_pred.max() - y_pred.min()) threshold = ROC(y_test, y_pred) t, th",
"= min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) # Read data # attack",
"testing(model, test_loader) windows_labels = [] for i in range(len(labels) -",
"shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE,",
"former_step=3) model = to_device(model, device) val_loss, train_loss = training(N_EPOCHS, model,",
"latent_size = 40 # w_size = windows_normal.shape[1] * windows_normal.shape[2] #",
"attack.values x_scaled = min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ############## windows ###################",
"# , nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # ,",
":] + np.arange(attack.shape[0] - window_size)[:, None]] ############## training ################### #",
"= 40 # w_size = windows_normal.shape[1] * windows_normal.shape[2] # window_size",
"torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE,",
"= training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\")",
"latent_size, former_step=3) model = to_device(model, device) val_loss, train_loss = training(N_EPOCHS,",
"val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0)",
"batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size,",
"= testing(model, test_loader) windows_labels = [] for i in range(len(labels)",
"# 样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred",
"(0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 #",
"axis=1) # normal.shape # Transform all columns into float64 for",
"window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3) model = to_device(model, device) val_loss,",
"x_scaled = min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) # Read data #",
"= SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3) model = to_device(model,",
"for i in list(attack): attack[i] = attack[i].apply(lambda x: str(x).replace(\",\", \".\"))",
"preprocessing from utils.eval_methods import * device = get_default_device() # Read",
"= windows_normal.shape[1] * hidden_size # window_size * hidden_size windows_normal_train =",
"(1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :] + np.arange(normal.shape[0] - window_size)[:,",
"np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred - y_pred.min()) / (y_pred.max()",
"数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x = normal.values x_scaled = min_max_scaler.fit_transform(x)",
"train_loss = training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()},",
"* hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8",
"torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results = testing(model, test_loader) windows_labels =",
"for window in windows_labels] # 样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(),",
"!= 'Normal') for label in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"],",
"test_loader) windows_labels = [] for i in range(len(labels) - window_size):",
"range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1 y_test =",
"\"Normal/Attack\"], axis=1) # normal.shape # Transform all columns into float64",
"windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))]",
"# np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:, None]",
"<gh_stars>0 from model.sparsely_lstm_vae import * import torch.utils.data as data_utils from",
"Read data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000)",
"label in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform",
"window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1 y_test = [1.0 if",
"torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset(",
"> 0) else 0 for window in windows_labels] # 样本太少的话,误差会很大",
"windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ),",
"# w_size = windows_normal.shape[1] * windows_normal.shape[2] # window_size * feature_size",
"= (y_pred - y_pred.min()) / (y_pred.max() - y_pred.min()) threshold =",
"preprocessing.MinMaxScaler() x = normal.values x_scaled = min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled)",
"import * device = get_default_device() # Read data # normal",
"y_pred.min()) threshold = ROC(y_test, y_pred) t, th = bf_search(y_pred, y_test,",
"np.arange(attack.shape[0] - window_size)[:, None]] ############## training ################### # BATCH_SIZE =",
"for label in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) #",
"normal = normal.astype(float) # 数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x =",
"attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\",",
"window_size)[:, None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] -",
"= pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # , nrows=1000) labels = [float(label",
"plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing ################# checkpoint =",
"\".\")) attack = attack.astype(float) x = attack.values x_scaled = min_max_scaler.transform(x)",
"+ np.arange(attack.shape[0] - window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None, :] +",
"(0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :] + np.arange(normal.shape[0] - window_size)[:, None]",
"attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack = attack.astype(float) x = attack.values",
"+ np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :]",
"model.sparsely_lstm_vae import * import torch.utils.data as data_utils from sklearn import",
"training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############",
"= [float(label != 'Normal') for label in attack[\"Normal/Attack\"].values] attack =",
"'Normal') for label in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1)",
"torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing ################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae'])",
"= 12 # np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] -",
"= get_default_device() # Read data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") #",
"data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal =",
"i in list(attack): attack[i] = attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack",
"window in windows_labels] # 样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()])",
"windows_normal.shape[1] * windows_normal.shape[2] # window_size * feature_size # z_size =",
"attack = attack.astype(float) x = attack.values x_scaled = min_max_scaler.transform(x) attack",
"list(normal): normal[i] = normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal = normal.astype(float)",
"# attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000) attack =",
"* device = get_default_device() # Read data # normal =",
"pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000)",
"0 for window in windows_labels] # 样本太少的话,误差会很大 y_pred = np.concatenate(",
"* windows_normal.shape[2] # window_size * feature_size # z_size = windows_normal.shape[1]",
"windows ################### window_size = 12 # np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列",
", nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape #",
"as data_utils from sklearn import preprocessing from utils.eval_methods import *",
"str(x).replace(\",\", \".\")) attack = attack.astype(float) x = attack.values x_scaled =",
"device) val_loss, train_loss = training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss)",
"num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3) model",
"val_loss, train_loss = training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae':",
"data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000) attack",
"* windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE,",
"nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # , nrows=1000) labels",
"[1.0 if (np.sum(window) > 0) else 0 for window in",
"= 100 latent_size = 40 # w_size = windows_normal.shape[1] *",
"# 窗口中有误差,则为异常,表示为1 y_test = [1.0 if (np.sum(window) > 0) else",
"window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :] + np.arange(normal.shape[0]",
"attack = pd.DataFrame(x_scaled) ############## windows ################### window_size = 12 #",
"windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False,",
"in windows_labels] # 样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred",
"train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0)",
"float64 for i in list(normal): normal[i] = normal[i].apply(lambda x: str(x).replace(\",\",",
"* import torch.utils.data as data_utils from sklearn import preprocessing from",
"y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred - y_pred.min())",
"# Transform all columns into float64 for i in list(normal):",
"= pd.DataFrame(x_scaled) ############## windows ################### window_size = 12 # np.arange(window_size)[None,",
"axis=1) # Transform all columns into float64 for i in",
"nrows=10000) # , nrows=1000) labels = [float(label != 'Normal') for",
"in list(normal): normal[i] = normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal =",
"样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred -",
"# Read data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000)",
"= np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred - y_pred.min()) /",
"import preprocessing from utils.eval_methods import * device = get_default_device() #",
"list(attack): attack[i] = attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack = attack.astype(float)",
"# , nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape",
"= attack.values x_scaled = min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ############## windows",
"torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader =",
"= normal.astype(float) # 数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x = normal.values",
"into float64 for i in list(normal): normal[i] = normal[i].apply(lambda x:",
"(1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]]",
"window_size)[:, None]] ############## training ################### # BATCH_SIZE = 7919 BATCH_SIZE",
"= normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal = normal.astype(float) # 数据预处理",
"attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform all columns into",
"None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :] + np.arange(normal.shape[0] -",
"nrows=1000) labels = [float(label != 'Normal') for label in attack[\"Normal/Attack\"].values]",
"x_scaled = min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ############## windows ################### window_size",
"BATCH_SIZE = 7919 BATCH_SIZE = 200 N_EPOCHS = 100 hidden_size",
"plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing ################# checkpoint = torch.load(\"model.pth\")",
"threshold = ROC(y_test, y_pred) t, th = bf_search(y_pred, y_test, start=0,",
"columns into float64 for i in list(attack): attack[i] = attack[i].apply(lambda",
"hidden_size = 100 latent_size = 40 # w_size = windows_normal.shape[1]",
"40 # w_size = windows_normal.shape[1] * windows_normal.shape[2] # window_size *",
"nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape # Transform",
"i in list(normal): normal[i] = normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal",
"model = to_device(model, device) val_loss, train_loss = training(N_EPOCHS, model, train_loader,",
"= [1.0 if (np.sum(window) > 0) else 0 for window",
"100 latent_size = 40 # w_size = windows_normal.shape[1] * windows_normal.shape[2]",
"= attack.astype(float) x = attack.values x_scaled = min_max_scaler.transform(x) attack =",
"= torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results = testing(model, test_loader) windows_labels",
"sep=\";\", nrows=10000) # , nrows=1000) labels = [float(label != 'Normal')",
"200 N_EPOCHS = 100 hidden_size = 100 latent_size = 40",
"utils.eval_methods import * device = get_default_device() # Read data #",
"attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform all columns into float64 for",
"windows_labels] # 样本太少的话,误差会很大 y_pred = np.concatenate( [torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred =",
"normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape # Transform all",
":] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...)",
"torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model =",
"= pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # , nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\",",
"- window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] -",
"窗口中有误差,则为异常,表示为1 y_test = [1.0 if (np.sum(window) > 0) else 0",
":] + np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None,",
"# normal.shape # Transform all columns into float64 for i",
"from sklearn import preprocessing from utils.eval_methods import * device =",
"pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1)",
"windows_labels = [] for i in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i",
"), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]]))",
"# window_size * feature_size # z_size = windows_normal.shape[1] * hidden_size",
"normal = pd.DataFrame(x_scaled) # Read data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\",",
"all columns into float64 for i in list(attack): attack[i] =",
"pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # , nrows=1000) labels = [float(label !=",
"to_device(model, device) val_loss, train_loss = training(N_EPOCHS, model, train_loader, val_loader) plot_simple_history(val_loss)",
"7919 BATCH_SIZE = 200 N_EPOCHS = 100 hidden_size = 100",
"windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1],",
"normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000)",
"min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) # Read data # attack =",
"[float(label != 'Normal') for label in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\",",
"normal.values x_scaled = min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) # Read data",
"# BATCH_SIZE = 7919 BATCH_SIZE = 200 N_EPOCHS = 100",
"BATCH_SIZE = 200 N_EPOCHS = 100 hidden_size = 100 latent_size",
"################### window_size = 12 # np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 #",
"i in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1",
"testing ################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results =",
"# normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\",",
"model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3) model =",
"if (np.sum(window) > 0) else 0 for window in windows_labels]",
"attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform all columns",
"shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE,",
"* feature_size # z_size = windows_normal.shape[1] * hidden_size # window_size",
"labels = [float(label != 'Normal') for label in attack[\"Normal/Attack\"].values] attack",
"= pd.DataFrame(x_scaled) # Read data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\")",
"in attack[\"Normal/Attack\"].values] attack = attack.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # Transform all",
"windows_normal.shape[2], hidden_size, latent_size, former_step=3) model = to_device(model, device) val_loss, train_loss",
"np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1",
"str(x).replace(\",\", \".\")) normal = normal.astype(float) # 数据预处理 min_max_scaler = preprocessing.MinMaxScaler()",
"= [] for i in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i +",
"windows_normal.shape[1] * hidden_size # window_size * hidden_size windows_normal_train = windows_normal[:int(np.floor(.8",
"= to_device(model, device) val_loss, train_loss = training(N_EPOCHS, model, train_loader, val_loader)",
"+ window_size]))) # 窗口中有误差,则为异常,表示为1 y_test = [1.0 if (np.sum(window) >",
"+ np.arange(attack.shape[0] - window_size)[:, None]] ############## training ################### # BATCH_SIZE",
"sep=\";\") # , nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) #",
"get_default_device() # Read data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # ,",
"[torch.stack(results[:-1]).flatten().detach().cpu().numpy(), results[-1].flatten().detach().cpu().numpy()]) y_pred = (y_pred - y_pred.min()) / (y_pred.max() -",
"# Transform all columns into float64 for i in list(attack):",
"window_size * feature_size # z_size = windows_normal.shape[1] * hidden_size #",
"val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing ################# checkpoint",
"= normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] windows_attack =",
"batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ),",
"attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # , nrows=1000) labels =",
"= windows_normal.shape[1] * windows_normal.shape[2] # window_size * feature_size # z_size",
"normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal = normal.astype(float) # 数据预处理 min_max_scaler",
"z_size = windows_normal.shape[1] * hidden_size # window_size * hidden_size windows_normal_train",
"for i in list(normal): normal[i] = normal[i].apply(lambda x: str(x).replace(\",\", \".\"))",
"for i in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) #",
"from utils.eval_methods import * device = get_default_device() # Read data",
"min_max_scaler = preprocessing.MinMaxScaler() x = normal.values x_scaled = min_max_scaler.fit_transform(x) normal",
"windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2],",
"ROC(y_test, y_pred) t, th = bf_search(y_pred, y_test, start=0, end=1, step_num=1000,",
"nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000) normal =",
"in list(attack): attack[i] = attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack =",
"############## windows ################### window_size = 12 # np.arange(window_size)[None, :] 1*12",
"model.state_dict()}, \"saved_model/model.pth\") ############ testing ################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) #",
"Transform all columns into float64 for i in list(attack): attack[i]",
"\".\")) normal = normal.astype(float) # 数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x",
"N_EPOCHS = 100 hidden_size = 100 latent_size = 40 #",
"window_size * hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val =",
"(y_pred.max() - y_pred.min()) threshold = ROC(y_test, y_pred) t, th =",
"nrows=10000) # , nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) #",
"x: str(x).replace(\",\", \".\")) attack = attack.astype(float) x = attack.values x_scaled",
"windows_normal.shape[2] # window_size * feature_size # z_size = windows_normal.shape[1] *",
"training ################### # BATCH_SIZE = 7919 BATCH_SIZE = 200 N_EPOCHS",
"= pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000) normal = normal.drop([\"Timestamp\", \"Normal/Attack\"],",
"np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :] +",
"hidden_size # window_size * hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))]",
"pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # ,",
"0) else 0 for window in windows_labels] # 样本太少的话,误差会很大 y_pred",
"################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results = testing(model,",
"torch.utils.data as data_utils from sklearn import preprocessing from utils.eval_methods import",
"None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:,",
"############## training ################### # BATCH_SIZE = 7919 BATCH_SIZE = 200",
"12 # np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:,",
"pd.DataFrame(x_scaled) # Read data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") #",
"* windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset(",
"w_size = windows_normal.shape[1] * windows_normal.shape[2] # window_size * feature_size #",
"= normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape # Transform all columns",
"np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :]",
"attack[i] = attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack = attack.astype(float) x",
"windows_attack = attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] ##############",
"############ testing ################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results",
"\"saved_model/model.pth\") ############ testing ################# checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合",
"np.arange(attack.shape[0] - window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0]",
"# np.arange(window_size)[None, :] + np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12 windows_normal",
"# window_size * hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val",
"- window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1 y_test = [1.0",
"num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False,",
"\"Normal/Attack\"], axis=1) # Transform all columns into float64 for i",
"# np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None,",
"Transform all columns into float64 for i in list(normal): normal[i]",
"import * import torch.utils.data as data_utils from sklearn import preprocessing",
"y_pred.min()) / (y_pred.max() - y_pred.min()) threshold = ROC(y_test, y_pred) t,",
"), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size,",
"windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1 y_test = [1.0 if (np.sum(window)",
"# 每一个batch都有一个result。组成result集合 results = testing(model, test_loader) windows_labels = [] for",
"sklearn import preprocessing from utils.eval_methods import * device = get_default_device()",
"into float64 for i in list(attack): attack[i] = attack[i].apply(lambda x:",
"= torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader",
"window_size = 12 # np.arange(window_size)[None, :] 1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0]",
"= torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model",
"= pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) #",
"normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000) normal = normal.drop([\"Timestamp\",",
"checkpoint = torch.load(\"model.pth\") model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results = testing(model, test_loader)",
"window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:,",
"= 200 N_EPOCHS = 100 hidden_size = 100 latent_size =",
"train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing #################",
"torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset(",
"- window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增 # np.arange(window_size)[None, :] +",
", nrows=1000) labels = [float(label != 'Normal') for label in",
"y_pred) t, th = bf_search(y_pred, y_test, start=0, end=1, step_num=1000, display_freq=50)",
"normal.drop([\"Timestamp\", \"Normal/Attack\"], axis=1) # normal.shape # Transform all columns into",
"= normal.values x_scaled = min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) # Read",
"= attack[i].apply(lambda x: str(x).replace(\",\", \".\")) attack = attack.astype(float) x =",
"else 0 for window in windows_labels] # 样本太少的话,误差会很大 y_pred =",
"normal.astype(float) # 数据预处理 min_max_scaler = preprocessing.MinMaxScaler() x = normal.values x_scaled",
"windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1],",
"- y_pred.min()) threshold = ROC(y_test, y_pred) t, th = bf_search(y_pred,",
"np.arange(window_size)[None, :] + np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12 windows_normal =",
"window_size]))) # 窗口中有误差,则为异常,表示为1 y_test = [1.0 if (np.sum(window) > 0)",
"from model.sparsely_lstm_vae import * import torch.utils.data as data_utils from sklearn",
"每一个batch都有一个result。组成result集合 results = testing(model, test_loader) windows_labels = [] for i",
"Read data # normal = pd.read_csv(\"data/SWaT_Dataset_Normal_v1.csv\") # , nrows=1000) normal",
"model, train_loader, val_loader) plot_simple_history(val_loss) plot_train_loss(train_loss) torch.save({'ae': model.state_dict()}, \"saved_model/model.pth\") ############ testing",
"# Read data # attack = pd.read_csv(\"data/SWaT_Dataset_Attack_v0.csv\", sep=\";\") # ,",
"- window_size)[:, None]] ############## training ################### # BATCH_SIZE = 7919",
"), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]]))",
"= preprocessing.MinMaxScaler() x = normal.values x_scaled = min_max_scaler.fit_transform(x) normal =",
"all columns into float64 for i in list(normal): normal[i] =",
"988列,每列递增 # np.arange(window_size)[None, :] + np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*12",
"windows_normal = normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] windows_attack",
"windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_attack).float().view(([windows_attack.shape[0], windows_attack.shape[1],",
"1*12 (0,1,2,3,4,5,6,7,8,9,10,11)一行12列 # np.arange(normal.shape[0] - window_size)[:, None] (1000-12)*1 (0,1,2,3,4,5...) 988列,每列递增",
"SparselyLstmVae(BATCH_SIZE, window_size, windows_normal.shape[2], hidden_size, latent_size, former_step=3) model = to_device(model, device)",
"None]] ############## training ################### # BATCH_SIZE = 7919 BATCH_SIZE =",
"= windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]]))",
"y_test = [1.0 if (np.sum(window) > 0) else 0 for",
"in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i + window_size]))) # 窗口中有误差,则为异常,表示为1 y_test",
"(np.sum(window) > 0) else 0 for window in windows_labels] #",
"columns into float64 for i in list(normal): normal[i] = normal[i].apply(lambda",
"normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] windows_attack = attack.values[np.arange(window_size)[None,",
"# , nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000)",
"normal[i] = normal[i].apply(lambda x: str(x).replace(\",\", \".\")) normal = normal.astype(float) #",
"(y_pred - y_pred.min()) / (y_pred.max() - y_pred.min()) threshold = ROC(y_test,",
"windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 * windows_normal.shape[0])):int(np.floor(windows_normal.shape[0]))] train_loader =",
", nrows=1000) normal = pd.read_csv(\"data/SWaT/SWaT_Dataset_Normal_v1.csv\", nrows=10000) # , nrows=1000) normal",
"= min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ############## windows ################### window_size =",
"windows_attack.shape[1], windows_attack.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) model = SparselyLstmVae(BATCH_SIZE, window_size,",
"attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] ############## training ###################",
"x = normal.values x_scaled = min_max_scaler.fit_transform(x) normal = pd.DataFrame(x_scaled) #",
"None]] windows_attack = attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]]",
"x: str(x).replace(\",\", \".\")) normal = normal.astype(float) # 数据预处理 min_max_scaler =",
"results = testing(model, test_loader) windows_labels = [] for i in",
"x = attack.values x_scaled = min_max_scaler.transform(x) attack = pd.DataFrame(x_scaled) ##############",
"= 100 hidden_size = 100 latent_size = 40 # w_size",
"################### # BATCH_SIZE = 7919 BATCH_SIZE = 200 N_EPOCHS =",
"* hidden_size # window_size * hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 *",
"normal.shape # Transform all columns into float64 for i in",
"= ROC(y_test, y_pred) t, th = bf_search(y_pred, y_test, start=0, end=1,",
"data_utils from sklearn import preprocessing from utils.eval_methods import * device",
"torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_train).float().view(([windows_normal_train.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader =",
"- window_size)[:, None] (1000-12)*12 windows_normal = normal.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0]",
"batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ),",
"# z_size = windows_normal.shape[1] * hidden_size # window_size * hidden_size",
"= torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) test_loader",
"model.load_state_dict(checkpoint['ae']) # 每一个batch都有一个result。组成result集合 results = testing(model, test_loader) windows_labels = []",
"num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0], windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False,",
"import torch.utils.data as data_utils from sklearn import preprocessing from utils.eval_methods",
"[] for i in range(len(labels) - window_size): windows_labels.append(list(np.int_(labels[i:i + window_size])))",
"= attack.values[np.arange(window_size)[None, :] + np.arange(attack.shape[0] - window_size)[:, None]] ############## training",
"windows_normal_train.shape[1], windows_normal_train.shape[2]])) ), batch_size=BATCH_SIZE, shuffle=False, num_workers=0) val_loader = torch.utils.data.DataLoader(data_utils.TensorDataset( torch.from_numpy(windows_normal_val).float().view(([windows_normal_val.shape[0],",
", nrows=1000) attack = pd.read_csv(\"data/SWaT/SWaT_Dataset_Attack_v0.csv\", sep=\";\", nrows=10000) # , nrows=1000)",
"hidden_size windows_normal_train = windows_normal[:int(np.floor(.8 * windows_normal.shape[0]))] windows_normal_val = windows_normal[int(np.floor(.8 *"
] |
[
"absolute_import, unicode_literals from dcs.celeryconf import app import time from django.core.mail",
"'val1': 1, 'val2': 2, 'val3': 3, } print(\"hellp\") from_email =",
"1, 'val2': 2, 'val3': 3, } print(\"hellp\") from_email = '<EMAIL>'",
"app import time from django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3)",
"result = { 'val1': 1, 'val2': 2, 'val3': 3, }",
"import absolute_import, unicode_literals from dcs.celeryconf import app import time from",
"print(\"hellp\") from_email = '<EMAIL>' to_list = ['<EMAIL>',] sendemail = EmailMessage(\"Message",
"from_email = '<EMAIL>' to_list = ['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\",",
"to_list = ['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\", \"Hello test\", str(from_email),",
"time from django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self):",
"dcs.celeryconf import app import time from django.core.mail import EmailMessage @app.task(bind=True,",
"import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self): result = {",
"from __future__ import absolute_import, unicode_literals from dcs.celeryconf import app import",
"@app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self): result = { 'val1': 1,",
"sendemail = EmailMessage(\"Message received!!!\", \"Hello test\", str(from_email), to_list) sendemail.send() return",
"import time from django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def",
"ignore_result=False, max_retries=3) def demo_task1(self): result = { 'val1': 1, 'val2':",
"} print(\"hellp\") from_email = '<EMAIL>' to_list = ['<EMAIL>',] sendemail =",
"from dcs.celeryconf import app import time from django.core.mail import EmailMessage",
"def demo_task1(self): result = { 'val1': 1, 'val2': 2, 'val3':",
"max_retries=3) def demo_task1(self): result = { 'val1': 1, 'val2': 2,",
"2, 'val3': 3, } print(\"hellp\") from_email = '<EMAIL>' to_list =",
"__future__ import absolute_import, unicode_literals from dcs.celeryconf import app import time",
"unicode_literals from dcs.celeryconf import app import time from django.core.mail import",
"= { 'val1': 1, 'val2': 2, 'val3': 3, } print(\"hellp\")",
"demo_task1(self): result = { 'val1': 1, 'val2': 2, 'val3': 3,",
"3, } print(\"hellp\") from_email = '<EMAIL>' to_list = ['<EMAIL>',] sendemail",
"import app import time from django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False,",
"= EmailMessage(\"Message received!!!\", \"Hello test\", str(from_email), to_list) sendemail.send() return result",
"= ['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\", \"Hello test\", str(from_email), to_list)",
"{ 'val1': 1, 'val2': 2, 'val3': 3, } print(\"hellp\") from_email",
"['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\", \"Hello test\", str(from_email), to_list) sendemail.send()",
"django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self): result =",
"from django.core.mail import EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self): result",
"EmailMessage @app.task(bind=True, ignore_result=False, max_retries=3) def demo_task1(self): result = { 'val1':",
"'<EMAIL>' to_list = ['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\", \"Hello test\",",
"'val2': 2, 'val3': 3, } print(\"hellp\") from_email = '<EMAIL>' to_list",
"= '<EMAIL>' to_list = ['<EMAIL>',] sendemail = EmailMessage(\"Message received!!!\", \"Hello",
"'val3': 3, } print(\"hellp\") from_email = '<EMAIL>' to_list = ['<EMAIL>',]"
] |
[
"any Python files in the models/ directory for file in",
"directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not file.startswith(\"_\"):",
"automatically import any Python files in the models/ directory for",
"in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not file.startswith(\"_\"): model_name = file[:",
"python3 import importlib import os # automatically import any Python",
"sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not file.startswith(\"_\"): model_name = file[: file.find(\".py\")]",
"<reponame>Ayansam1152/translate #!/usr/bin/env python3 import importlib import os # automatically import",
"and not file.startswith(\"_\"): model_name = file[: file.find(\".py\")] importlib.import_module(\"pytorch_translate.models.\" + model_name)",
"models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not",
"Python files in the models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))):",
"# automatically import any Python files in the models/ directory",
"importlib import os # automatically import any Python files in",
"if file.endswith(\".py\") and not file.startswith(\"_\"): model_name = file[: file.find(\".py\")] importlib.import_module(\"pytorch_translate.models.\"",
"import os # automatically import any Python files in the",
"os # automatically import any Python files in the models/",
"import importlib import os # automatically import any Python files",
"file.endswith(\".py\") and not file.startswith(\"_\"): model_name = file[: file.find(\".py\")] importlib.import_module(\"pytorch_translate.models.\" +",
"the models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and",
"import any Python files in the models/ directory for file",
"in the models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\")",
"for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not file.startswith(\"_\"): model_name",
"files in the models/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if",
"file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(\".py\") and not file.startswith(\"_\"): model_name =",
"#!/usr/bin/env python3 import importlib import os # automatically import any"
] |
[
"datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API = 'http://ip.yushu.im/get' #",
"= 465 MAIL_USE_SSL = True MAIL_USE_TSL = False MAIL_USERNAME =",
"True MAIL_USE_TSL = False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>'",
"MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER",
"'<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER = '鱼书",
"MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>'",
"True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT",
"'<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>' # 开启数据库查询性能测试",
"0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO = True",
"# -*- coding: utf-8 -*- __author__ = '带土' SQLALCHEMY_DATABASE_URI =",
"True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO = True from datetime import",
"from datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API = 'http://ip.yushu.im/get'",
"SECRET_KEY = <KEY>' # Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT",
"__author__ = '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' #",
"<KEY>' # Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465",
"utf-8 -*- __author__ = '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY =",
"'鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT",
"True from datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API =",
"MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TSL",
"开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS",
"SQLALCHEMY_ECHO = True from datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30)",
"= True MAIL_USE_TSL = False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD =",
"MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TSL = False MAIL_USERNAME",
"MAIL_USE_SSL = True MAIL_USE_TSL = False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD",
"= False SQLALCHEMY_ECHO = True from datetime import timedelta REMEMBER_COOKIE_DURATION",
"-*- __author__ = '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>'",
"# 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT =",
"False SQLALCHEMY_ECHO = True from datetime import timedelta REMEMBER_COOKIE_DURATION =",
"MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES",
"REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API = 'http://ip.yushu.im/get' # PERMANENT_SESSION_LIFETIME = 3600",
"= 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' # Email 配置 MAIL_SERVER =",
"= 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO =",
"= '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>' #",
"SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO = True from",
"性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT = False",
"= '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]' MAIL_SENDER =",
"'带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' # Email 配置",
"SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' # Email 配置 MAIL_SERVER",
"MAIL_SENDER = '鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True #",
"= True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True",
"= True from datetime import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API",
"'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' # Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com'",
"= <KEY>' # Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT =",
"'[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True",
"<<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT =",
"coding: utf-8 -*- __author__ = '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY",
"= '[鱼书]' MAIL_SENDER = '鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES =",
"WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO = True from datetime import timedelta",
"-*- coding: utf-8 -*- __author__ = '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome'",
"= '带土' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:mapei123@127.0.0.1:3306/awesome' SECRET_KEY = <KEY>' # Email",
"'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TSL = False",
"False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX = '[鱼书]'",
"SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS =",
"import timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API = 'http://ip.yushu.im/get' # PERMANENT_SESSION_LIFETIME",
"= False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX =",
"MAIL_USE_TSL = False MAIL_USERNAME = '<EMAIL>' MAIL_PASSWORD = '<PASSWORD>' MAIL_SUBJECT_PREFIX",
"# Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL",
"# 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值 DATABASE_QUERY_TIMEOUT = 0.5",
"DATABASE_QUERY_TIMEOUT = 0.5 SQLALCHEMY_TRACK_MODIFICATIONS = True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO",
"= True WTF_CSRF_CHECK_DEFAULT = False SQLALCHEMY_ECHO = True from datetime",
"配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL = True",
"timedelta REMEMBER_COOKIE_DURATION = timedelta(days=30) PROXY_API = 'http://ip.yushu.im/get' # PERMANENT_SESSION_LIFETIME =",
"Email 配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL =",
"465 MAIL_USE_SSL = True MAIL_USE_TSL = False MAIL_USERNAME = '<EMAIL>'",
"= '鱼书 <<EMAIL>>' # 开启数据库查询性能测试 SQLALCHEMY_RECORD_QUERIES = True # 性能测试的阀值",
"= 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TSL ="
] |
[
"('مخ واعصاب', 'مخ واعصاب'), ('انف واذن', 'انف واذن'), ('امراض دم',",
"max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"'انف واذن'), ('امراض دم', 'امراض دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'),",
"('عظام', 'عظام'), ('جراحه عامه', 'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'),",
"واعصاب', 'مخ واعصاب'), ('انف واذن', 'انف واذن'), ('امراض دم', 'امراض",
"التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='users.Profile')), ],",
"verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')),",
"'مخ واعصاب'), ('انف واذن', 'انف واذن'), ('امراض دم', 'امراض دم'),",
"('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body',",
"models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى",
"verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')),",
"التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)),",
"('جراحه تجميل', 'جراحه تجميل'), ('حميات', 'حميات'), ('نسا وتوليد', 'نسا وتوليد')],",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب', 'مخ واعصاب'),",
"دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه تجميل'), ('حميات',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب",
"'0013_auto_20200731_1810'), ] operations = [ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال',",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254,",
"# Generated by Django 2.2 on 2020-08-01 08:08 from django.db",
"الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"('حميات', 'حميات'), ('نسا وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ),",
"واعصاب'), ('انف واذن', 'انف واذن'), ('امراض دم', 'امراض دم'), ('باطنة',",
"عامه', 'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب', 'مخ",
"تجميل'), ('حميات', 'حميات'), ('نسا وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'),",
"migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام',",
"dependencies = [ ('users', '0013_auto_20200731_1810'), ] operations = [ migrations.AlterField(",
"2.2 on 2020-08-01 08:08 from django.db import migrations, models import",
"اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه', 'جراحه عامه'), ('اطفال',",
"name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه",
"'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه', 'جراحه عامه'),",
"by Django 2.2 on 2020-08-01 08:08 from django.db import migrations,",
"verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'), ] operations =",
"models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)),",
"'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[ ('id',",
"وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[",
"models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='users.Profile')),",
"دم', 'امراض دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه",
"Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'), ] operations = [",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email',",
"('امراض دم', 'امراض دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل',",
"('انف واذن', 'انف واذن'), ('امراض دم', 'امراض دم'), ('باطنة', 'باطنه'),",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'), ]",
"('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه', 'جراحه عامه'), ('اطفال', 'اطفال'),",
"model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'),",
"('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه تجميل'), ('حميات', 'حميات'), ('نسا وتوليد',",
"default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"<reponame>aliharby12/Simple-vezeeta-project<gh_stars>0 # Generated by Django 2.2 on 2020-08-01 08:08 from",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'),",
"اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه', 'جراحه",
"name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"واذن', 'انف واذن'), ('امراض دم', 'امراض دم'), ('باطنة', 'باطنه'), ('اسنان',",
"('users', '0013_auto_20200731_1810'), ] operations = [ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه",
"on 2020-08-01 08:08 from django.db import migrations, models import django.db.models.deletion",
"= [ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس',",
"تجميل', 'جراحه تجميل'), ('حميات', 'حميات'), ('نسا وتوليد', 'نسا وتوليد')], default='باطنه',",
"'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب', 'مخ واعصاب'), ('انف واذن', 'انف",
"'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه', 'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام',",
"صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date',",
"('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments',",
"'اورام'), ('مخ واعصاب', 'مخ واعصاب'), ('انف واذن', 'انف واذن'), ('امراض",
"('جراحه عامه', 'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب',",
"('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')), ('body', models.TextField(verbose_name='محتوى التعليق')), ('comment_date', models.DateTimeField(auto_now_add=True)), ('active',",
"[ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'),",
"), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"] operations = [ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه",
"= [ ('users', '0013_auto_20200731_1810'), ] operations = [ migrations.AlterField( model_name='profile',",
"08:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"'عظام'), ('جراحه عامه', 'جراحه عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ",
"وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True,",
"'امراض دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه تجميل'),",
"('comment_date', models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='users.Profile')), ], ),",
"'جراحه تجميل'), ('حميات', 'حميات'), ('نسا وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255,",
"operations = [ migrations.AlterField( model_name='profile', name='Specialist_doctor', field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'),",
"Django 2.2 on 2020-08-01 08:08 from django.db import migrations, models",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد",
"verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='اسم صاحب التعليق')), ('email', models.EmailField(max_length=254, verbose_name='البريد الالكتروني')),",
"('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه تجميل'), ('حميات', 'حميات'),",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users',",
"('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب', 'مخ واعصاب'), ('انف واذن',",
"('نسا وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel( name='Comment',",
"[ ('users', '0013_auto_20200731_1810'), ] operations = [ migrations.AlterField( model_name='profile', name='Specialist_doctor',",
"عامه'), ('اطفال', 'اطفال'), ('اورام', 'اورام'), ('مخ واعصاب', 'مخ واعصاب'), ('انف",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20200731_1810'), ] operations",
"واذن'), ('امراض دم', 'امراض دم'), ('باطنة', 'باطنه'), ('اسنان', 'اسنان'), ('جراحه",
"'حميات'), ('نسا وتوليد', 'نسا وتوليد')], default='باطنه', max_length=255, verbose_name='التخصص'), ), migrations.CreateModel(",
"migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255,",
"'باطنه'), ('اسنان', 'اسنان'), ('جراحه تجميل', 'جراحه تجميل'), ('حميات', 'حميات'), ('نسا",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"2020-08-01 08:08 from django.db import migrations, models import django.db.models.deletion class",
"Generated by Django 2.2 on 2020-08-01 08:08 from django.db import",
"('اورام', 'اورام'), ('مخ واعصاب', 'مخ واعصاب'), ('انف واذن', 'انف واذن'),",
"'اسنان'), ('جراحه تجميل', 'جراحه تجميل'), ('حميات', 'حميات'), ('نسا وتوليد', 'نسا",
"models.DateTimeField(auto_now_add=True)), ('active', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='users.Profile')), ], ), ]",
"field=models.CharField(choices=[('جراحه اطفال', 'جراحه اططفال'), ('تخسيس', 'تخسيس'), ('عظام', 'عظام'), ('جراحه عامه',"
] |
[
"def get_docker_image() -> Any: images_list = docker_client.images.list(all=True) return { 'images':",
"app import schemas from app.core import docker_client import json from",
"import APIRouter, HTTPException, status, BackgroundTasks from app import schemas from",
"import deepcopy router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() ->",
"Any: volumes_list = docker_client.volumes.list() return { 'volumes': [{'id': volume.short_id, 'name':",
"from app.core import docker_client import json from copy import deepcopy",
"response_model=schemas.DockerImageRespond) def get_docker_image() -> Any: images_list = docker_client.images.list(all=True) return {",
"import Any, List, Callable from fastapi import APIRouter, HTTPException, status,",
"def get_docker_volume() -> Any: volumes_list = docker_client.volumes.list() return { 'volumes':",
"return { 'images': [{'id': image.short_id, 'tags': image.tags} for image in",
"schemas from app.core import docker_client import json from copy import",
"= APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() -> Any: images_list =",
"return { 'volumes': [{'id': volume.short_id, 'name': volume.name} for volume in",
"from typing import Any, List, Callable from fastapi import APIRouter,",
"image.tags} for image in images_list if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond)",
"router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() -> Any: images_list",
"app.core import docker_client import json from copy import deepcopy router",
"json from copy import deepcopy router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond)",
"HTTPException, status, BackgroundTasks from app import schemas from app.core import",
"[{'id': image.short_id, 'tags': image.tags} for image in images_list if image.tags]",
"for image in images_list if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def",
"APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() -> Any: images_list = docker_client.images.list(all=True)",
"image in images_list if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume()",
"Any, List, Callable from fastapi import APIRouter, HTTPException, status, BackgroundTasks",
"images_list = docker_client.images.list(all=True) return { 'images': [{'id': image.short_id, 'tags': image.tags}",
"from copy import deepcopy router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def",
"volumes_list = docker_client.volumes.list() return { 'volumes': [{'id': volume.short_id, 'name': volume.name}",
"if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any: volumes_list",
"-> Any: images_list = docker_client.images.list(all=True) return { 'images': [{'id': image.short_id,",
"import schemas from app.core import docker_client import json from copy",
"= docker_client.images.list(all=True) return { 'images': [{'id': image.short_id, 'tags': image.tags} for",
"@router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any: volumes_list = docker_client.volumes.list() return",
"{ 'images': [{'id': image.short_id, 'tags': image.tags} for image in images_list",
"{ 'volumes': [{'id': volume.short_id, 'name': volume.name} for volume in volumes_list]",
"BackgroundTasks from app import schemas from app.core import docker_client import",
"from fastapi import APIRouter, HTTPException, status, BackgroundTasks from app import",
"from app import schemas from app.core import docker_client import json",
"docker_client import json from copy import deepcopy router = APIRouter()",
"Any: images_list = docker_client.images.list(all=True) return { 'images': [{'id': image.short_id, 'tags':",
"Callable from fastapi import APIRouter, HTTPException, status, BackgroundTasks from app",
"images_list if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any:",
"in images_list if image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() ->",
"response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any: volumes_list = docker_client.volumes.list() return {",
"get_docker_volume() -> Any: volumes_list = docker_client.volumes.list() return { 'volumes': [{'id':",
"fastapi import APIRouter, HTTPException, status, BackgroundTasks from app import schemas",
"image.tags] } @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any: volumes_list =",
"} @router.get(\"/volumes\", response_model=schemas.DockerVolumeRespond) def get_docker_volume() -> Any: volumes_list = docker_client.volumes.list()",
"'volumes': [{'id': volume.short_id, 'name': volume.name} for volume in volumes_list] }",
"@router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() -> Any: images_list = docker_client.images.list(all=True) return",
"deepcopy router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image() -> Any:",
"get_docker_image() -> Any: images_list = docker_client.images.list(all=True) return { 'images': [{'id':",
"APIRouter, HTTPException, status, BackgroundTasks from app import schemas from app.core",
"'images': [{'id': image.short_id, 'tags': image.tags} for image in images_list if",
"= docker_client.volumes.list() return { 'volumes': [{'id': volume.short_id, 'name': volume.name} for",
"docker_client.volumes.list() return { 'volumes': [{'id': volume.short_id, 'name': volume.name} for volume",
"-> Any: volumes_list = docker_client.volumes.list() return { 'volumes': [{'id': volume.short_id,",
"List, Callable from fastapi import APIRouter, HTTPException, status, BackgroundTasks from",
"import docker_client import json from copy import deepcopy router =",
"copy import deepcopy router = APIRouter() @router.get(\"/images\", response_model=schemas.DockerImageRespond) def get_docker_image()",
"typing import Any, List, Callable from fastapi import APIRouter, HTTPException,",
"status, BackgroundTasks from app import schemas from app.core import docker_client",
"docker_client.images.list(all=True) return { 'images': [{'id': image.short_id, 'tags': image.tags} for image",
"image.short_id, 'tags': image.tags} for image in images_list if image.tags] }",
"'tags': image.tags} for image in images_list if image.tags] } @router.get(\"/volumes\",",
"import json from copy import deepcopy router = APIRouter() @router.get(\"/images\","
] |
[
"created layers. tensor_map = {} # Map {reference_tensor: (corresponding_tensor, mask)}",
"= list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys: nodes = model._nodes_by_depth[depth]",
"' + str(x) tensor, _ = tensor_map[x] output_tensors.append(tensor) return Model(input_tensors,",
"isinstance(model, Model): raise ValueError('Expected `model` argument ' 'to be a",
"return Sequential(layers=[input_layer] + layers, name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone any",
"input_tensors is None: # Create placeholders to build the model",
"layer_map[_original] = _cloned else: # Make sure that all input",
"for x, y, mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] =",
"Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly created input",
"_input_tensors.append(x) input_tensors = _input_tensors for x, y in zip(model.inputs, input_tensors):",
"absolute_import from __future__ import division from __future__ import print_function from",
"the existing layers. # Arguments model: Instance of `Sequential`. input_tensors:",
"newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors =",
"new model from inputs and outputs. output_tensors = [] for",
"depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys:",
"upon. If not provided, placeholders will be created. # Returns",
"'mask' not in kwargs: kwargs['mask'] = computed_masks output_tensors = to_list(",
"if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] + layers, name=model.name) else: raise",
"raise ValueError('Expected `model` argument ' 'to be a `Model` instance,",
"output_tensors = [] for x in model.outputs: assert x in",
"argument value. \"\"\" if not isinstance(model, Model): raise ValueError('Expected `model`",
"An instance of `Sequential` reproducing the behavior of the original",
"layer = new_layer else: # Reuse previously cloned layer. layer",
"Reuse previously cloned layer. layer = layer_map[layer] # Don't call",
"= to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for x, y,",
"layer = layer_map[layer] # Don't call InputLayer multiple times. if",
"if x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): #",
".utils.generic_utils import to_list from .engine.input_layer import Input from .engine.input_layer import",
"in model.outputs: assert x in tensor_map, 'Could not compute output",
"from .engine.saving import save_mxnet_model try: import h5py except ImportError: h5py",
"\"\"\"Clone any `Model` instance. Model cloning is similar to calling",
"model). input_tensors: optional list of input tensors to build the",
"layers. # Arguments model: Instance of `Sequential`. input_tensors: optional list",
"name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential` model instance. Model",
"input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original, _cloned in zip(model._input_layers, input_layers):",
"not compute output ' + str(x) tensor, _ = tensor_map[x]",
"K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' + name)",
"[computed_mask] else: computed_tensors = [x[0] for x in computed_data] computed_masks",
"x in enumerate(input_tensors): if not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor",
"tensor, mask # Iterated over every node in the reference",
"argument ' 'to be a `Model` instance, got ', model)",
"+ name) _input_tensors.append(input_tensor) # Cache newly created input layer. original_input_layer",
"computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors,",
"a tensor that comes from a Keras layer ' 'other",
"= [] # List of tuples (input, mask). for x",
"of `input_tensors`.') x = to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer = x._keras_history[0]",
"mask)} if input_tensors is None: # Create placeholders to build",
"= computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks = to_list(",
"Model from .engine.sequential import Sequential from .engine.saving import save_model from",
"for node in nodes: # Recover the corresponding layer. layer",
"isinstance(layer, InputLayer): continue # Gather inputs to call the new",
"name='input_wrapper_for_' + str(x.name)) input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers,",
"`Model` reproducing the behavior of the original model, on top",
".engine.training import Model from .engine.sequential import Sequential from .engine.saving import",
"= new_layer layer = new_layer else: # Reuse previously cloned",
"will be created. # Returns An instance of `Sequential` reproducing",
"model: Instance of `Model` (could be a functional model or",
"from a Keras layer. # If tensor comes from an",
"new_layer layer = new_layer else: # Reuse previously cloned layer.",
"input_tensors): tensor_map[x] = (y, None) # tensor, mask # Iterated",
"`model` argument ' 'to be a `Sequential` model instance, '",
"output_masks): tensor_map[x] = (y, mask) # Check that we did",
"new inputs tensors, using newly instantiated weights. # Raises ValueError:",
"= to_list(input_tensors) _input_tensors = [] for i, x in enumerate(input_tensors):",
"mask # Iterated over every node in the reference model,",
"ValueError('Expected `model` argument ' 'to be a `Model` instance, got",
"if 'mask' not in kwargs: kwargs['mask'] = computed_masks output_tensors =",
"layer ' 'other than an `InputLayer`. ' 'Use the functional",
"'Use the functional API instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_' +",
"(input, mask). for x in reference_input_tensors: if x in tensor_map:",
"functional model or a Sequential model). input_tensors: optional list of",
"new weights) instead of sharing the weights of the existing",
"then call node.inbound_layer on them. computed_data = [] # List",
"calling a model on new inputs, except that it creates",
"the functional API instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name))",
"from .engine.sequential import Sequential from .engine.saving import save_model from .engine.saving",
"it creates new layers (and thus new weights) instead of",
"_ = tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model,",
"model) def clone(layer): return layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for layer",
"# List of tuples (input, mask). for x in reference_input_tensors:",
"None) # tensor, mask # Iterated over every node in",
"model_from_config from .engine.saving import model_from_yaml from .engine.saving import model_from_json from",
"input layer. original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] =",
"tensor_map, # then call node.inbound_layer on them. computed_data = []",
"on them. computed_data = [] # List of tuples (input,",
"not isinstance(model, Model): raise ValueError('Expected `model` argument ' 'to be",
"' 'as part of `input_tensors`.') x = to_list(input_tensors)[0] if K.is_keras_tensor(x):",
"assert x in tensor_map, 'Could not compute output ' +",
"zip(model.inputs, input_tensors): tensor_map[x] = (y, None) # tensor, mask #",
"model_from_json from .engine.saving import save_mxnet_model try: import h5py except ImportError:",
"model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache",
"len(to_list(input_tensors)) != 1: raise ValueError('To clone a `Sequential` model, we",
"str(x.name)) input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers, name=model.name) def",
"comes from an input layer: cache the input layer. input_tensors",
"Returns An instance of `Model` reproducing the behavior of the",
"if isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to be",
"create layer. if layer not in layer_map: # Clone layer.",
"in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) #",
"from . import backend as K from .utils.generic_utils import has_arg",
"top of. input_layers = [] input_tensors = [] for layer",
"def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential` model instance. Model cloning",
"computed_masks = [x[1] for x in computed_data] if has_arg(layer.call, 'mask'):",
"layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map.",
"x._keras_history[0] if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] + layers, name=model.name) else:",
"tensors, using newly instantiated weights. # Raises ValueError: in case",
"layer: cache the input layer. input_tensors = to_list(input_tensors) _input_tensors =",
"from .engine.saving import model_from_config from .engine.saving import model_from_yaml from .engine.saving",
"' 'of a tensor that comes from a Keras layer",
"ValueError('To clone a `Sequential` model, we expect ' ' at",
"from __future__ import absolute_import from __future__ import division from __future__",
"_cloned else: # Make sure that all input tensors come",
"backend as K from .utils.generic_utils import has_arg from .utils.generic_utils import",
"a functional `Model` instance, ' 'got a `Sequential` instance instead:',",
"_clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional `Model` instance. Model cloning is",
"in reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) ==",
"x = to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer = x._keras_history[0] if isinstance(origin_layer,",
"= to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer = x._keras_history[0] if isinstance(origin_layer, InputLayer):",
"dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly created input layer.",
"layer. reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors # If all",
"layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for layer in model.layers] if input_tensors",
"+ layers, name=model.name) else: raise ValueError('Cannot clone a `Sequential` model",
"computed_data[0] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask']",
"layers, name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone any `Model` instance. Model",
"input_tensors = [] for layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape,",
"Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache newly created input",
"or create layer. if layer not in layer_map: # Clone",
"is None: # Create placeholders to build the model on",
"all input tensors come from a Keras layer. # If",
"layer. if node.arguments: kwargs = node.arguments else: kwargs = {}",
"save_mxnet_model try: import h5py except ImportError: h5py = None def",
"# Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer",
"input tensors come from a Keras layer. # If tensor",
"str(x) tensor, _ = tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name)",
"model upon. If not provided, placeholders will be created. #",
"of the existing layers. # Arguments model: Instance of `Model`.",
"in depth_keys: nodes = model._nodes_by_depth[depth] for node in nodes: #",
"= Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly created",
"created. # Returns An instance of `Model` reproducing the behavior",
"Iterated over every node in the reference model, in depth",
"mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y, mask) #",
"times. if isinstance(layer, InputLayer): continue # Gather inputs to call",
"inputs, except that it creates new layers (and thus new",
"`Sequential` instance instead:', model) layer_map = {} # Cache for",
"# Create placeholders to build the model on top of.",
"behavior of the original model, on top of new inputs",
"tensor_map[x] = (y, mask) # Check that we did compute",
"Call layer. if node.arguments: kwargs = node.arguments else: kwargs =",
"if len(computed_data) == len(reference_input_tensors): # Call layer. if node.arguments: kwargs",
"kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks =",
"most one tensor ' 'as part of `input_tensors`.') x =",
"of `Model`. input_tensors: optional list of input tensors to build",
"layer_map[layer] = newly_created_input_layer for _original, _cloned in zip(model._input_layers, input_layers): layer_map[_original]",
"existing layers. # Arguments model: Instance of `Sequential`. input_tensors: optional",
"\"\"\"Clone a functional `Model` instance. Model cloning is similar to",
"# Iterated over every node in the reference model, in",
"of `Model` (could be a functional model or a Sequential",
"to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks = [computed_mask] else:",
"x in computed_data] if has_arg(layer.call, 'mask'): if 'mask' not in",
"computed_masks)) # Update tensor_map. for x, y, mask in zip(reference_output_tensors,",
"Model cloning is similar to calling a model on new",
"except ImportError: h5py = None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a",
"Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors is None: # Create",
"layer_map[layer] # Don't call InputLayer multiple times. if isinstance(layer, InputLayer):",
"= node.output_tensors # If all previous input tensors are available",
"layer in model.layers] if input_tensors is None: return Sequential(layers=layers, name=model.name)",
"layers (and thus new weights) instead of sharing the weights",
"tensor_map = {} # Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors",
"Don't call InputLayer multiple times. if isinstance(layer, InputLayer): continue #",
"in zip(model.inputs, input_tensors): tensor_map[x] = (y, None) # tensor, mask",
"tensor that comes from a Keras layer ' 'other than",
"new layers (and thus new weights) instead of sharing the",
"mask) # Check that we did compute the model outputs,",
"from .utils.generic_utils import to_list from .engine.input_layer import Input from .engine.input_layer",
"origin_layer = x._keras_history[0] if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] + layers,",
"nodes = model._nodes_by_depth[depth] for node in nodes: # Recover the",
"that it creates new layers (and thus new weights) instead",
"instance, ' 'got a `Sequential` instance instead:', model) layer_map =",
"instance instead:', model) layer_map = {} # Cache for created",
".engine.sequential import Sequential from .engine.saving import save_model from .engine.saving import",
"ValueError('Cannot clone a `Sequential` model on top ' 'of a",
"# tensor, mask # Iterated over every node in the",
"reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors):",
"division from __future__ import print_function from . import backend as",
"the existing layers. # Arguments model: Instance of `Model`. input_tensors:",
"ValueError('Expected `model` argument ' 'to be a functional `Model` instance,",
"import model_from_yaml from .engine.saving import model_from_json from .engine.saving import save_mxnet_model",
"from .engine.input_layer import InputLayer from .engine.training import Model from .engine.sequential",
"model_from_yaml from .engine.saving import model_from_json from .engine.saving import save_mxnet_model try:",
"the corresponding layer. layer = node.outbound_layer # Get or create",
"Cache newly created input layer. original_input_layer = x._keras_history[0] newly_created_input_layer =",
"import load_model from .engine.saving import model_from_config from .engine.saving import model_from_yaml",
"len(computed_data) == 1: computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call, 'mask'):",
"[clone(layer) for layer in model.layers] if input_tensors is None: return",
"`Model` instance, ' 'got a `Sequential` instance instead:', model) layer_map",
"API instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer =",
"in case of invalid `model` argument value. \"\"\" if not",
"save_model from .engine.saving import load_model from .engine.saving import model_from_config from",
"newly_created_input_layer for _original, _cloned in zip(model._input_layers, input_layers): layer_map[_original] = _cloned",
"Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential` model",
"# Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors is None: #",
"cache the input layer. input_tensors = to_list(input_tensors) _input_tensors = []",
"depth_keys: nodes = model._nodes_by_depth[depth] for node in nodes: # Recover",
"return layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for layer in model.layers] if",
"the new layer. reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors #",
"new layer. reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors # If",
"expect ' ' at most one tensor ' 'as part",
"on top ' 'of a tensor that comes from a",
"# Cache newly created input layer. original_input_layer = x._keras_history[0] newly_created_input_layer",
"model: Instance of `Sequential`. input_tensors: optional list of input tensors",
"of invalid `model` argument value. \"\"\" if not isinstance(model, Sequential):",
"= computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks = to_list(",
"import Sequential from .engine.saving import save_model from .engine.saving import load_model",
"Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors)) != 1: raise ValueError('To clone",
"'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_masks output_tensors",
"input_tensors=None): \"\"\"Clone a `Sequential` model instance. Model cloning is similar",
"' 'to be a `Sequential` model instance, ' 'but got:',",
"# Update tensor_map. for x, y, mask in zip(reference_output_tensors, output_tensors,",
"+ str(x.name)) input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers, name=model.name)",
"= [x[0] for x in computed_data] computed_masks = [x[1] for",
"in computed_data] computed_masks = [x[1] for x in computed_data] if",
"input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original,",
"the behavior of the original model, on top of new",
"(y, mask) # Check that we did compute the model",
"input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers, name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone",
"None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional `Model` instance. Model",
"case of invalid `model` argument value. \"\"\" if isinstance(model, Sequential):",
"in layer_map: # Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] =",
"kwargs: kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks",
"model, on top of new inputs tensors, using newly instantiated",
"**kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for",
"import has_arg from .utils.generic_utils import to_list from .engine.input_layer import Input",
"def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional `Model` instance. Model cloning",
".utils.generic_utils import has_arg from .utils.generic_utils import to_list from .engine.input_layer import",
"created input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for",
"+ str(x) tensor, _ = tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors,",
"model, in depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth",
"return Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential`",
"node.outbound_layer # Get or create layer. if layer not in",
"output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask))",
"in case of invalid `model` argument value. \"\"\" if isinstance(model,",
"= {} # Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors is",
"in enumerate(input_tensors): if not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor =",
".engine.input_layer import Input from .engine.input_layer import InputLayer from .engine.training import",
"= model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) #",
"= to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors",
"the model outputs, # then instantiate a new model from",
"that all input tensors come from a Keras layer. #",
"instance, ' 'but got:', model) def clone(layer): return layer.__class__.from_config(layer.get_config()) layers",
"layers. # Arguments model: Instance of `Model`. input_tensors: optional list",
"from inputs and outputs. output_tensors = [] for x in",
"= None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional `Model` instance.",
"kwargs = node.arguments else: kwargs = {} if len(computed_data) ==",
"Make sure that all input tensors come from a Keras",
"clone(layer): return layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for layer in model.layers]",
"in tensor_map, 'Could not compute output ' + str(x) tensor,",
"cloned layer. layer = layer_map[layer] # Don't call InputLayer multiple",
"a Keras layer ' 'other than an `InputLayer`. ' 'Use",
"on top of. input_layers = [] input_tensors = [] for",
"If tensor comes from an input layer: cache the input",
"has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_masks",
"' 'but got:', model) def clone(layer): return layer.__class__.from_config(layer.get_config()) layers =",
"in the reference model, in depth order. depth_keys = list(model._nodes_by_depth.keys())",
"y, mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y, mask)",
"functional API instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer",
"name=layer.name) input_tensors.append(input_tensor) # Cache newly created input layer. newly_created_input_layer =",
"of `Sequential` reproducing the behavior of the original model, on",
"model on top ' 'of a tensor that comes from",
"argument value. \"\"\" if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors) else:",
"the existing layers. # Arguments model: Instance of `Model` (could",
"model.layers] if input_tensors is None: return Sequential(layers=layers, name=model.name) else: if",
"return Sequential(layers=[origin_layer] + layers, name=model.name) else: raise ValueError('Cannot clone a",
"{reference_tensor: (corresponding_tensor, mask)} if input_tensors is None: # Create placeholders",
"= new_layer else: # Reuse previously cloned layer. layer =",
"model on top of. input_layers = [] input_tensors = []",
"= {} # Cache for created layers. tensor_map = {}",
"computed_tensors = [computed_tensor] computed_masks = [computed_mask] else: computed_tensors = [x[0]",
"= Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache newly created",
"`Sequential` model instance, ' 'but got:', model) def clone(layer): return",
"of tuples (input, mask). for x in reference_input_tensors: if x",
"`model` argument value. \"\"\" if not isinstance(model, Model): raise ValueError('Expected",
"InputLayer from .engine.training import Model from .engine.sequential import Sequential from",
"tensors come from a Keras layer. # If tensor comes",
"computed_masks = [computed_mask] else: computed_tensors = [x[0] for x in",
"Sequential model). input_tensors: optional list of input tensors to build",
"layers = [clone(layer) for layer in model.layers] if input_tensors is",
"_input_tensors = [] for i, x in enumerate(input_tensors): if not",
"call InputLayer multiple times. if isinstance(layer, InputLayer): continue # Gather",
"for layer in model.layers] if input_tensors is None: return Sequential(layers=layers,",
"{} # Cache for created layers. tensor_map = {} #",
"`InputLayer`. ' 'Use the functional API instead.') input_tensor = Input(tensor=x,",
"top ' 'of a tensor that comes from a Keras",
"= x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x)",
"else: computed_tensors = [x[0] for x in computed_data] computed_masks =",
"'Could not compute output ' + str(x) tensor, _ =",
"argument ' 'to be a `Sequential` model instance, ' 'but",
"# If all previous input tensors are available in tensor_map,",
"layer. original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer",
"Recover the corresponding layer. layer = node.outbound_layer # Get or",
"be a functional `Model` instance, ' 'got a `Sequential` instance",
"reference_output_tensors = node.output_tensors # If all previous input tensors are",
"# then instantiate a new model from inputs and outputs.",
"tensor ' 'as part of `input_tensors`.') x = to_list(input_tensors)[0] if",
"compute output ' + str(x) tensor, _ = tensor_map[x] output_tensors.append(tensor)",
"tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone",
"if K.is_keras_tensor(x): origin_layer = x._keras_history[0] if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer]",
"argument ' 'to be a functional `Model` instance, ' 'got",
"them. computed_data = [] # List of tuples (input, mask).",
"' 'other than an `InputLayer`. ' 'Use the functional API",
"\"\"\"Model-related utilities. \"\"\" from __future__ import absolute_import from __future__ import",
"import save_mxnet_model try: import h5py except ImportError: h5py = None",
"', model) if isinstance(model, Sequential): raise ValueError('Expected `model` argument '",
"'but got:', model) def clone(layer): return layer.__class__.from_config(layer.get_config()) layers = [clone(layer)",
"_clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential` model instance. Model cloning is",
"else: _input_tensors.append(x) input_tensors = _input_tensors for x, y in zip(model.inputs,",
"depth_keys.sort(reverse=True) for depth in depth_keys: nodes = model._nodes_by_depth[depth] for node",
"input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors for",
"computed_tensors = [x[0] for x in computed_data] computed_masks = [x[1]",
"None: # Create placeholders to build the model on top",
"got ', model) if isinstance(model, Sequential): raise ValueError('Expected `model` argument",
"input tensors are available in tensor_map, # then call node.inbound_layer",
"build the model on top of. input_layers = [] input_tensors",
"else: if len(to_list(input_tensors)) != 1: raise ValueError('To clone a `Sequential`",
"placeholders to build the model on top of. input_layers =",
"from __future__ import print_function from . import backend as K",
"Arguments model: Instance of `Sequential`. input_tensors: optional list of input",
"`Sequential`. input_tensors: optional list of input tensors to build the",
"h5py except ImportError: h5py = None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone",
"layers. # Arguments model: Instance of `Model` (could be a",
"in zip(model._input_layers, input_layers): layer_map[_original] = _cloned else: # Make sure",
"`model` argument ' 'to be a `Model` instance, got ',",
"# then call node.inbound_layer on them. computed_data = [] #",
"if not isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to",
"layer. if layer not in layer_map: # Clone layer. new_layer",
"# Check that we did compute the model outputs, #",
"\"\"\" from __future__ import absolute_import from __future__ import division from",
"import Input from .engine.input_layer import InputLayer from .engine.training import Model",
"optional list of input tensors to build the model upon.",
"[x[1] for x in computed_data] if has_arg(layer.call, 'mask'): if 'mask'",
"except that it creates new layers (and thus new weights)",
"on top of new inputs tensors, using newly instantiated weights.",
"len(reference_input_tensors): # Call layer. if node.arguments: kwargs = node.arguments else:",
"' 'to be a functional `Model` instance, ' 'got a",
"i, x in enumerate(input_tensors): if not K.is_keras_tensor(x): name = model._input_layers[i].name",
"else: # Make sure that all input tensors come from",
"x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors",
"(could be a functional model or a Sequential model). input_tensors:",
"new_layer else: # Reuse previously cloned layer. layer = layer_map[layer]",
"ValueError('Expected `model` argument ' 'to be a `Sequential` model instance,",
"the model upon. If not provided, placeholders will be created.",
"to call the new layer. reference_input_tensors = node.input_tensors reference_output_tensors =",
"An instance of `Model` reproducing the behavior of the original",
"if len(to_list(input_tensors)) != 1: raise ValueError('To clone a `Sequential` model,",
"else: # Reuse previously cloned layer. layer = layer_map[layer] #",
"'to be a functional `Model` instance, ' 'got a `Sequential`",
"layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor]",
"= (y, None) # tensor, mask # Iterated over every",
"call the new layer. reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors",
"Update tensor_map. for x, y, mask in zip(reference_output_tensors, output_tensors, output_masks):",
"layer_map[layer] = new_layer layer = new_layer else: # Reuse previously",
"output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a",
"instead:', model) layer_map = {} # Cache for created layers.",
"`Model` instance. Model cloning is similar to calling a model",
"weights. # Raises ValueError: in case of invalid `model` argument",
"= tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None):",
"= [x[1] for x in computed_data] if has_arg(layer.call, 'mask'): if",
"we did compute the model outputs, # then instantiate a",
"# Gather inputs to call the new layer. reference_input_tensors =",
"the weights of the existing layers. # Arguments model: Instance",
"`Model`. input_tensors: optional list of input tensors to build the",
"computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor,",
"is None: return Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors)) != 1:",
"import backend as K from .utils.generic_utils import has_arg from .utils.generic_utils",
"for x, y in zip(model.inputs, input_tensors): tensor_map[x] = (y, None)",
"functional `Model` instance. Model cloning is similar to calling a",
"model) if isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to",
"# Raises ValueError: in case of invalid `model` argument value.",
"in depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in",
"output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks))",
"instead of sharing the weights of the existing layers. #",
"to_list from .engine.input_layer import Input from .engine.input_layer import InputLayer from",
"input_tensors.append(input_tensor) # Cache newly created input layer. newly_created_input_layer = input_tensor._keras_history[0]",
"Get or create layer. if layer not in layer_map: #",
"computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call, 'mask'): if 'mask' not",
"Returns An instance of `Sequential` reproducing the behavior of the",
"not isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to be",
"input_tensors: optional list of input tensors to build the model",
"= {} if len(computed_data) == 1: computed_tensor, computed_mask = computed_data[0]",
"for x in reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x]) if",
"import absolute_import from __future__ import division from __future__ import print_function",
"that we did compute the model outputs, # then instantiate",
"InputLayer): continue # Gather inputs to call the new layer.",
"import print_function from . import backend as K from .utils.generic_utils",
"instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer = input_tensor._keras_history[0]",
"Keras layer. # If tensor comes from an input layer:",
"tensor_map[x] = (y, None) # tensor, mask # Iterated over",
"case of invalid `model` argument value. \"\"\" if not isinstance(model,",
"= newly_created_input_layer for _original, _cloned in zip(model._input_layers, input_layers): layer_map[_original] =",
"top of new inputs tensors, using newly instantiated weights. #",
"layer. layer = node.outbound_layer # Get or create layer. if",
"continue # Gather inputs to call the new layer. reference_input_tensors",
"inputs and outputs. output_tensors = [] for x in model.outputs:",
"the input layer. input_tensors = to_list(input_tensors) _input_tensors = [] for",
"tensor_map. for x, y, mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x]",
"model, we expect ' ' at most one tensor '",
".engine.saving import load_model from .engine.saving import model_from_config from .engine.saving import",
"new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer = new_layer else:",
"of invalid `model` argument value. \"\"\" if not isinstance(model, Model):",
"layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks = [computed_mask] else: computed_tensors",
".engine.input_layer import InputLayer from .engine.training import Model from .engine.sequential import",
"layer. input_tensors = to_list(input_tensors) _input_tensors = [] for i, x",
"be a `Model` instance, got ', model) if isinstance(model, Sequential):",
"= [] input_tensors = [] for layer in model._input_layers: input_tensor",
"as K from .utils.generic_utils import has_arg from .utils.generic_utils import to_list",
"previously cloned layer. layer = layer_map[layer] # Don't call InputLayer",
"a `Sequential` model instance, ' 'but got:', model) def clone(layer):",
"def clone(layer): return layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for layer in",
"' 'Use the functional API instead.') input_tensor = Input(tensor=x, name='input_wrapper_for_'",
"`model` argument ' 'to be a functional `Model` instance, '",
"[] for x in model.outputs: assert x in tensor_map, 'Could",
"`Model` (could be a functional model or a Sequential model).",
"to build the model on top of. input_layers = []",
"`Sequential` model instance. Model cloning is similar to calling a",
"`model` argument value. \"\"\" if not isinstance(model, Sequential): raise ValueError('Expected",
"Raises ValueError: in case of invalid `model` argument value. \"\"\"",
"{} if len(computed_data) == 1: computed_tensor, computed_mask = computed_data[0] if",
"a model on new inputs, except that it creates new",
"functional `Model` instance, ' 'got a `Sequential` instance instead:', model)",
"Gather inputs to call the new layer. reference_input_tensors = node.input_tensors",
"`input_tensors`.') x = to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer = x._keras_history[0] if",
"to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update",
"on new inputs, except that it creates new layers (and",
"of `Model` reproducing the behavior of the original model, on",
"compute the model outputs, # then instantiate a new model",
"placeholders will be created. # Returns An instance of `Model`",
"import InputLayer from .engine.training import Model from .engine.sequential import Sequential",
"newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors for x, y in",
"in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y, mask) # Check",
"output_tensors, name=model.name) def _clone_sequential_model(model, input_tensors=None): \"\"\"Clone a `Sequential` model instance.",
"Sequential): raise ValueError('Expected `model` argument ' 'to be a `Sequential`",
"outputs. output_tensors = [] for x in model.outputs: assert x",
"if not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_'",
"model instance. Model cloning is similar to calling a model",
"def clone_model(model, input_tensors=None): \"\"\"Clone any `Model` instance. Model cloning is",
"ImportError: h5py = None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional",
"[] for layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse,",
"instance, got ', model) if isinstance(model, Sequential): raise ValueError('Expected `model`",
"from .engine.input_layer import Input from .engine.input_layer import InputLayer from .engine.training",
"name = model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor)",
"value. \"\"\" if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors) else: return",
"{} # Map {reference_tensor: (corresponding_tensor, mask)} if input_tensors is None:",
"__future__ import division from __future__ import print_function from . import",
"in nodes: # Recover the corresponding layer. layer = node.outbound_layer",
"previous input tensors are available in tensor_map, # then call",
"comes from a Keras layer ' 'other than an `InputLayer`.",
"be a `Sequential` model instance, ' 'but got:', model) def",
"else: raise ValueError('Cannot clone a `Sequential` model on top '",
"if not isinstance(model, Model): raise ValueError('Expected `model` argument ' 'to",
"then instantiate a new model from inputs and outputs. output_tensors",
"x in tensor_map, 'Could not compute output ' + str(x)",
"of the original model, on top of new inputs tensors,",
"a functional `Model` instance. Model cloning is similar to calling",
"for depth in depth_keys: nodes = model._nodes_by_depth[depth] for node in",
"Cache for created layers. tensor_map = {} # Map {reference_tensor:",
"x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): # Call",
"__future__ import print_function from . import backend as K from",
"= input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors",
"in model.layers] if input_tensors is None: return Sequential(layers=layers, name=model.name) else:",
"invalid `model` argument value. \"\"\" if isinstance(model, Sequential): return _clone_sequential_model(model,",
"load_model from .engine.saving import model_from_config from .engine.saving import model_from_yaml from",
"if len(computed_data) == 1: computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call,",
"be a functional model or a Sequential model). input_tensors: optional",
"# Don't call InputLayer multiple times. if isinstance(layer, InputLayer): continue",
"1: computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call, 'mask'): if 'mask'",
"in kwargs: kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs))",
"of invalid `model` argument value. \"\"\" if isinstance(model, Sequential): return",
"layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer = new_layer",
"import model_from_config from .engine.saving import model_from_yaml from .engine.saving import model_from_json",
"x, y, mask in zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y,",
"node.input_tensors reference_output_tensors = node.output_tensors # If all previous input tensors",
"value. \"\"\" if not isinstance(model, Sequential): raise ValueError('Expected `model` argument",
"reproducing the behavior of the original model, on top of",
"Sequential): raise ValueError('Expected `model` argument ' 'to be a functional",
"tensor, _ = tensor_map[x] output_tensors.append(tensor) return Model(input_tensors, output_tensors, name=model.name) def",
"' 'to be a `Model` instance, got ', model) if",
"model instance, ' 'but got:', model) def clone(layer): return layer.__class__.from_config(layer.get_config())",
"corresponding layer. layer = node.outbound_layer # Get or create layer.",
"weights of the existing layers. # Arguments model: Instance of",
"instantiated weights. # Raises ValueError: in case of invalid `model`",
"instance of `Sequential` reproducing the behavior of the original model,",
"None: return Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors)) != 1: raise",
"Input from .engine.input_layer import InputLayer from .engine.training import Model from",
"list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys: nodes = model._nodes_by_depth[depth] for",
"input layer. input_tensors = to_list(input_tensors) _input_tensors = [] for i,",
"computed_data] computed_masks = [x[1] for x in computed_data] if has_arg(layer.call,",
"computed_data] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask']",
"model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache",
"be created. # Returns An instance of `Model` reproducing the",
"created input layer. original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer]",
"layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer = new_layer else: # Reuse",
"' at most one tensor ' 'as part of `input_tensors`.')",
"similar to calling a model on new inputs, except that",
"node.output_tensors # If all previous input tensors are available in",
"placeholders will be created. # Returns An instance of `Sequential`",
"InputLayer): return Sequential(layers=[origin_layer] + layers, name=model.name) else: raise ValueError('Cannot clone",
"= node.outbound_layer # Get or create layer. if layer not",
"enumerate(input_tensors): if not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor = Input(tensor=x,",
"newly created input layer. original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0]",
"else: kwargs = {} if len(computed_data) == 1: computed_tensor, computed_mask",
"!= 1: raise ValueError('To clone a `Sequential` model, we expect",
"layer not in layer_map: # Clone layer. new_layer = layer.__class__.from_config(layer.get_config())",
"+ layers, name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone any `Model` instance.",
"Model): raise ValueError('Expected `model` argument ' 'to be a `Model`",
"if node.arguments: kwargs = node.arguments else: kwargs = {} if",
"layer_map: # Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer",
"original_input_layer = x._keras_history[0] newly_created_input_layer = input_tensor._keras_history[0] layer_map[original_input_layer] = newly_created_input_layer else:",
"= _input_tensors for x, y in zip(model.inputs, input_tensors): tensor_map[x] =",
"inputs to call the new layer. reference_input_tensors = node.input_tensors reference_output_tensors",
"input_tensors = _input_tensors for x, y in zip(model.inputs, input_tensors): tensor_map[x]",
"zip(reference_output_tensors, output_tensors, output_masks): tensor_map[x] = (y, mask) # Check that",
"input_tensors=None): \"\"\"Clone any `Model` instance. Model cloning is similar to",
"did compute the model outputs, # then instantiate a new",
"model on new inputs, except that it creates new layers",
"x in model.outputs: assert x in tensor_map, 'Could not compute",
"# Arguments model: Instance of `Model` (could be a functional",
"a `Sequential` model, we expect ' ' at most one",
"# Returns An instance of `Model` reproducing the behavior of",
"node.arguments: kwargs = node.arguments else: kwargs = {} if len(computed_data)",
"input tensors to build the model upon. If not provided,",
"[computed_tensor] computed_masks = [computed_mask] else: computed_tensors = [x[0] for x",
"output ' + str(x) tensor, _ = tensor_map[x] output_tensors.append(tensor) return",
"inputs tensors, using newly instantiated weights. # Raises ValueError: in",
"depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys: nodes =",
"If not provided, placeholders will be created. # Returns An",
"the original model, on top of new inputs tensors, using",
"layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor)",
"in kwargs: kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs))",
"= layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer = new_layer else: #",
"kwargs = {} if len(computed_data) == 1: computed_tensor, computed_mask =",
"tuples (input, mask). for x in reference_input_tensors: if x in",
"from .utils.generic_utils import has_arg from .utils.generic_utils import to_list from .engine.input_layer",
"layer_map[original_input_layer] = newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors for x,",
"if input_tensors is None: # Create placeholders to build the",
"build the model upon. If not provided, placeholders will be",
"mask). for x in reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x])",
"new inputs, except that it creates new layers (and thus",
"Instance of `Model` (could be a functional model or a",
"invalid `model` argument value. \"\"\" if not isinstance(model, Model): raise",
"a `Sequential` instance instead:', model) layer_map = {} # Cache",
"node in nodes: # Recover the corresponding layer. layer =",
"of input tensors to build the model upon. If not",
"# Returns An instance of `Sequential` reproducing the behavior of",
"from .engine.saving import model_from_yaml from .engine.saving import model_from_json from .engine.saving",
"tensors are available in tensor_map, # then call node.inbound_layer on",
"Create placeholders to build the model on top of. input_layers",
"to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer = x._keras_history[0] if isinstance(origin_layer, InputLayer): return",
"\"\"\" if not isinstance(model, Model): raise ValueError('Expected `model` argument '",
"= [] for x in model.outputs: assert x in tensor_map,",
"created. # Returns An instance of `Sequential` reproducing the behavior",
"instantiate a new model from inputs and outputs. output_tensors =",
"if layer not in layer_map: # Clone layer. new_layer =",
"to calling a model on new inputs, except that it",
"(and thus new weights) instead of sharing the weights of",
"model or a Sequential model). input_tensors: optional list of input",
"__future__ import absolute_import from __future__ import division from __future__ import",
"existing layers. # Arguments model: Instance of `Model`. input_tensors: optional",
"_input_tensors for x, y in zip(model.inputs, input_tensors): tensor_map[x] = (y,",
"not in kwargs: kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor,",
"tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): # Call layer. if",
"of the existing layers. # Arguments model: Instance of `Sequential`.",
"K from .utils.generic_utils import has_arg from .utils.generic_utils import to_list from",
"= to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks = [computed_mask]",
"a new model from inputs and outputs. output_tensors = []",
"print_function from . import backend as K from .utils.generic_utils import",
"cloning is similar to calling a model on new inputs,",
"# Reuse previously cloned layer. layer = layer_map[layer] # Don't",
"x in reference_input_tensors: if x in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data)",
"in tensor_map: computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): # Call layer.",
"in computed_data] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs:",
"[] input_tensors = [] for layer in model._input_layers: input_tensor =",
"call node.inbound_layer on them. computed_data = [] # List of",
"# If tensor comes from an input layer: cache the",
"name=model.name) else: raise ValueError('Cannot clone a `Sequential` model on top",
".engine.saving import save_mxnet_model try: import h5py except ImportError: h5py =",
"= model._nodes_by_depth[depth] for node in nodes: # Recover the corresponding",
"of new inputs tensors, using newly instantiated weights. # Raises",
"for x in computed_data] if has_arg(layer.call, 'mask'): if 'mask' not",
"'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_mask output_tensors",
"name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache newly created input layer.",
"every node in the reference model, in depth order. depth_keys",
"= [clone(layer) for layer in model.layers] if input_tensors is None:",
"[x[0] for x in computed_data] computed_masks = [x[1] for x",
"layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original, _cloned",
"computed_data = [] # List of tuples (input, mask). for",
".engine.saving import model_from_json from .engine.saving import save_mxnet_model try: import h5py",
"'to be a `Model` instance, got ', model) if isinstance(model,",
"in tensor_map, # then call node.inbound_layer on them. computed_data =",
"input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) _input_tensors.append(input_tensor) # Cache newly",
"name=model.name) else: if len(to_list(input_tensors)) != 1: raise ValueError('To clone a",
"Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer] +",
"got:', model) def clone(layer): return layer.__class__.from_config(layer.get_config()) layers = [clone(layer) for",
"model from inputs and outputs. output_tensors = [] for x",
"to build the model upon. If not provided, placeholders will",
"raise ValueError('Cannot clone a `Sequential` model on top ' 'of",
"tensors to build the model upon. If not provided, placeholders",
"name) _input_tensors.append(input_tensor) # Cache newly created input layer. original_input_layer =",
"= node.arguments else: kwargs = {} if len(computed_data) == 1:",
"return Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors)) != 1: raise ValueError('To",
"a `Sequential` model instance. Model cloning is similar to calling",
"x in computed_data] computed_masks = [x[1] for x in computed_data]",
"for created layers. tensor_map = {} # Map {reference_tensor: (corresponding_tensor,",
"all previous input tensors are available in tensor_map, # then",
"output_tensors, output_masks): tensor_map[x] = (y, mask) # Check that we",
"`Sequential` model on top ' 'of a tensor that comes",
"raise ValueError('To clone a `Sequential` model, we expect ' '",
"`Model` instance, got ', model) if isinstance(model, Sequential): raise ValueError('Expected",
". import backend as K from .utils.generic_utils import has_arg from",
"if isinstance(layer, InputLayer): continue # Gather inputs to call the",
"1: raise ValueError('To clone a `Sequential` model, we expect '",
"input_layers): layer_map[_original] = _cloned else: # Make sure that all",
"from .engine.saving import model_from_json from .engine.saving import save_mxnet_model try: import",
"for x in computed_data] computed_masks = [x[1] for x in",
"# Recover the corresponding layer. layer = node.outbound_layer # Get",
"raise ValueError('Expected `model` argument ' 'to be a `Sequential` model",
"of the existing layers. # Arguments model: Instance of `Model`",
"utilities. \"\"\" from __future__ import absolute_import from __future__ import division",
"<filename>keras/models.py \"\"\"Model-related utilities. \"\"\" from __future__ import absolute_import from __future__",
"for x in model.outputs: assert x in tensor_map, 'Could not",
"be created. # Returns An instance of `Sequential` reproducing the",
"a Keras layer. # If tensor comes from an input",
"= to_list( layer(computed_tensors, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) #",
"model: Instance of `Model`. input_tensors: optional list of input tensors",
"are available in tensor_map, # then call node.inbound_layer on them.",
"model.outputs: assert x in tensor_map, 'Could not compute output '",
"import h5py except ImportError: h5py = None def _clone_functional_model(model, input_tensors=None):",
"x, y in zip(model.inputs, input_tensors): tensor_map[x] = (y, None) #",
"# Cache newly created input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer]",
"a `Model` instance, got ', model) if isinstance(model, Sequential): raise",
"not in layer_map: # Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer]",
"' 'got a `Sequential` instance instead:', model) layer_map = {}",
"argument value. \"\"\" if not isinstance(model, Sequential): raise ValueError('Expected `model`",
"a functional model or a Sequential model). input_tensors: optional list",
"layer = node.outbound_layer # Get or create layer. if layer",
"Sequential(layers=[input_layer] + layers, name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone any `Model`",
"depth in depth_keys: nodes = model._nodes_by_depth[depth] for node in nodes:",
"import division from __future__ import print_function from . import backend",
"= [] for i, x in enumerate(input_tensors): if not K.is_keras_tensor(x):",
"value. \"\"\" if not isinstance(model, Model): raise ValueError('Expected `model` argument",
"newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original, _cloned in",
"K.is_keras_tensor(x): origin_layer = x._keras_history[0] if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] +",
"Clone layer. new_layer = layer.__class__.from_config(layer.get_config()) layer_map[layer] = new_layer layer =",
"if 'mask' not in kwargs: kwargs['mask'] = computed_mask output_tensors =",
"instance of `Model` reproducing the behavior of the original model,",
"if input_tensors is None: return Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors))",
"and outputs. output_tensors = [] for x in model.outputs: assert",
"Sequential from .engine.saving import save_model from .engine.saving import load_model from",
"\"\"\" if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors) else: return _clone_functional_model(model,",
"isinstance(model, Sequential): raise ValueError('Expected `model` argument ' 'to be a",
"or a Sequential model). input_tensors: optional list of input tensors",
"# Arguments model: Instance of `Model`. input_tensors: optional list of",
"' ' at most one tensor ' 'as part of",
"outputs, # then instantiate a new model from inputs and",
"clone_model(model, input_tensors=None): \"\"\"Clone any `Model` instance. Model cloning is similar",
"clone a `Sequential` model on top ' 'of a tensor",
"List of tuples (input, mask). for x in reference_input_tensors: if",
"(y, None) # tensor, mask # Iterated over every node",
"an `InputLayer`. ' 'Use the functional API instead.') input_tensor =",
"name=model.name) def clone_model(model, input_tensors=None): \"\"\"Clone any `Model` instance. Model cloning",
"one tensor ' 'as part of `input_tensors`.') x = to_list(input_tensors)[0]",
"provided, placeholders will be created. # Returns An instance of",
"= node.input_tensors reference_output_tensors = node.output_tensors # If all previous input",
"using newly instantiated weights. # Raises ValueError: in case of",
"that comes from a Keras layer ' 'other than an",
"== 1: computed_tensor, computed_mask = computed_data[0] if has_arg(layer.call, 'mask'): if",
"a `Sequential` model on top ' 'of a tensor that",
"an input layer: cache the input layer. input_tensors = to_list(input_tensors)",
"computed_data.append(tensor_map[x]) if len(computed_data) == len(reference_input_tensors): # Call layer. if node.arguments:",
"_input_tensors.append(input_tensor) # Cache newly created input layer. original_input_layer = x._keras_history[0]",
"newly created input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer",
"output_masks = to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for x,",
".engine.saving import model_from_yaml from .engine.saving import model_from_json from .engine.saving import",
"multiple times. if isinstance(layer, InputLayer): continue # Gather inputs to",
"if has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask'] =",
"[] for i, x in enumerate(input_tensors): if not K.is_keras_tensor(x): name",
"input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly",
"InputLayer multiple times. if isinstance(layer, InputLayer): continue # Gather inputs",
"# Make sure that all input tensors come from a",
"original model, on top of new inputs tensors, using newly",
"== len(reference_input_tensors): # Call layer. if node.arguments: kwargs = node.arguments",
"reference_input_tensors = node.input_tensors reference_output_tensors = node.output_tensors # If all previous",
"Arguments model: Instance of `Model` (could be a functional model",
"raise ValueError('Expected `model` argument ' 'to be a functional `Model`",
"[] # List of tuples (input, mask). for x in",
"we expect ' ' at most one tensor ' 'as",
"h5py = None def _clone_functional_model(model, input_tensors=None): \"\"\"Clone a functional `Model`",
"over every node in the reference model, in depth order.",
"= (y, mask) # Check that we did compute the",
"tensor_map, 'Could not compute output ' + str(x) tensor, _",
"'other than an `InputLayer`. ' 'Use the functional API instead.')",
"**kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks",
"to_list(input_tensors) _input_tensors = [] for i, x in enumerate(input_tensors): if",
"of. input_layers = [] input_tensors = [] for layer in",
"kwargs: kwargs['mask'] = computed_mask output_tensors = to_list( layer(computed_tensor, **kwargs)) output_masks",
"model) layer_map = {} # Cache for created layers. tensor_map",
"isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] + layers, name=model.name) else: raise ValueError('Cannot",
"= _cloned else: # Make sure that all input tensors",
"layer. layer = layer_map[layer] # Don't call InputLayer multiple times.",
"clone a `Sequential` model, we expect ' ' at most",
"layers, name=model.name) else: raise ValueError('Cannot clone a `Sequential` model on",
"invalid `model` argument value. \"\"\" if not isinstance(model, Sequential): raise",
"from .engine.saving import save_model from .engine.saving import load_model from .engine.saving",
"not in kwargs: kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors,",
"layer_map = {} # Cache for created layers. tensor_map =",
"sparse=layer.sparse, name=layer.name) input_tensors.append(input_tensor) # Cache newly created input layer. newly_created_input_layer",
"(corresponding_tensor, mask)} if input_tensors is None: # Create placeholders to",
"'as part of `input_tensors`.') x = to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer",
"input_tensors=None): \"\"\"Clone a functional `Model` instance. Model cloning is similar",
"sure that all input tensors come from a Keras layer.",
"= input_tensor._keras_history[0] layer_map[layer] = newly_created_input_layer for _original, _cloned in zip(model._input_layers,",
"= [] for layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype,",
"for _original, _cloned in zip(model._input_layers, input_layers): layer_map[_original] = _cloned else:",
"_cloned in zip(model._input_layers, input_layers): layer_map[_original] = _cloned else: # Make",
"output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors = [computed_tensor] computed_masks =",
"to_list( layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for x, y, mask",
"Sequential(layers=[origin_layer] + layers, name=model.name) else: raise ValueError('Cannot clone a `Sequential`",
"will be created. # Returns An instance of `Model` reproducing",
"tensor comes from an input layer: cache the input layer.",
"'mask' not in kwargs: kwargs['mask'] = computed_mask output_tensors = to_list(",
"not K.is_keras_tensor(x): name = model._input_layers[i].name input_tensor = Input(tensor=x, name='input_wrapper_for_' +",
"the reference model, in depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True)",
"input_tensors = to_list(input_tensors) _input_tensors = [] for i, x in",
"If all previous input tensors are available in tensor_map, #",
"part of `input_tensors`.') x = to_list(input_tensors)[0] if K.is_keras_tensor(x): origin_layer =",
"try: import h5py except ImportError: h5py = None def _clone_functional_model(model,",
"nodes: # Recover the corresponding layer. layer = node.outbound_layer #",
"of sharing the weights of the existing layers. # Arguments",
"order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for depth in depth_keys: nodes",
"from a Keras layer ' 'other than an `InputLayer`. '",
"layer. # If tensor comes from an input layer: cache",
"instance. Model cloning is similar to calling a model on",
"Arguments model: Instance of `Model`. input_tensors: optional list of input",
"has_arg(layer.call, 'mask'): if 'mask' not in kwargs: kwargs['mask'] = computed_mask",
"the model on top of. input_layers = [] input_tensors =",
"has_arg from .utils.generic_utils import to_list from .engine.input_layer import Input from",
"than an `InputLayer`. ' 'Use the functional API instead.') input_tensor",
"is similar to calling a model on new inputs, except",
"list of input tensors to build the model upon. If",
"for i, x in enumerate(input_tensors): if not K.is_keras_tensor(x): name =",
"model outputs, # then instantiate a new model from inputs",
"`Sequential` model, we expect ' ' at most one tensor",
"node.arguments else: kwargs = {} if len(computed_data) == 1: computed_tensor,",
"`model` argument value. \"\"\" if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors)",
"to_list( layer(computed_tensor, **kwargs)) output_masks = to_list( layer.compute_mask(computed_tensor, computed_mask)) computed_tensors =",
".engine.saving import model_from_config from .engine.saving import model_from_yaml from .engine.saving import",
"come from a Keras layer. # If tensor comes from",
"ValueError: in case of invalid `model` argument value. \"\"\" if",
"= layer_map[layer] # Don't call InputLayer multiple times. if isinstance(layer,",
"node in the reference model, in depth order. depth_keys =",
"\"\"\" if not isinstance(model, Sequential): raise ValueError('Expected `model` argument '",
"Cache newly created input layer. newly_created_input_layer = input_tensor._keras_history[0] layer_map[layer] =",
"layer.compute_mask(computed_tensors, computed_masks)) # Update tensor_map. for x, y, mask in",
"input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers, name=model.name) def clone_model(model,",
"Keras layer ' 'other than an `InputLayer`. ' 'Use the",
"'to be a `Sequential` model instance, ' 'but got:', model)",
"creates new layers (and thus new weights) instead of sharing",
"'of a tensor that comes from a Keras layer '",
"if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors) else: return _clone_functional_model(model, input_tensors=input_tensors)",
"= [computed_mask] else: computed_tensors = [x[0] for x in computed_data]",
"# Call layer. if node.arguments: kwargs = node.arguments else: kwargs",
"zip(model._input_layers, input_layers): layer_map[_original] = _cloned else: # Make sure that",
"not provided, placeholders will be created. # Returns An instance",
"computed_mask)) computed_tensors = [computed_tensor] computed_masks = [computed_mask] else: computed_tensors =",
"_original, _cloned in zip(model._input_layers, input_layers): layer_map[_original] = _cloned else: #",
"from .engine.training import Model from .engine.sequential import Sequential from .engine.saving",
"weights) instead of sharing the weights of the existing layers.",
"'got a `Sequential` instance instead:', model) layer_map = {} #",
"input_layers = [] input_tensors = [] for layer in model._input_layers:",
"import Model from .engine.sequential import Sequential from .engine.saving import save_model",
".engine.saving import save_model from .engine.saving import load_model from .engine.saving import",
"import to_list from .engine.input_layer import Input from .engine.input_layer import InputLayer",
"layers. tensor_map = {} # Map {reference_tensor: (corresponding_tensor, mask)} if",
"`Sequential` reproducing the behavior of the original model, on top",
"input layer: cache the input layer. input_tensors = to_list(input_tensors) _input_tensors",
"= Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer = input_tensor._keras_history[0] return Sequential(layers=[input_layer]",
"newly instantiated weights. # Raises ValueError: in case of invalid",
"y in zip(model.inputs, input_tensors): tensor_map[x] = (y, None) # tensor,",
"= x._keras_history[0] if isinstance(origin_layer, InputLayer): return Sequential(layers=[origin_layer] + layers, name=model.name)",
"# Get or create layer. if layer not in layer_map:",
"= newly_created_input_layer else: _input_tensors.append(x) input_tensors = _input_tensors for x, y",
"from __future__ import division from __future__ import print_function from .",
"input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name)) input_layer = input_tensor._keras_history[0] return",
"existing layers. # Arguments model: Instance of `Model` (could be",
"for layer in model._input_layers: input_tensor = Input(batch_shape=layer.batch_input_shape, dtype=layer.dtype, sparse=layer.sparse, name=layer.name)",
"node.inbound_layer on them. computed_data = [] # List of tuples",
"from an input layer: cache the input layer. input_tensors =",
"computed_mask = computed_data[0] if has_arg(layer.call, 'mask'): if 'mask' not in",
"from .engine.saving import load_model from .engine.saving import model_from_config from .engine.saving",
"sharing the weights of the existing layers. # Arguments model:",
"import save_model from .engine.saving import load_model from .engine.saving import model_from_config",
"= [computed_tensor] computed_masks = [computed_mask] else: computed_tensors = [x[0] for",
"thus new weights) instead of sharing the weights of the",
"input_tensors is None: return Sequential(layers=layers, name=model.name) else: if len(to_list(input_tensors)) !=",
"= computed_data[0] if has_arg(layer.call, 'mask'): if 'mask' not in kwargs:",
"Check that we did compute the model outputs, # then",
"available in tensor_map, # then call node.inbound_layer on them. computed_data",
"# Arguments model: Instance of `Sequential`. input_tensors: optional list of",
"Instance of `Sequential`. input_tensors: optional list of input tensors to",
"kwargs['mask'] = computed_masks output_tensors = to_list( layer(computed_tensors, **kwargs)) output_masks =",
"\"\"\"Clone a `Sequential` model instance. Model cloning is similar to",
"len(computed_data) == len(reference_input_tensors): # Call layer. if node.arguments: kwargs =",
"model._nodes_by_depth[depth] for node in nodes: # Recover the corresponding layer.",
"reference model, in depth order. depth_keys = list(model._nodes_by_depth.keys()) depth_keys.sort(reverse=True) for",
"any `Model` instance. Model cloning is similar to calling a",
"import model_from_json from .engine.saving import save_mxnet_model try: import h5py except",
"a Sequential model). input_tensors: optional list of input tensors to",
"# Cache for created layers. tensor_map = {} # Map",
"of `Sequential`. input_tensors: optional list of input tensors to build",
"= input_tensor._keras_history[0] return Sequential(layers=[input_layer] + layers, name=model.name) def clone_model(model, input_tensors=None):",
"Instance of `Model`. input_tensors: optional list of input tensors to",
"at most one tensor ' 'as part of `input_tensors`.') x"
] |
[
"fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers':",
"fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]',",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'),",
"fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]',",
"### {'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y', 'parentid': fix_path('./tests/x'), },",
"'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name':",
"'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id':",
"fix_path('./tests/w'), 'kind': 'folder', 'name': 'w', 'parentid': fix_path('./tests'), }, ## +++",
"'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++ {'id':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers':",
"'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid':",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [],",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name':",
"'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name':",
"kwargs.pop('hidestdio', True) assert not kwargs kwds = {} argv =",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), },",
"def run_adapter(cmd, tool, *cliargs): try: return _run_adapter(cmd, tool, *cliargs) except",
"group = [] for test in tests: if (curfile or",
"'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"'name': 'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name':",
"'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'),",
"not in test['id']: fixed.extend(sorted(group, key=lambda t: t['id'])) group = []",
"fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped',",
"{'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'),",
"srcfile = test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase):",
"None self.assertEqual(result, expected) def test_discover_not_found(self): projroot, testroot = resolve_testroot('notests') out",
"(curfile or '???') not in test['id']: fixed.extend(sorted(group, key=lambda t: t['id']))",
"'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'),",
"'kind': 'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'),",
"{'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'),",
"fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid':",
"'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ###########",
"'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source':",
"'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'),",
"fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'),",
"'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'),",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33', 'parentid':",
"'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name':",
"'kind': 'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'),",
"= json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected)",
"'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function',",
"fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01', 'parentid':",
"# 'tests': [], # }]) COMPLEX = { 'root': None,",
"fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), },",
"'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'),",
"fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/b/test_spam.py'), },",
"'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id':",
"fix_path(nodeid): return nodeid.replace('/', os.path.sep) def fix_test_order(tests): if sys.version_info >= (3,",
"{'id': fix_path('./tests/x'), 'kind': 'folder', 'name': 'x', 'parentid': fix_path('./tests'), }, ###",
"'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name':",
"'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"found'.format(testid)) if not srcfile: srcfile = test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile,",
"'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function',",
"'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id':",
"fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source':",
"fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), },",
"'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'),",
"'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'), 'kind': 'folder', 'name':",
"fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [],",
"'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, ###########",
"'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"None self.assertEqual(result, [{ 'root': projroot, 'rootid': '.', 'parents': [ {'id':",
"}, ## {'id': fix_path('./tests/v'), 'kind': 'folder', 'name': 'v', 'parentid': fix_path('./tests'),",
"'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name':",
"'kind': 'file', 'name': 'mod.py', 'parentid': '.', }) expected[0]['tests'] = [",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source':",
"'parentid': fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'),",
"'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'),",
"'rootid': '.', # 'parents': [], # 'tests': [], # }])",
"{'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'),",
"fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'],",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'),",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [],",
"'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind':",
"'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"[] for test in tests: if (curfile or '???') not",
"## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'),",
"'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'),",
"'parentid': fix_path('./tests/x/y/z'), }, ], 'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'/')[-1] for arg in argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds) def",
"'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name':",
"t['id'])) return fixed def fix_source(tests, testid, srcfile, lineno): testid =",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'),",
"'name': 'y', 'parentid': fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder',",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'),",
"{'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'),",
"[], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'),",
"'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param', 'parentid':",
"'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite',",
"}, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [], 'parentid':",
"'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'),",
"fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), },",
"+++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), },",
"}, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), },",
"fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), }, ## {'id':",
"## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'),",
"'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'),",
"def test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests']",
"'kind': 'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source':",
"projroot, testroot) result = json.loads(out) self.maxDiff = None self.assertEqual(result, [{",
"testid, None, 0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules',",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13', 'parentid':",
"}, ## {'id': fix_path('./tests/w'), 'kind': 'folder', 'name': 'w', 'parentid': fix_path('./tests'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'),",
"'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers':",
"fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py',",
"'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple',",
"(3, 6): return tests fixed = [] curfile = None",
"run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules', projroot) result = json.loads(out) result[0]['tests']",
"'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name':",
"'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file',",
"'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests',",
"{'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, #",
"'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'),",
"'--rootdir', projroot, testroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff",
"'.', }) expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source':",
"'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name':",
"'parentid': fix_path('./tests'), }, ], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple',",
"'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source':",
"'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++ {'id': fix_path('./tests/test_unittest.py'),",
"'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source':",
"#self.assertEqual(result, [{ # 'root': projroot, # 'rootid': '.', # 'parents':",
"fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [],",
"from test suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name':",
"'w', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file',",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), },",
"}, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source':",
"projroot = os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot, 'tests') def run_adapter(cmd,",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), },",
"'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function',",
"'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'),",
"= os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot = os.path.join(DATA_DIR, name) return",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"}, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid':",
"'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'),",
"'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ######",
"'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam',",
"'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name':",
"'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name':",
"'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ], 'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'),",
"{ 'id': fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py', 'parentid': '.', })",
"expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [],",
"def fix_test_order(tests): if sys.version_info >= (3, 6): return tests fixed",
"fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name':",
"fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'),",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid':",
"'id': fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py', 'parentid': '.', }) expected[0]['tests']",
"*cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio', True) assert not kwargs kwds",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source':",
"fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), },",
"'source': fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name':",
"os.path import subprocess import sys import unittest import pytest from",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'),",
"'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function',",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'),",
"'folder', 'name': 'x', 'parentid': fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'), 'kind':",
"'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source':",
"fix_path('./tests/w'), }, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py',",
"'--doctest-modules', projroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff =",
"self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex') expected =",
"'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid':",
"fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function',",
"{'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'),",
"fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]',",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'),",
"fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers':",
"testroot) result = json.loads(out) self.maxDiff = None self.assertEqual(result, []) #",
"fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind':",
"following instead? #self.assertEqual(result, [{ # 'root': projroot, # 'rootid': '.',",
"'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'),",
"os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot =",
"}, # +++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py', 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'test_spam.py', 'parentid': fix_path('./tests'), }, ], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source':",
"'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite',",
"'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'),",
"except subprocess.CalledProcessError as exc: print(exc.output) def _run_adapter(cmd, tool, *cliargs, **kwargs):",
"= run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules', projroot) result = json.loads(out)",
"'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function',",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [],",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers':",
"test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex') expected = self.complex(projroot) # add",
"fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py',",
"fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'),",
"'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'),",
"result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_complex_doctest(self):",
"'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name':",
"'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers':",
"'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function',",
"fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'),",
"'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id':",
"'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite',",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), },",
"try: return _run_adapter(cmd, tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError as exc:",
"fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), },",
"'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'),",
"fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), },",
"fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source':",
"fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]',",
"test['id'] == testid: break else: raise KeyError('test {!r} not found'.format(testid))",
"reserved. # Licensed under the MIT License. from __future__ import",
"'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite',",
"return _run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError: # Re-run pytest but",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]',",
"fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]',",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name':",
"'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'),",
"fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'), }, ##### {'id':",
"'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind':",
"'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id':",
"'parentid': fix_path('./tests/w'), }, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name':",
"PytestTests(unittest.TestCase): def complex(self, testroot): results = COMPLEX.copy() results['root'] = testroot",
"['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'),",
"'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid':",
"'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id':",
"sys.version_info >= (3, 6): return tests fixed = [] curfile",
"'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), }, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'),",
"'name': 'tests', 'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), },",
"subprocess.CalledProcessError: # Re-run pytest but print out stdout & stderr",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'),",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [],",
"= fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped',",
"'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'), 'kind': 'folder',",
"fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]',",
"'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'),",
"argv = [sys.executable, SCRIPT, cmd, tool, '--'] + list(cliargs) if",
"fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'),",
"########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid':",
"['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'),",
"'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [],",
"MIT License. from __future__ import unicode_literals import json import os",
"}, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [],",
"fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [],",
"fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure',",
"'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'),",
"fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [],",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]',",
"'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'),",
"'z', 'parentid': fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name':",
"'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id':",
"'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name':",
"###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'),",
"fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'), 'kind': 'folder', 'name': 'w', 'parentid':",
"'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id':",
"'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), },",
"{'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'),",
"fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'],",
"hidestdio = kwargs.pop('hidestdio', True) assert not kwargs kwds = {}",
"'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name':",
"'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind':",
"fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'),",
"'tests', 'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py',",
"fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++",
"instead? #self.assertEqual(result, [{ # 'root': projroot, # 'rootid': '.', #",
"'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'),",
"fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]',",
"fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped',",
"'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'),",
"'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind':",
"'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid':",
"'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name':",
"'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), },",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'),",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id':",
"'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'),",
"'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), }) #",
"fix_path('./tests/x'), 'kind': 'folder', 'name': 'x', 'parentid': fix_path('./tests'), }, ### {'id':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers':",
"'./tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in decorated: fix_source(expected[0]['tests'], testid,",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), },",
"[] curfile = test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group, key=lambda t:",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'),",
"fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), },",
"import unicode_literals import json import os import os.path import subprocess",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'),",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'),",
"not found'.format(testid)) if not srcfile: srcfile = test['source'].rpartition(':')[0] test['source'] =",
"= resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info",
"= None self.assertEqual(result, expected) def test_discover_not_found(self): projroot, testroot = resolve_testroot('notests')",
"'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"'name': 'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name':",
"'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name':",
"*cliargs) except subprocess.CalledProcessError: # Re-run pytest but print out stdout",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [],",
"'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers':",
"'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id':",
"fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped',",
"fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs',",
"self.maxDiff = None self.assertEqual(result, expected) def test_discover_not_found(self): projroot, testroot =",
"'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ], 'tests': [",
"'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'),",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [],",
"fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id':",
"'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"= None self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex')",
"{'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'),",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers':",
"}, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid':",
"}]) def test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex') expected = self.complex(projroot)",
"'test_ham.py', 'parentid': fix_path('./tests/v'), }, ## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file',",
"# +++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'),",
"'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), }) # add in doctests from",
"}, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid':",
"fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), },",
"{'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), }, #",
"as exc: print(exc.output) def _run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio =",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name':",
"{'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ##",
"'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id':",
"'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple',",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers':",
"fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), },",
"{!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for arg in argv))) return subprocess.check_output(argv,",
"'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), },",
"'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source':",
"import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT",
"'--'] + list(cliargs) if not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] =",
"fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'),",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [],",
"rights reserved. # Licensed under the MIT License. from __future__",
"if not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running",
"}, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source':",
"fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name':",
"+++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'), },",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'),",
"'source': fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name':",
"'source': fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'), }, ] + expected[0]['tests']",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id':",
"'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'),",
"fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), },",
"None, 'rootid': '.', 'parents': [ # {'id': fix_path('./tests'), 'kind': 'folder',",
"fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple',",
"'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function',",
"'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source':",
"'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13',",
"= fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_not_found(self): projroot,",
"fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), },",
"fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source':",
"'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/b/test_spam.py'), }, ],",
"test_discover_simple(self): projroot, testroot = resolve_testroot('simple') out = run_adapter('discover', 'pytest', '--rootdir',",
"'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'), }, ], 'tests': [ {'id':",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [],",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers':",
"fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'),",
"'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]',",
"'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers',",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"{'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers':",
"}, ## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py', 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple',",
"= [] curfile = test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group, key=lambda",
"'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'),",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'),",
"print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for arg in argv))) return",
"[], 'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source':",
"##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'),",
"fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'],",
"{'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'),",
"'--rootdir', projroot, testroot) result = json.loads(out) self.maxDiff = None self.assertEqual(result,",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"{'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'),",
"fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'),",
"COMPLEX = { 'root': None, 'rootid': '.', 'parents': [ #",
"fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'), },",
"# +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'),",
"{'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard',",
"list(cliargs) if not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear')",
"'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'),",
"_run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError: # Re-run pytest but print",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'),",
"_run_adapter(cmd, tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError as exc: print(exc.output) def",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple',",
"'markers': [], 'parentid': fix_path('./mod.py'), }, ] + expected[0]['tests'] expected[0]['tests'] =",
"fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), },",
"fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), },",
"'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source':",
"'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), }, #####",
"self.maxDiff = None self.assertEqual(result, []) # TODO: Expect the following",
"{'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ##",
"import json import os import os.path import subprocess import sys",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers':",
"}, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [],",
"'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid':",
"'folder', 'name': 'y', 'parentid': fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'), 'kind':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'),",
"print out stdout & stderr this time try: return _run_adapter(cmd,",
"{'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"def resolve_testroot(name): projroot = os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot, 'tests')",
"{'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'),",
"'kind': 'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source':",
"'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'),",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), },",
"}, # +++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py', 'parentid':",
"'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'),",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [],",
"'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), },",
"'name': 'w', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind':",
"not srcfile: srcfile = test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional",
"'kind': 'folder', 'name': 'y', 'parentid': fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'),",
"'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source':",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers':",
"run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result = json.loads(out) result[0]['tests'] =",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers':",
"}, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid':",
"cmd, tool, '--'] + list(cliargs) if not hidestdio: argv.insert(4, '--no-hide-stdio')",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'),",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source':",
"'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests',",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [],",
"'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13',",
"'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id':",
"+ '/')[-1] for arg in argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds)",
"'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ######",
"'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name':",
"DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name):",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [],",
"'kind': 'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind':",
"'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture', 'parentid':",
"'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat',",
"fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), },",
"return nodeid.replace('/', os.path.sep) def fix_test_order(tests): if sys.version_info >= (3, 6):",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source':",
"'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'),",
"{'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]',",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"'b', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file',",
"# TODO: Expect the following instead? #self.assertEqual(result, [{ # 'root':",
"fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]',",
"{'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'),",
"return [results] def test_discover_simple(self): projroot, testroot = resolve_testroot('simple') out =",
"{'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, #",
"json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def",
"fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]',",
"tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError as exc: print(exc.output) def _run_adapter(cmd,",
"resolve_testroot('notests') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result =",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'),",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source':",
"{'id': fix_path('./tests/v'), 'kind': 'folder', 'name': 'v', 'parentid': fix_path('./tests'), }, ##",
"'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function',",
"TODO: Expect the following instead? #self.assertEqual(result, [{ # 'root': projroot,",
"}, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"'kind': 'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind':",
"fixed def fix_source(tests, testid, srcfile, lineno): testid = fix_path(testid) for",
"'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id':",
"projroot, os.path.join(projroot, 'tests') def run_adapter(cmd, tool, *cliargs): try: return _run_adapter(cmd,",
"fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers':",
"{ 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'), })",
"'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'),",
"'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"{'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y', 'parentid': fix_path('./tests/x'), }, ####",
"'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'),",
"'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'),",
"'run_adapter.py') def resolve_testroot(name): projroot = os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot,",
"}, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [],",
"{'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id':",
"{!r} not found'.format(testid)) if not srcfile: srcfile = test['source'].rpartition(':')[0] test['source']",
"fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure',",
"fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [],",
"None, 0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules', projroot)",
"fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"'kind': 'folder', 'name': 'tests', 'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'), 'kind':",
"the following instead? #self.assertEqual(result, [{ # 'root': projroot, # 'rootid':",
"fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]',",
"'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple',",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]',",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'),",
"{'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'), }, ],",
"'rootid': '.', 'parents': [ {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests',",
"}, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip',",
"fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'],",
"fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple',",
"fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]',",
"'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers':",
"'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'),",
"fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), },",
"# +++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'),",
"expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'),",
"complex(self, testroot): results = COMPLEX.copy() results['root'] = testroot return [results]",
"fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [],",
"'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, ######",
"'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'),",
"fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'),",
"'parentid': fix_path('./tests/test_doctest.py'), }) # add in doctests from non-test module",
"fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture',",
"fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id':",
"'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'),",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'),",
"'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'),",
"# +++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'),",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple',",
"}, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers':",
"'kind': 'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind':",
"json.loads(out) self.maxDiff = None self.assertEqual(result, [{ 'root': projroot, 'rootid': '.',",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid':",
"'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), },",
"'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple', 'parentid':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source':",
"'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers':",
"fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), },",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source':",
"'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite',",
"'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind':",
"}, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [],",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source':",
"'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name':",
"fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), },",
"{'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'),",
"fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]',",
"subprocess import sys import unittest import pytest from ...__main__ import",
"'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), },",
"{} argv = [sys.executable, SCRIPT, cmd, tool, '--'] + list(cliargs)",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers':",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid':",
"import subprocess import sys import unittest import pytest from ...__main__",
"'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id':",
"'kind': 'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers':",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'),",
"fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), },",
"'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name':",
"self.assertEqual(result, []) # TODO: Expect the following instead? #self.assertEqual(result, [{",
"'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source':",
"projroot, testroot = resolve_testroot('notests') out = run_adapter('discover', 'pytest', '--rootdir', projroot,",
"'.py' group.append(test) fixed.extend(sorted(group, key=lambda t: t['id'])) return fixed def fix_source(tests,",
"'.', 'parents': [ # {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests',",
"# add in doctests from non-test module expected[0]['parents'].insert(0, { 'id':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'),",
"fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'),",
"'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers':",
"'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name':",
"{'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'),",
"}, ], }]) def test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex') expected",
"fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'), },",
"'folder', 'name': 'w', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/w/test_spam.py'),",
"}, # +++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py', 'parentid':",
"fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]',",
"& stderr this time try: return _run_adapter(cmd, tool, *cliargs, hidestdio=False)",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'),",
"fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), }) # add in doctests",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'),",
"'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name':",
"fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'),",
"fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises',",
"{'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'),",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'),",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source':",
"fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped',",
"under the MIT License. from __future__ import unicode_literals import json",
"'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name':",
"'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'),",
"'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name':",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), },",
"'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source':",
"module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py', 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"[{ # 'root': projroot, # 'rootid': '.', # 'parents': [],",
"'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'), 'kind':",
"'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source':",
"'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), },",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers':",
"{'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id':",
"## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'),",
"'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id':",
"## {'id': fix_path('./tests/w'), 'kind': 'folder', 'name': 'w', 'parentid': fix_path('./tests'), },",
"None group = [] for test in tests: if (curfile",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'),",
"fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'),",
"License. from __future__ import unicode_literals import json import os import",
"sys import unittest import pytest from ...__main__ import TESTING_TOOLS_ROOT CWD",
"0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules', projroot) result",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source':",
"{'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'),",
"}, ## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid':",
"'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name':",
"'test_spam.py', 'parentid': fix_path('./tests/w'), }, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file',",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers':",
"fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"for testid in decorated: fix_source(expected[0]['tests'], testid, None, 0) out =",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid':",
"'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'),",
"fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py',",
"fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests',",
"fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'), }, # +++",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid':",
"'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name':",
"###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid':",
"'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'),",
"'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'),",
"'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id':",
"'pytest', '--rootdir', projroot, testroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests'])",
"'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name':",
"}, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid':",
"'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [],",
"fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name':",
"fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'],",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), },",
"'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, # +++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file',",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'),",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'),",
"] for testid in decorated: fix_source(expected[0]['tests'], testid, None, 0) out",
"'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function',",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [],",
"= [] curfile = None group = [] for test",
"{'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), },",
"'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'),",
"[], 'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source':",
"fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple',",
"fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"# +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'),",
"###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid':",
"= None group = [] for test in tests: if",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'),",
"tests fixed = [] curfile = None group = []",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'),",
"'tests') def run_adapter(cmd, tool, *cliargs): try: return _run_adapter(cmd, tool, *cliargs)",
"}, ## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid':",
"def test_discover_not_found(self): projroot, testroot = resolve_testroot('notests') out = run_adapter('discover', 'pytest',",
"+ expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated",
"'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name':",
"+ '.py' group.append(test) fixed.extend(sorted(group, key=lambda t: t['id'])) return fixed def",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [],",
"SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot = os.path.join(DATA_DIR, name)",
"fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid':",
"'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll',",
"resolve_testroot(name): projroot = os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot, 'tests') def",
"testid in decorated: fix_source(expected[0]['tests'], testid, None, 0) out = run_adapter('discover',",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), },",
"'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'),",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source':",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source':",
"'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'),",
"'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid':",
"'./tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in decorated: fix_source(expected[0]['tests'], testid, None, 0)",
"'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'),",
"}, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid':",
"'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id':",
"'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file',",
"'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id':",
"'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name':",
"curfile = test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group, key=lambda t: t['id']))",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source':",
"fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), },",
"return _run_adapter(cmd, tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError as exc: print(exc.output)",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers':",
"fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]',",
"except subprocess.CalledProcessError: # Re-run pytest but print out stdout &",
"fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [],",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name':",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [],",
"'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'),",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'),",
"'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'), }, ] +",
"fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name':",
"fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [],",
"'name': 'a', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind':",
"[], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'),",
"expected) def test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex') expected = self.complex(projroot)",
"{'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'),",
"fixed.extend(sorted(group, key=lambda t: t['id'])) group = [] curfile = test['id'].partition('.py::')[0]",
"'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name':",
"'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name':",
"}, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'),",
"fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z', 'parentid':",
"'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'), }, ], }]) def",
"CWD = os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT,",
"{'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source':",
"'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name':",
"fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ], 'tests':",
"'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'),",
"= fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self, testroot): results",
"##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid':",
"projroot, # 'rootid': '.', # 'parents': [], # 'tests': [],",
"'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source':",
"'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'),",
"}, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid':",
"'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest',",
"'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped',",
"'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name':",
"'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id':",
"'markers': [], 'parentid': fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt',",
"fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), })",
"[], # }]) COMPLEX = { 'root': None, 'rootid': '.',",
"fix_source(expected[0]['tests'], testid, None, 0) out = run_adapter('discover', 'pytest', '--rootdir', projroot,",
"'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id':",
"fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]',",
"}, ## {'id': fix_path('./tests/x'), 'kind': 'folder', 'name': 'x', 'parentid': fix_path('./tests'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid':",
"tests: if (curfile or '???') not in test['id']: fixed.extend(sorted(group, key=lambda",
"fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), },",
"'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'),",
"'kind': 'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind':",
"= COMPLEX.copy() results['root'] = testroot return [results] def test_discover_simple(self): projroot,",
"in argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid): return nodeid.replace('/',",
"}, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), },",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'),",
"fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped',",
"'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers':",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'),",
"[], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'),",
"'parentid': '.', }) expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'), 'name': 'mod',",
"[ {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', },",
"'x', 'parentid': fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name':",
"sys.version_info < (3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ]",
"'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'),",
"'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'),",
"self.maxDiff = None self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot, _ =",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid':",
"{'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'),",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'parentid': fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a',",
"t: t['id'])) return fixed def fix_source(tests, testid, srcfile, lineno): testid",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers':",
"'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name':",
"fix_path('./tests/x/y/z'), }, ], 'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple',",
"'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name':",
"{'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/b/test_spam.py'),",
"}, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids', 'parentid':",
"fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [],",
"'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, #####",
"'kind': 'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind':",
"= [] for test in tests: if (curfile or '???')",
"'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name':",
"testid: break else: raise KeyError('test {!r} not found'.format(testid)) if not",
"fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name':",
"results['root'] = testroot return [results] def test_discover_simple(self): projroot, testroot =",
"Expect the following instead? #self.assertEqual(result, [{ # 'root': projroot, #",
"universal_newlines=True, **kwds) def fix_path(nodeid): return nodeid.replace('/', os.path.sep) def fix_test_order(tests): if",
"fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'),",
"{'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), }, ##",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid':",
"'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'),",
"'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_',",
"{'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers':",
"'folder', 'name': 'tests', 'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file',",
"'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite', 'parentid':",
"= resolve_testroot('notests') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result",
"'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'),",
"fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]',",
"########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid':",
"'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level',",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id':",
"expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated = [",
"fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, # +++",
"fix_path('./tests/v'), 'kind': 'folder', 'name': 'v', 'parentid': fix_path('./tests'), }, ## +++",
"'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name':",
"os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot, 'tests') def run_adapter(cmd, tool, *cliargs):",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"out = run_adapter('discover', 'pytest', '--rootdir', projroot, '--doctest-modules', projroot) result =",
"'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source':",
"], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers':",
"fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'),",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), },",
"fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self, testroot): results =",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'),",
"'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13',",
"'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'),",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]',",
"**kwds) def fix_path(nodeid): return nodeid.replace('/', os.path.sep) def fix_test_order(tests): if sys.version_info",
"'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id':",
"'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source':",
"'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs',",
"fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'),",
"'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple',",
"'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name':",
"'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers':",
"'test_42.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file',",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers':",
"projroot, _ = resolve_testroot('complex') expected = self.complex(projroot) # add in",
"key=lambda t: t['id'])) group = [] curfile = test['id'].partition('.py::')[0] +",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source':",
"fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [],",
"'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id':",
"testid = fix_path(testid) for test in tests: if test['id'] ==",
"'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_mixed.py'),",
"'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function',",
"tool, *cliargs) except subprocess.CalledProcessError: # Re-run pytest but print out",
"KeyError('test {!r} not found'.format(testid)) if not srcfile: srcfile = test['source'].rpartition(':')[0]",
"{'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name':",
"'.join(arg.rpartition(CWD + '/')[-1] for arg in argv))) return subprocess.check_output(argv, universal_newlines=True,",
"[]) # TODO: Expect the following instead? #self.assertEqual(result, [{ #",
"'folder', 'name': 'tests', 'parentid': '.', }, # +++ {'id': fix_path('./tests/test_42-43.py'),",
"'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name':",
"'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), }) # add",
"fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), },",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'),",
"'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name':",
"= kwargs.pop('hidestdio', True) assert not kwargs kwds = {} argv",
"fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'),",
"fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), },",
"'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, # +++ {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers':",
"'parentid': fix_path('./tests/x/y/z/b'), }, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name':",
"__future__ import unicode_literals import json import os import os.path import",
"= [sys.executable, SCRIPT, cmd, tool, '--'] + list(cliargs) if not",
"# }]) COMPLEX = { 'root': None, 'rootid': '.', 'parents':",
"'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), }, ## +++ {'id':",
"'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind':",
"'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source':",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid':",
"[ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid':",
"'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'),",
"{'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'),",
"'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name':",
"for test in tests: if (curfile or '???') not in",
"'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'),",
"'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id':",
"########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers': [], 'parentid':",
"expected = self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,):",
"'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'),",
"fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), },",
"'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]',",
"fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py',",
"{'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), },",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'),",
"'source': fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name':",
"< (3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for",
"{'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ##",
"[], 'parentid': fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source':",
"}, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid':",
"'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite',",
"'file', 'name': 'mod.py', 'parentid': '.', }) expected[0]['tests'] = [ {'id':",
"'???') not in test['id']: fixed.extend(sorted(group, key=lambda t: t['id'])) group =",
"}, ## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid':",
"'name': 'test_42-43.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_42.py'), 'kind':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), },",
"fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), },",
"# {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', },",
"'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers':",
"'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'),",
"fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'),",
"= run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result = json.loads(out) self.maxDiff",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [],",
"fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name':",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers':",
"+++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), },",
"= None self.assertEqual(result, []) # TODO: Expect the following instead?",
"########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid':",
"'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id':",
"fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]',",
"{'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source':",
"fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam',",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'),",
"from __future__ import unicode_literals import json import os import os.path",
"fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [],",
"'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name':",
"'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name':",
"fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'),",
"'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'), 'kind': 'folder',",
"fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]',",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid':",
"fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), },",
"{'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'),",
"'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name':",
"fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests',",
"'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name':",
"fix_path('./tests/v'), }, ## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py',",
"'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'),",
"'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'),",
"{'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++",
"'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source':",
"'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'),",
"[results] def test_discover_simple(self): projroot, testroot = resolve_testroot('simple') out = run_adapter('discover',",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers':",
"'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name':",
"'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'),",
"fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), },",
"{'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'),",
"'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'), }, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'),",
"'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'),",
"'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name':",
"= fix_path(testid) for test in tests: if test['id'] == testid:",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid':",
"'parentid': fix_path('./mod.py'), }, ] + expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if",
"'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'),",
"stderr this time try: return _run_adapter(cmd, tool, *cliargs, hidestdio=False) except",
"fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), },",
"'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, # +++ {'id': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), },",
"out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result = json.loads(out)",
"}, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), },",
"if (curfile or '???') not in test['id']: fixed.extend(sorted(group, key=lambda t:",
"'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id':",
"'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'),",
"fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'),",
"try: return _run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError: # Re-run pytest",
"fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'),",
"'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source':",
"'root': None, 'rootid': '.', 'parents': [ # {'id': fix_path('./tests'), 'kind':",
"'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), }, ## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind':",
"}, ], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'),",
"fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"os.path.join(projroot, 'tests') def run_adapter(cmd, tool, *cliargs): try: return _run_adapter(cmd, tool,",
"}) expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source':",
"= {} argv = [sys.executable, SCRIPT, cmd, tool, '--'] +",
"}, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid':",
"'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33',",
"}, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), },",
"'kind': 'suite', 'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, # +++ {'id':",
"'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests',",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"[], 'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source':",
"'tests', 'parentid': '.', }, # +++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file',",
"0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result =",
"fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'),",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers':",
"'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name':",
"'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name':",
"'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'),",
"fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'),",
"'a', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file',",
"'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name':",
"fix_path('./mod.py'), }, ] + expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info",
"'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ######",
"+++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), },",
"fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot = os.path.join(DATA_DIR, name) return projroot,",
"# +++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'),",
"'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name':",
"testroot = resolve_testroot('notests') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot)",
"{'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name':",
"fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name':",
"'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name':",
"}, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid':",
"fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py',",
"'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers':",
"}, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [],",
"'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name':",
"fix_path(testid) for test in tests: if test['id'] == testid: break",
"'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id':",
"= resolve_testroot('simple') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result",
"t['id'])) group = [] curfile = test['id'].partition('.py::')[0] + '.py' group.append(test)",
"'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'),",
"'name': 'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name':",
"'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01',",
"}, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [],",
"test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self,",
"{'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"'test_foo.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file',",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'),",
"subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid): return nodeid.replace('/', os.path.sep) def fix_test_order(tests):",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'),",
"{'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'),",
"'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ], 'tests': [ ##########",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'),",
"'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'),",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers':",
"'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id':",
"fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), },",
"}) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13',",
"projroot, testroot) result = json.loads(out) self.maxDiff = None self.assertEqual(result, [])",
"'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'),",
"subprocess.CalledProcessError as exc: print(exc.output) def _run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio",
"'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function',",
"'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'),",
"}, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid':",
"'parents': [ {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.',",
"'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id':",
"'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13',",
"raise KeyError('test {!r} not found'.format(testid)) if not srcfile: srcfile =",
"+++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), },",
"the MIT License. from __future__ import unicode_literals import json import",
"fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'),",
"'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'),",
"'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'),",
"[], 'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source':",
"None self.assertEqual(result, []) # TODO: Expect the following instead? #self.assertEqual(result,",
"argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid): return nodeid.replace('/', os.path.sep)",
"'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id':",
"'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), },",
"'folder', 'name': 'v', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/v/test_eggs.py'),",
"fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"testroot return [results] def test_discover_simple(self): projroot, testroot = resolve_testroot('simple') out",
"key=lambda t: t['id'])) return fixed def fix_source(tests, testid, srcfile, lineno):",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source':",
"= resolve_testroot('complex') expected = self.complex(projroot) # add in doctests from",
"'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name':",
"fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'),",
"fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped',",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam', 'parentid':",
"'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid':",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid':",
"'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), }, #####",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), },",
"'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers':",
"run_adapter(cmd, tool, *cliargs): try: return _run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError:",
"*cliargs): try: return _run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError: # Re-run",
"'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'),",
"'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'),",
"test['id']: fixed.extend(sorted(group, key=lambda t: t['id'])) group = [] curfile =",
"fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [],",
"'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_spam.py'), }, ], }]) def test_discover_complex_default(self): projroot, testroot",
"'name': 'v', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind':",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'),",
"'name': 'tests', 'parentid': '.', }, # +++ {'id': fix_path('./tests/test_42-43.py'), 'kind':",
"fix_path('./tests/w/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple',",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid':",
"'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers':",
"+++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), },",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite',",
"'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid':",
"'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), }, ## +++ {'id': fix_path('./tests/v/test_spam.py'),",
"fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture',",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id':",
"not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format('",
"'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'),",
"'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name':",
"fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot, _",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid':",
"'kind': 'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind':",
"'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'],",
"'parentid': fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'), 'kind': 'folder', 'name': 'x',",
"] + expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,):",
"[], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source':",
"'parentid': fix_path('./tests/test_pytest.py'), }, # +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid':",
"fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'),",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [],",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers':",
"{'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', }, {'id':",
"}, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source':",
"'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name':",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source':",
"{'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'),",
"fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'),",
"fix_test_order(tests): if sys.version_info >= (3, 6): return tests fixed =",
"'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ], 'tests': [ ########## {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid':",
"class PytestTests(unittest.TestCase): def complex(self, testroot): results = COMPLEX.copy() results['root'] =",
"json import os import os.path import subprocess import sys import",
"fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]',",
"test in tests: if (curfile or '???') not in test['id']:",
"'parentid': fix_path('./tests/test_mixed.py'), }, # +++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name':",
"'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'),",
"'mod.py', 'parentid': '.', }) expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'), 'name':",
"fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]',",
"srcfile, lineno): testid = fix_path(testid) for test in tests: if",
"fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]',",
"}, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [],",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'),",
"def fix_source(tests, testid, srcfile, lineno): testid = fix_path(testid) for test",
"*cliargs, hidestdio=False) except subprocess.CalledProcessError as exc: print(exc.output) def _run_adapter(cmd, tool,",
"'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers':",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source':",
"'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source':",
"{'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'),",
"_ = resolve_testroot('complex') expected = self.complex(projroot) # add in doctests",
"else: raise KeyError('test {!r} not found'.format(testid)) if not srcfile: srcfile",
"+++ {'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'), },",
"{ 'root': None, 'rootid': '.', 'parents': [ # {'id': fix_path('./tests'),",
"{'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'),",
"'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11',",
"fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [],",
"'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id':",
"'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'), }, ],",
"'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam',",
"import os.path import subprocess import sys import unittest import pytest",
"{'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', }, #",
"}, # +++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py', 'parentid':",
"'kind': 'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source':",
"= testroot return [results] def test_discover_simple(self): projroot, testroot = resolve_testroot('simple')",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, # +++",
"'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'),",
"[], 'parentid': fix_path('./tests/test_doctest.py'), }) # add in doctests from non-test",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source':",
"'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'),",
"'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'),",
"'source': fix_path('./tests/test_pytest.py:73'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name':",
"fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source':",
"'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid':",
"'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'),",
"'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function',",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), },",
"fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), }, ## +++",
"{'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'],",
"[], 'parentid': fix_path('./mod.py'), }, ] + expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests'])",
"}, # +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py', 'parentid':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source':",
"fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'), 'kind': 'folder', 'name': 'x', 'parentid':",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid':",
"= test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def",
"'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind':",
"fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'), 'kind':",
"test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests'] =",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'),",
"+++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'), },",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), },",
"fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]',",
"fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'), }, ] + expected[0]['tests'] expected[0]['tests']",
"}, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [],",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple',",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'),",
"##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid':",
"resolve_testroot('complex') expected = self.complex(projroot) # add in doctests from test",
"fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]',",
"fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed',",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'),",
"...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data')",
"print(exc.output) def _run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio', True)",
"fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), }, # +++",
"projroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source':",
"testroot = resolve_testroot('simple') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot)",
"'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'),",
"'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'),",
"'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name':",
"'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id':",
"doctests from test suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file',",
"+++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'), },",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises', 'parentid':",
"fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), },",
"fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), },",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid':",
"'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'),",
"resolve_testroot('simple') out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result =",
"subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for arg in",
"fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source':",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name':",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped', 'source': fix_path('./tests/test_unittest.py:17'), 'markers': [],",
"# add in doctests from test suite expected[0]['parents'].insert(3, { 'id':",
"'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'),",
"'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id':",
"}, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'),",
"'test_42-43.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file',",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'],",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source':",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'),",
"fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [],",
"{'id': fix_path('./tests/test_mixed.py'), 'kind': 'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id':",
"test suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py',",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source':",
"'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), }, ## +++ {'id':",
"'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.py'), }) # add in",
"name) return projroot, os.path.join(projroot, 'tests') def run_adapter(cmd, tool, *cliargs): try:",
"+++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), },",
"{'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'),",
"[], 'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"[ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid':",
"group = [] curfile = test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group,",
"fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid':",
"'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name':",
"= os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot",
"'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name':",
"= None self.assertEqual(result, [{ 'root': projroot, 'rootid': '.', 'parents': [",
"'v', 'parentid': fix_path('./tests'), }, ## +++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file',",
"fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'), }, # +++",
"TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT =",
"'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers':",
"fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py',",
"fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure',",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name':",
"fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"unittest import pytest from ...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd()",
"'name': 'test_spam.py', 'parentid': fix_path('./tests/w'), }, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind':",
"}, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid':",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"import os import os.path import subprocess import sys import unittest",
"'kind': 'folder', 'name': 'x', 'parentid': fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'),",
"}, # +++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py', 'parentid':",
"{'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'),",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'),",
"'parents': [], # 'tests': [], # }]) COMPLEX = {",
"return subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid): return nodeid.replace('/', os.path.sep) def",
"expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated =",
"self.assertEqual(result, expected) def test_discover_not_found(self): projroot, testroot = resolve_testroot('notests') out =",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'),",
"{'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'), }, ],",
"'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'),",
"['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1',",
"###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid':",
"'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name':",
"kwargs kwds = {} argv = [sys.executable, SCRIPT, cmd, tool,",
"'pytest', '--rootdir', projroot, testroot) result = json.loads(out) self.maxDiff = None",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source':",
"{'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'), }, #",
"'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'), }, #####",
"def test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex') expected = self.complex(projroot) #",
"kwds = {} argv = [sys.executable, SCRIPT, cmd, tool, '--']",
"{'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, ####",
"'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests', 'parentid':",
"tool, *cliargs): try: return _run_adapter(cmd, tool, *cliargs) except subprocess.CalledProcessError: #",
"'name': 'test_foo.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_mixed.py'), 'kind':",
"'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'),",
"'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"{'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'),",
"'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name':",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), },",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source':",
"'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'),",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source':",
"_run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio', True) assert not",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid':",
"## +++ {'id': fix_path('./tests/w/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/w'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid':",
"# +++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'),",
"fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid':",
"'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name':",
"fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [],",
"'name': 'b', 'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers':",
"#### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/x/y/z'),",
"unicode_literals import json import os import os.path import subprocess import",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers':",
"fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat', 'parentid':",
"fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2',",
"'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'), }, #####",
"'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, #### +++ {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"{'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'),",
"fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py', 'parentid': '.', }) expected[0]['tests'] =",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name': 'test_param_33_ids[v2]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid':",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name':",
"[], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'), }, ########### {'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source':",
"fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b', 'parentid':",
"'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name':",
"@pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self, testroot): results = COMPLEX.copy() results['root']",
"{'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), }, ##",
"assert not kwargs kwds = {} argv = [sys.executable, SCRIPT,",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'),",
"fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), },",
"fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers':",
"fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]',",
"'kind': 'file', 'name': 'test_mixed.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests'), 'kind':",
"fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), },",
"'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name':",
"if not srcfile: srcfile = test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno))",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid':",
"'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name':",
"'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id':",
"result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_not_found(self):",
"fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), },",
"'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind':",
"'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), },",
"'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name':",
"= run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result = json.loads(out) result[0]['tests']",
"'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), 'kind': 'function', 'name':",
"fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py',",
"'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [],",
"fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [],",
"'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'), 'kind': 'folder', 'name': 'v',",
"= os.path.join(DATA_DIR, name) return projroot, os.path.join(projroot, 'tests') def run_adapter(cmd, tool,",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source':",
"fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"{ 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'), 'name': 'tests.test_doctest', 'source': fix_path('./tests/test_doctest.py:1'), 'markers': [], 'parentid':",
"'kind': 'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source':",
"fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped',",
"'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2,",
"'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]', 'source':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'),",
"'kind': 'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind':",
"fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'),",
"'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'),",
"'name': 'test_spam.py', 'parentid': fix_path('./tests'), }, ], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'),",
"fix_path('./tests/test_mixed.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'),",
"if sys.version_info >= (3, 6): return tests fixed = []",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid':",
"'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'),",
"fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), },",
"{'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'),",
"= test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group, key=lambda t: t['id'])) return",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'),",
"'parentid': fix_path('./tests/test_spam.py'), }, ], }]) def test_discover_complex_default(self): projroot, testroot =",
"'.', }, # +++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py',",
"'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name':",
"'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id':",
"'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id':",
"{'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'), }, #####",
"{'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'),",
"fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [],",
"out stdout & stderr this time try: return _run_adapter(cmd, tool,",
"{'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'),",
"{'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'),",
"return fixed def fix_source(tests, testid, srcfile, lineno): testid = fix_path(testid)",
"nodeid.replace('/', os.path.sep) def fix_test_order(tests): if sys.version_info >= (3, 6): return",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id':",
"{'id': fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'), }, #",
"}, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z',",
"test_discover_not_found(self): projroot, testroot = resolve_testroot('notests') out = run_adapter('discover', 'pytest', '--rootdir',",
"'parentid': fix_path('./tests/v'), }, ## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name':",
"'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'),",
"'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name': 'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), },",
"'kind': 'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'), }, # +++ {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'),",
"fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [],",
"'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'),",
"fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [],",
"'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name':",
"fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]',",
"'name': 'TestMySuite', 'parentid': fix_path('./tests/test_mixed.py'), }, # +++ {'id': fix_path('./tests/test_pytest.py'), 'kind':",
"# +++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'),",
"###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers':",
"fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]',",
"'kind': 'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind':",
"'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite',",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers':",
"run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result = json.loads(out) self.maxDiff =",
"fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [],",
"None self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot, _ = resolve_testroot('complex') expected",
"{'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source':",
"'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), },",
"fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), },",
"arg in argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid): return",
"## +++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'),",
"'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite',",
"fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/b'), }, #### +++",
"'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name':",
"fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [],",
"'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple',",
"exc: print(exc.output) def _run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio',",
"fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [],",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure',",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid':",
"[ # {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.',",
"self.assertEqual(result, [{ 'root': projroot, 'rootid': '.', 'parents': [ {'id': fix_path('./tests'),",
"fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), },",
"'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"decorated: fix_source(expected[0]['tests'], testid, None, 0) out = run_adapter('discover', 'pytest', '--rootdir',",
"'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name':",
"'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id':",
"'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'),",
"'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid':",
"'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'),",
"'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"= self.complex(projroot) # add in doctests from test suite expected[0]['parents'].insert(3,",
"fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple',",
"fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'),",
"in doctests from test suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind':",
"add in doctests from non-test module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'),",
"'kind': 'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind':",
"'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers':",
"fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]',",
"{'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self, testroot):",
"{'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'),",
"'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, # +++ {'id': fix_path('./tests/test_pytest_param.py'),",
"fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [],",
"= json.loads(out) self.maxDiff = None self.assertEqual(result, [{ 'root': projroot, 'rootid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'),",
"'source': fix_path('./tests/test_unittest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_2'), 'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'),",
"argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD +",
"result = json.loads(out) self.maxDiff = None self.assertEqual(result, []) # TODO:",
"'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite',",
"{'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), },",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'),",
"non-test module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py',",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z2]'), 'name': 'test_param_23_13[1-1-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), },",
"fix_path('./tests/x/y/z/b'), }, #### +++ {'id': fix_path('./tests/x/y/z/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py',",
"fix_path('./tests/test_pytest.py:140'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]',",
"{'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'),",
"'name': 'mod.py', 'parentid': '.', }) expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'),",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'),",
"'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'),",
"# 'rootid': '.', # 'parents': [], # 'tests': [], #",
"[sys.executable, SCRIPT, cmd, tool, '--'] + list(cliargs) if not hidestdio:",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]',",
"fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'), }, ], }]) def test_discover_complex_default(self):",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'), 'name': 'test_runtime_failed', 'source': fix_path('./tests/test_pytest.py:18'),",
"'function', 'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function',",
"[], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:9'),",
"None, 0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot) result",
"+++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), },",
"'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name':",
"fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'),",
"'--rootdir', projroot, '--doctest-modules', projroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests'])",
"'y', 'parentid': fix_path('./tests/x'), }, #### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name':",
"#### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'), },",
"not kwargs kwds = {} argv = [sys.executable, SCRIPT, cmd,",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name':",
"'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name':",
"fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'),",
"'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'),",
"fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), },",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'),",
"'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_42.py'),",
"result = json.loads(out) self.maxDiff = None self.assertEqual(result, [{ 'root': projroot,",
"'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name':",
"[], # 'tests': [], # }]) COMPLEX = { 'root':",
"fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), },",
"'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name':",
"fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/test_ham.py'), },",
"for arg in argv))) return subprocess.check_output(argv, universal_newlines=True, **kwds) def fix_path(nodeid):",
"'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_spam.py'), }, ], }])",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"t: t['id'])) group = [] curfile = test['id'].partition('.py::')[0] + '.py'",
"[], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'),",
"'--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1]",
"hidestdio=False) except subprocess.CalledProcessError as exc: print(exc.output) def _run_adapter(cmd, tool, *cliargs,",
"'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_failed'),",
"os.path.sep) def fix_test_order(tests): if sys.version_info >= (3, 6): return tests",
"'parentid': fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'), 'kind': 'folder', 'name': 'w',",
"decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in",
"'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id':",
"doctests from non-test module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind': 'file',",
"fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ## {'id':",
"'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'),",
"{'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_mixed.py'), }, # +++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source':",
"= fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_complex_doctest(self): projroot,",
"= subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for arg",
"'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'), 'markers':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'), 'kind': 'function', 'name': 'test_param_13_repeat', 'parentid': fix_path('./tests/test_pytest.py'), },",
"fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker',",
"'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind':",
"fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'),",
"'root': projroot, 'rootid': '.', 'parents': [ {'id': fix_path('./tests'), 'kind': 'folder',",
"+++ {'id': fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), },",
"'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'),",
"fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]',",
"'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers':",
"fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'), },",
"'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id':",
"'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ######",
"fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]',",
"projroot, 'rootid': '.', 'parents': [ {'id': fix_path('./tests'), 'kind': 'folder', 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z1]'), 'name': 'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"{'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'),",
"{'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id':",
"fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]',",
"'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b',",
"'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers':",
"'kind': 'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id':",
"##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a', 'parentid': fix_path('./tests/x/y/z'), },",
"}, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'),",
"'root': projroot, # 'rootid': '.', # 'parents': [], # 'tests':",
"[ {'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers': [], 'parentid':",
"+++ {'id': fix_path('./tests/v/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), },",
"'parents': [ # {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid':",
"'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind':",
"{'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'),",
"'test_pytest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs',",
"'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers':",
"'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'),",
"curfile = None group = [] for test in tests:",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers': [],",
"##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid':",
"'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'), }, ], 'tests': [",
"fixed = [] curfile = None group = [] for",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid':",
"testroot) result = json.loads(out) self.maxDiff = None self.assertEqual(result, [{ 'root':",
"'test_param_23_13[3-4-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'),",
"fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'),",
"'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13',",
"'kind': 'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'),",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'],",
"fix_path('./tests/test_pytest_param.py'), }, # +++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py',",
"fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), },",
"'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/b/test_spam.py'), }, ], }",
"expected) def test_discover_not_found(self): projroot, testroot = resolve_testroot('notests') out = run_adapter('discover',",
"self.complex(projroot) # add in doctests from test suite expected[0]['parents'].insert(3, {",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'),",
"fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'), 'name': 'test_maybe_not_skipped',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source':",
"'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_mark_fixture'), 'name':",
"'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function',",
"fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'), 'name': 'test_param_13_repeat[x0]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), },",
"'kind': 'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'), }, # +++ {'id':",
"'name': 'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers':",
"'test_spam.py', 'parentid': fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'), 'kind': 'folder', 'name':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers':",
"{'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers':",
"'test_simple', 'source': fix_path('./tests/v/spam.py:8'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id':",
"{'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'),",
"}, ] + expected[0]['tests'] expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info <",
"# Re-run pytest but print out stdout & stderr this",
"fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers':",
"fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'), 'markers': [], 'parentid': fix_path('./tests/x/y/z/a/test_spam.py'), },",
"'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++ {'id': fix_path('./tests/test_unittest.py'), 'kind':",
"fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]',",
"'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id':",
"in doctests from non-test module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind':",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'),",
"projroot, testroot = resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests'])",
"'name': 'test_param_11', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13'), 'kind': 'function', 'name':",
"in tests: if (curfile or '???') not in test['id']: fixed.extend(sorted(group,",
"'MyTests', 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite'), 'kind': 'suite', 'name': 'TestMySuite',",
"{'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'),",
"'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id':",
"fix_path('./tests/test_pytest.py:81'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple',",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'),",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [],",
"test['id'].partition('.py::')[0] + '.py' group.append(test) fixed.extend(sorted(group, key=lambda t: t['id'])) return fixed",
"'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, {'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source':",
"{'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'),",
"'markers': [], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source':",
"time try: return _run_adapter(cmd, tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError as",
"# 'parents': [], # 'tests': [], # }]) COMPLEX =",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'),",
"{'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name': 'test_42-43.py', 'parentid': fix_path('./tests'), }, #",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [],",
"# Licensed under the MIT License. from __future__ import unicode_literals",
"tests: if test['id'] == testid: break else: raise KeyError('test {!r}",
"'mod', 'source': fix_path('./mod.py:1'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'),",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"'.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def resolve_testroot(name): projroot = os.path.join(DATA_DIR,",
"testroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None",
"'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple',",
"test in tests: if test['id'] == testid: break else: raise",
"fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [],",
"'kind': 'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind':",
"'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function',",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z1]'), 'name': 'test_param_23_13[0-0-z1]',",
"fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), },",
"expected[0]['tests'] = [ {'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers':",
"fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y', 'parentid':",
"'suite', 'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id': fix_path('./tests/v/test_ham.py'),",
"{'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'),",
"}, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [], 'parentid':",
"in decorated: fix_source(expected[0]['tests'], testid, None, 0) out = run_adapter('discover', 'pytest',",
"'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name':",
"'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name':",
"projroot, '--doctest-modules', projroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff",
"or '???') not in test['id']: fixed.extend(sorted(group, key=lambda t: t['id'])) group",
"break else: raise KeyError('test {!r} not found'.format(testid)) if not srcfile:",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers':",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), },",
"{'id': fix_path('./tests/test_unittest.py::OtherTests::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:61'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::OtherTests'),",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam', 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'),",
"fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'), 'kind': 'folder', 'name': 'v', 'parentid':",
"+++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), },",
"'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id':",
"{'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'),",
"'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source':",
"}, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid':",
"'name': 'test_simple', 'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid':",
"'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name':",
"+++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'), },",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source':",
"{'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, #####",
"'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name':",
"], 'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42-43.py:2'),",
"'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'),",
"def _run_adapter(cmd, tool, *cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio', True) assert",
"[], 'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source':",
"'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'), 'kind':",
"}, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'name': 'test_spam.py', 'parentid': fix_path('./tests/v'), }, ## {'id': fix_path('./tests/w'), 'kind': 'folder',",
"'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'),",
"'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name':",
"'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function',",
"os import os.path import subprocess import sys import unittest import",
"fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), },",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'),",
"(3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid",
"{'id': fix_path('./tests/v/test_eggs.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind': 'function', 'name': 'test_param_11', 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid':",
"fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'),",
"= [ {'id': fix_path('./mod.py::mod'), 'name': 'mod', 'source': fix_path('./mod.py:1'), 'markers': [],",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'),",
"expected = self.complex(projroot) # add in doctests from test suite",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source':",
"}, {'id': fix_path('./mod.py::mod.Spam'), 'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_multiple_markers'), 'name': 'test_multiple_markers',",
"stdout & stderr this time try: return _run_adapter(cmd, tool, *cliargs,",
"'./tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in decorated: fix_source(expected[0]['tests'], testid, None,",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind': 'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), },",
"for test in tests: if test['id'] == testid: break else:",
"suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py', 'parentid':",
"[], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'),",
"pytest from ...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR =",
"'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function',",
"fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers':",
"fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [],",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers':",
"'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_spam.py:2'), 'markers': [],",
"'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'),",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source':",
"fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[3-4-5]'), 'name': 'test_param_33[3-4-5]',",
"fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), },",
"fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'), 'markers': [],",
"'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ###########",
"'source': fix_path('./tests/test_pytest.py:10'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name':",
"= os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py')",
"projroot, testroot = resolve_testroot('simple') out = run_adapter('discover', 'pytest', '--rootdir', projroot,",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers':",
"return projroot, os.path.join(projroot, 'tests') def run_adapter(cmd, tool, *cliargs): try: return",
"'test_param_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers':",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [],",
"return tests fixed = [] curfile = None group =",
"'kind': 'function', 'name': 'test_fixture_param', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01'), 'kind':",
"6): return tests fixed = [] curfile = None group",
"fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned',",
"'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id':",
"tool, '--'] + list(cliargs) if not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr']",
"'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source':",
"os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__), '.data') SCRIPT = os.path.join(TESTING_TOOLS_ROOT, 'run_adapter.py') def",
"'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [],",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'),",
"{'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id':",
"'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_42.py'), 'kind': 'file', 'name':",
"fix_source(tests, testid, srcfile, lineno): testid = fix_path(testid) for test in",
"fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name': 'test_param_11[x0]', 'source': fix_path('./tests/test_pytest.py:108'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [],",
"'kind': 'folder', 'name': 'tests', 'parentid': '.', }, # +++ {'id':",
"{'id': fix_path('./tests/test_unittest.py'), 'kind': 'file', 'name': 'test_unittest.py', 'parentid': fix_path('./tests'), }, {'id':",
"'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name':",
"fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y', 'parentid': fix_path('./tests/x'), }, #### {'id':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [],",
"'test_mark_fixture', 'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'),",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'), 'markers': [],",
"= self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated",
"fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name':",
"'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'),",
"fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers':",
"this time try: return _run_adapter(cmd, tool, *cliargs, hidestdio=False) except subprocess.CalledProcessError",
"'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises'), 'kind': 'function', 'name': 'test_param_23_raises',",
"'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name': 'TestParamAll',",
"}, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'), },",
"fix_path('./tests'), }, ], 'tests': [ {'id': fix_path('./tests/test_spam.py::test_simple'), 'name': 'test_simple', 'source':",
"'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder',",
"testid, None, 0) out = run_adapter('discover', 'pytest', '--rootdir', projroot, testroot)",
"'name': 'mod.Spam', 'source': fix_path('./mod.py:33'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id':",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [],",
"'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, # +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file',",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'),",
"'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id':",
"'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'),",
"'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name':",
"'parentid': fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/b/test_spam.py'), 'kind': 'file', 'name':",
"'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind': 'suite',",
"}]) COMPLEX = { 'root': None, 'rootid': '.', 'parents': [",
"fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'), }, ], 'tests':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_pytest.py:36'), 'markers': ['expected-failure'],",
"'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers':",
"[], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'),",
"'source': fix_path('./tests/test_pytest.py:103'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_01'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11[x0]'), 'name':",
"but print out stdout & stderr this time try: return",
"fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]',",
"+++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py', 'parentid': fix_path('./tests'), },",
"'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'), }, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind':",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]',",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'),",
"'.', }, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests'),",
"'kind': 'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'), }, # +++ {'id':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid':",
"'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll'), 'kind': 'suite', 'name':",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers':",
"'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, #",
"##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source':",
"fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]',",
"}, ########### {'id': fix_path('./tests/w/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam.py:4'), 'markers': [],",
"fix_path('./tests/test_doctest.py'), 'kind': 'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, {",
"'kind': 'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'), 'kind':",
"'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'), }, ##### {'id':",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [],",
"'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_skipped'), 'name':",
"fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [],",
"'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests'), 'kind': 'suite', 'name': 'MyTests', 'parentid':",
"fix_path('./tests/test_doctest.py'), }) # add in doctests from non-test module expected[0]['parents'].insert(0,",
"'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v2]'), 'name':",
"add in doctests from test suite expected[0]['parents'].insert(3, { 'id': fix_path('./tests/test_doctest.py'),",
"'kind': 'function', 'name': 'test_param_23_raises', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind':",
"fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid':",
"results = COMPLEX.copy() results['root'] = testroot return [results] def test_discover_simple(self):",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:175'),",
"}, #### {'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'),",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the",
"{'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestEggs'),",
"'parentid': fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y',",
"fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'), }, ###### {'id': fix_path('./tests/v/test_spam.py::test_simple'), 'name':",
"COMPLEX.copy() results['root'] = testroot return [results] def test_discover_simple(self): projroot, testroot",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py'), }, # +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py',",
"'rootid': '.', 'parents': [ # {'id': fix_path('./tests'), 'kind': 'folder', 'name':",
"fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"= { 'root': None, 'rootid': '.', 'parents': [ # {'id':",
"##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid': fix_path('./tests/x/y/z/a'),",
"'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name': 'test_fixture_param[eggs]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers':",
"[], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source':",
"# 'root': projroot, # 'rootid': '.', # 'parents': [], #",
"fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]',",
"from ...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR = os.path.join(os.path.dirname(__file__),",
"}, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped'), 'kind': 'function', 'name': 'test_param_13_skipped', 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'), 'name': 'test_param_13_markers[???]', 'source': fix_path('./tests/test_pytest.py:140'),",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), },",
"= json.loads(out) self.maxDiff = None self.assertEqual(result, []) # TODO: Expect",
"fix_path('./tests/test_spam.py'), }, ], }]) def test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex')",
"{'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'),",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam', 'parentid': fix_path('./tests/test_pytest.py'), },",
"'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'),",
"projroot, testroot) result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff =",
"}, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name': 'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), },",
"'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[???]'),",
"'test_param_13_skipped[x2]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'),",
"fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1.0-None]'), 'name': 'test_param_23_raises[1.0-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [],",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'),",
"fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), },",
"resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info <",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source':",
"'kind': 'folder', 'name': 'v', 'parentid': fix_path('./tests'), }, ## +++ {'id':",
"= [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in decorated:",
"hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD",
"'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_foo.py'), 'kind':",
"{'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'),",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]',",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x1]'), 'name': 'test_param_fixture[x1]', 'source':",
"SCRIPT, cmd, tool, '--'] + list(cliargs) if not hidestdio: argv.insert(4,",
"'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name':",
"fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"[{ 'root': projroot, 'rootid': '.', 'parents': [ {'id': fix_path('./tests'), 'kind':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name': 'test_param_33[1-1-1]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source':",
"True) assert not kwargs kwds = {} argv = [sys.executable,",
"'test_param_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), 'kind': 'function', 'name': 'test_param_mark_fixture',",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]', 'source': fix_path('./tests/test_pytest.py:134'),",
"fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat'),",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid':",
"fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name': 'test_param_13[x2]',",
"result = json.loads(out) result[0]['tests'] = fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result,",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x2]'), 'name': 'test_param_fixture[x2]', 'source':",
"'source': fix_path('./tests/test_pytest_param.py:8'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x2]'), 'name':",
"['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_mixed.py:16'),",
"'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:93'), 'markers':",
"'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x1]'),",
"fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name': 'test_param_33_ids[v3]',",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_pytest.py:73'),",
"fix_path('./tests/test_pytest.py::test_fixture_param'), }, ###### {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:8'), 'markers':",
"fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'), },",
"'name': 'TestSimple', 'parentid': fix_path('./tests/v/test_eggs.py'), }, ## +++ {'id': fix_path('./tests/v/test_ham.py'), 'kind':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_pytest.py:10'), 'markers': [],",
"}, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), },",
"'parentid': '.', }, {'id': fix_path('./tests/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py', 'parentid':",
"{'id': fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), }, ##",
"'markers': [], 'parentid': fix_path('./tests/test_spam.py'), }, ], }]) def test_discover_complex_default(self): projroot,",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers': ['expected-failure'], 'parentid':",
"'TestEggs', 'parentid': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param'), 'kind': 'function', 'name': 'test_fixture_param',",
"'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"{'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x2]'), 'name': 'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source':",
"}, {'id': fix_path('./tests/test_pytest_param.py::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), },",
"{'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'),",
"fix_path('./tests/test_unittest.py:9'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside',",
"fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[2-catch2]'), 'name': 'test_param_23_raises[2-catch2]',",
"fix_path('./tests/v/test_eggs.py'), 'kind': 'file', 'name': 'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'),",
"'name': 'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'],",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name': 'TestSpam',",
"'test_simple', 'source': fix_path('./tests/test_mixed.py:16'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py::TestMySuite'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_simple'),",
"fix_path('./tests/test_pytest.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:175'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), },",
"fix_path('./tests/test_mixed.py:9'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::TestMySuite::test_simple'), 'name': 'test_simple',",
"'source': fix_path('./tests/test_pytest.py:18'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name':",
"[], 'parentid': fix_path('./tests/v/test_eggs.py::TestSimple'), }, ###### {'id': fix_path('./tests/v/test_ham.py::test_simple'), 'name': 'test_simple', 'source':",
"[ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped', ] for testid in decorated: fix_source(expected[0]['tests'],",
"'test_param_13[x1]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'),",
"[], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:8'),",
"fix_test_order(result[0]['tests']) self.maxDiff = None self.assertEqual(result, expected) def test_discover_not_found(self): projroot, testroot",
"fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'), 'name': 'test_with_nested_subtests', 'source': fix_path('./tests/test_unittest.py:46'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), },",
"'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'),",
"fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder', 'name': 'a', 'parentid':",
"'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'), }, ]",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name': 'test_param_fixture[x0]', 'source':",
"fix_path('./tests/test_mixed.py::MyTests'), }, {'id': fix_path('./tests/test_mixed.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_mixed.py:25'), 'markers': ['skip'],",
"fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'), }, ##### {'id': fix_path('./tests/test_foo.py::test_simple'), 'name':",
"'file', 'name': 'test_doctest.py', 'parentid': fix_path('./tests'), }) expected[0]['tests'].insert(2, { 'id': fix_path('./tests/test_doctest.py::tests.test_doctest'),",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest.py:178'),",
"['skip'], 'parentid': fix_path('./tests/test_mixed.py::MyTests'), }, ##### {'id': fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source':",
"fixed.extend(sorted(group, key=lambda t: t['id'])) return fixed def fix_source(tests, testid, srcfile,",
"'.', # 'parents': [], # 'tests': [], # }]) COMPLEX",
"Corporation. All rights reserved. # Licensed under the MIT License.",
"fix_path('./tests/test_pytest.py::test_param_mark_fixture[x2]'), 'name': 'test_param_mark_fixture[x2]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), },",
"fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid': '.', }, # +++",
"fix_path('./tests/v/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), },",
"'suite', 'name': 'TestParamAll', 'parentid': fix_path('./tests/test_pytest_param.py'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), 'kind': 'function',",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_subtests'), 'name': 'test_with_subtests', 'source': fix_path('./tests/test_unittest.py:41'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid':",
"'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids'), 'kind': 'function', 'name': 'test_param_33_ids',",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid':",
"'parentid': fix_path('./tests/x/y/z/test_ham.py'), }, ###### {'id': fix_path('./tests/x/y/z/a/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/a/test_spam.py:11'),",
"'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"'name': 'test_param_mark_fixture', 'parentid': fix_path('./tests/test_pytest.py'), }, # +++ {'id': fix_path('./tests/test_pytest_param.py'), 'kind':",
"'test_eggs.py', 'parentid': fix_path('./tests/v'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple'), 'kind': 'suite', 'name': 'TestSimple',",
"## {'id': fix_path('./tests/x'), 'kind': 'folder', 'name': 'x', 'parentid': fix_path('./tests'), },",
"'kind': 'function', 'name': 'test_param_13_skipped', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind':",
"fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v1]'), 'name': 'test_param_33_ids[v1]', 'source': fix_path('./tests/test_pytest.py:128'), 'markers': [],",
"fix_path('./tests/x/y/z/a/test_spam.py'), }, {'id': fix_path('./tests/x/y/z/b/test_spam.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/b/test_spam.py:7'), 'markers': [],",
"fix_path('./tests/test_foo.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'), },",
"fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'), }, {'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square',",
"fix_path('./tests/test_foo.py'), 'kind': 'file', 'name': 'test_foo.py', 'parentid': fix_path('./tests'), }, # +++",
"fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id': fix_path('./tests/v/test_spam.py::test_simpler'), 'name': 'test_simpler',",
"'name': 'test_multiple_markers', 'source': fix_path('./tests/test_pytest.py:51'), 'markers': ['expected-failure', 'skip', 'skip-if'], 'parentid': fix_path('./tests/test_pytest.py'),",
"'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_foo.py'),",
"{'id': fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'),",
"expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind': 'file', 'name': 'mod.py', 'parentid': '.',",
"'name': 'MyTests', 'parentid': fix_path('./tests/test_unittest.py'), }, {'id': fix_path('./tests/test_unittest.py::OtherTests'), 'kind': 'suite', 'name':",
"import pytest from ...__main__ import TESTING_TOOLS_ROOT CWD = os.getcwd() DATA_DIR",
"], }]) def test_discover_complex_default(self): projroot, testroot = resolve_testroot('complex') expected =",
"'OtherTests', 'parentid': fix_path('./tests/test_unittest.py'), }, ## {'id': fix_path('./tests/v'), 'kind': 'folder', 'name':",
"'tests': [], # }]) COMPLEX = { 'root': None, 'rootid':",
"}, ##### {'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [],",
"'test_warned', 'source': fix_path('./tests/test_pytest.py:41'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'),",
"[], 'parentid': fix_path('./tests/test_pytest_param.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::test_param_13[x1]'), 'name': 'test_param_13[x1]', 'source': fix_path('./tests/test_pytest_param.py:8'),",
"'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name':",
"def fix_path(nodeid): return nodeid.replace('/', os.path.sep) def fix_test_order(tests): if sys.version_info >=",
"'source': fix_path('./tests/test_unittest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name':",
"self.maxDiff = None self.assertEqual(result, [{ 'root': projroot, 'rootid': '.', 'parents':",
"}, ## +++ {'id': fix_path('./tests/w/test_spam_ex.py'), 'kind': 'file', 'name': 'test_spam_ex.py', 'parentid':",
"['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_warned'), 'name': 'test_warned', 'source': fix_path('./tests/test_pytest.py:41'),",
"'test_param_13', 'parentid': fix_path('./tests/test_pytest_param.py'), }, # +++ {'id': fix_path('./tests/test_unittest.py'), 'kind': 'file',",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"def complex(self, testroot): results = COMPLEX.copy() results['root'] = testroot return",
"'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'), 'name':",
"fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_42.py:2'), 'markers': [], 'parentid': fix_path('./tests/test_42.py'), },",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13', 'parentid':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers':",
"'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'),",
"fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_eggs.py'), }, {'id': fix_path('./tests/v/test_eggs.py::TestSimple::test_simple'), 'name': 'test_simple',",
"Re-run pytest but print out stdout & stderr this time",
"tool, *cliargs, **kwargs): hidestdio = kwargs.pop('hidestdio', True) assert not kwargs",
"'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name': 'test_param_fixture',",
"group.append(test) fixed.extend(sorted(group, key=lambda t: t['id'])) return fixed def fix_source(tests, testid,",
"}, ### {'id': fix_path('./tests/x/y'), 'kind': 'folder', 'name': 'y', 'parentid': fix_path('./tests/x'),",
"from non-test module expected[0]['parents'].insert(0, { 'id': fix_path('./mod.py'), 'kind': 'file', 'name':",
"'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[x0]'), 'name': 'test_param_13_markers[x0]', 'source': fix_path('./tests/test_pytest.py:140'), 'markers':",
"== testid: break else: raise KeyError('test {!r} not found'.format(testid)) if",
">= (3, 6): return tests fixed = [] curfile =",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x0]'), 'name': 'test_param_mark_fixture[x0]', 'source': fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid':",
"'kind': 'file', 'name': 'test_spam_ex.py', 'parentid': fix_path('./tests/w'), }, ## {'id': fix_path('./tests/x'),",
"}, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/x/y/z/test_ham.py:2'), 'markers': [],",
"import sys import unittest import pytest from ...__main__ import TESTING_TOOLS_ROOT",
"'name': 'test_param_33_ids', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture'), 'kind': 'function', 'name':",
"}, ##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'),",
"fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'), 'name': 'test_top_level', 'source': fix_path('./tests/test_mixed.py:5'), 'markers':",
"'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'),",
"}, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [],",
"{'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x1]'), 'name': 'test_param_13_skipped[x1]', 'source': fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid':",
"lineno): testid = fix_path(testid) for test in tests: if test['id']",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name':",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source':",
"'parentid': '.', }, # +++ {'id': fix_path('./tests/test_42-43.py'), 'kind': 'file', 'name':",
"'name': 'TestEggs', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name':",
"'kind': 'folder', 'name': 'w', 'parentid': fix_path('./tests'), }, ## +++ {'id':",
"{'id': fix_path('./tests/x/y/z'), 'kind': 'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'), }, #####",
"'name': 'test_param_33[3-4-5]', 'source': fix_path('./tests/test_pytest.py:123'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id':",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers'), 'kind': 'function', 'name': 'test_param_13_markers', 'parentid':",
"fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name':",
"json.loads(out) self.maxDiff = None self.assertEqual(result, []) # TODO: Expect the",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll'), }, {'id':",
"**kwargs): hidestdio = kwargs.pop('hidestdio', True) assert not kwargs kwds =",
"'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped', 'source':",
"fix_path('./tests/w/test_spam_ex.py:4'), 'markers': [], 'parentid': fix_path('./tests/w/test_spam_ex.py'), }, ########### {'id': fix_path('./tests/x/y/z/test_ham.py::test_simple'), 'name':",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_failure'), 'name': 'test_failure', 'source': fix_path('./tests/test_unittest.py:34'), 'markers': [], 'parentid':",
"'kind': 'file', 'name': 'test_doctest.txt', 'parentid': fix_path('./tests'), }, # +++ {'id':",
"'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x0]'),",
"'test_param_13_repeat[x2]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[1-1-1]'),",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z0]'), 'name': 'test_param_23_13[1-1-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"'name': 'test_spam_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam'), 'kind': 'suite', 'name':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x2]'), 'name': 'test_spam_13[x2]', 'source': fix_path('./tests/test_pytest.py:178'),",
"def test_discover_simple(self): projroot, testroot = resolve_testroot('simple') out = run_adapter('discover', 'pytest',",
"{'id': fix_path('./tests/test_doctest.txt::test_doctest.txt'), 'name': 'test_doctest.txt', 'source': fix_path('./tests/test_doctest.txt:1'), 'markers': [], 'parentid': fix_path('./tests/test_doctest.txt'),",
"'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source':",
"'TestParam', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), 'kind': 'function', 'name': 'test_param_13',",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_custom_marker'), 'name': 'test_custom_marker', 'source': fix_path('./tests/test_pytest.py:46'),",
"fix_path('./tests/test_mixed.py:5'), 'markers': [], 'parentid': fix_path('./tests/test_mixed.py'), }, {'id': fix_path('./tests/test_mixed.py::test_skipped'), 'name': 'test_skipped',",
"fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), },",
"testroot): results = COMPLEX.copy() results['root'] = testroot return [results] def",
"fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'), 'name': 'test_maybe_skipped',",
"fix_path('./tests/test_pytest.py::test_runtime_skipped'), 'name': 'test_runtime_skipped', 'source': fix_path('./tests/test_pytest.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"fix_path('./tests/test_pytest.py::TestParam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), },",
"pytest but print out stdout & stderr this time try:",
"}) # add in doctests from non-test module expected[0]['parents'].insert(0, {",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source':",
"'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id':",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'),",
"'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_not_skipped'),",
"fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped_inside'), 'name': 'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [],",
"##### {'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'), },",
"'name': 'test_simple', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, {'id':",
"fix_path('./tests/test_pytest_param.py'), 'kind': 'file', 'name': 'test_pytest_param.py', 'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll'),",
"fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]', 'source': fix_path('./tests/test_pytest.py:155'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_raises'), },",
"'test_skipped', 'source': fix_path('./tests/test_pytest.py:26'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_maybe_skipped'),",
"testid, srcfile, lineno): testid = fix_path(testid) for test in tests:",
"if test['id'] == testid: break else: raise KeyError('test {!r} not",
"fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13[x0]'), 'name': 'test_spam_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:17'), 'markers': [],",
"'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name':",
"import unittest import pytest from ...__main__ import TESTING_TOOLS_ROOT CWD =",
"'parentid': fix_path('./tests'), }, {'id': fix_path('./tests/test_pytest.py::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid':",
"'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_fixture_param'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[eggs]'), 'name':",
"'test_doctest.txt', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_foo.py'), 'kind': 'file',",
"## {'id': fix_path('./tests/v'), 'kind': 'folder', 'name': 'v', 'parentid': fix_path('./tests'), },",
"kwds['stderr'] = subprocess.STDOUT argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for",
"'test_simpler', 'source': fix_path('./tests/v/test_spam.py:4'), 'markers': [], 'parentid': fix_path('./tests/v/test_spam.py'), }, ########### {'id':",
"All rights reserved. # Licensed under the MIT License. from",
"}, # +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt', 'parentid':",
"[], 'parentid': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13[x1]'), 'name': 'test_spam_13[x1]', 'source': fix_path('./tests/test_pytest.py:178'),",
"fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), },",
"{'id': fix_path('./tests/v/test_ham.py::test_not_hard'), 'name': 'test_not_hard', 'source': fix_path('./tests/v/spam.py:2'), 'markers': [], 'parentid': fix_path('./tests/v/test_ham.py'),",
"'source': fix_path('./tests/test_pytest.py:128'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_33_ids'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33_ids[v3]'), 'name':",
"'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_skipped'), 'name': 'test_skipped', 'source': fix_path('./tests/test_unittest.py:9'), 'markers':",
"}, # +++ {'id': fix_path('./tests/test_pytest.py'), 'kind': 'file', 'name': 'test_pytest.py', 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source': fix_path('./tests/test_pytest.py:216'), 'markers': [], 'parentid':",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z2]'), 'name': 'test_param_23_13[0-0-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"srcfile: srcfile = test['source'].rpartition(':')[0] test['source'] = fix_path('{}:{}'.format(srcfile, lineno)) @pytest.mark.functional class",
"fix_path('./tests/test_pytest.py:164'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam'), }, {'id': fix_path('./tests/test_pytest.py::TestParam::test_param_13[x0]'), 'name': 'test_param_13[x0]',",
"'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:81'), 'markers':",
"[], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_raises'), 'name': 'test_raises', 'source': fix_path('./tests/test_pytest.py:22'),",
"fix_path('./tests/test_pytest.py::test_fixture'), 'name': 'test_fixture', 'source': fix_path('./tests/test_pytest.py:192'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"testroot = resolve_testroot('complex') expected = self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_fixture_param[spam]'), 'name': 'test_fixture_param[spam]', 'source':",
"fix_path('./tests/v/test_ham.py'), 'kind': 'file', 'name': 'test_ham.py', 'parentid': fix_path('./tests/v'), }, ## +++",
"'kind': 'function', 'name': 'test_param_01', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_11'), 'kind':",
"lineno)) @pytest.mark.functional class PytestTests(unittest.TestCase): def complex(self, testroot): results = COMPLEX.copy()",
"fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z2]'), 'name': 'test_param_23_13[3-4-z2]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [],",
"'source': fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name':",
"'folder', 'name': 'z', 'parentid': fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind':",
"self.complex(projroot) expected[0]['tests'] = fix_test_order(expected[0]['tests']) if sys.version_info < (3,): decorated =",
"'name': 'test_42.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind':",
"'file', 'name': 'test_42.py', 'parentid': fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_doctest.txt'),",
"{'id': fix_path('./tests/x/y/z/b'), 'kind': 'folder', 'name': 'b', 'parentid': fix_path('./tests/x/y/z'), }, #####",
"}, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[1-1-z1]'), 'name': 'test_param_23_13[1-1-z1]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid':",
"}, ], 'tests': [ ########## {'id': fix_path('./tests/test_42-43.py::test_simple'), 'name': 'test_simple', 'source':",
"'name': 'x', 'parentid': fix_path('./tests'), }, ### {'id': fix_path('./tests/x/y'), 'kind': 'folder',",
"'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'), }, {'id':",
"Licensed under the MIT License. from __future__ import unicode_literals import",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13'), 'kind': 'function', 'name': 'test_param_23_13', 'parentid': fix_path('./tests/test_pytest.py'),",
"argv.append('--cache-clear') print('running {!r}'.format(' '.join(arg.rpartition(CWD + '/')[-1] for arg in argv)))",
"'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id': fix_path('./tests/test_mixed.py::test_top_level'),",
"fix_path('./tests/test_pytest.py:31'), 'markers': ['skip-if'], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_known_failure'), 'name': 'test_known_failure',",
"'test_param_13', 'parentid': fix_path('./tests/test_pytest.py::TestParamAll'), }, {'id': fix_path('./tests/test_pytest.py::TestParamAll::test_spam_13'), 'kind': 'function', 'name': 'test_spam_13',",
"{'id': fix_path('./mod.py::mod.square'), 'name': 'mod.square', 'source': fix_path('./mod.py:18'), 'markers': [], 'parentid': fix_path('./mod.py'),",
"'test_dynamic_2', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'),",
"{'id': fix_path('./tests/test_pytest.py::test_param_33'), 'kind': 'function', 'name': 'test_param_33', 'parentid': fix_path('./tests/test_pytest.py'), }, {'id':",
"fix_path('./tests/test_pytest.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:6'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), },",
"'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam::TestEggs'), 'kind': 'suite', 'name': 'TestEggs', 'parentid':",
"+ list(cliargs) if not hidestdio: argv.insert(4, '--no-hide-stdio') kwds['stderr'] = subprocess.STDOUT",
"fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest.py:113'), 'markers': [],",
"['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_markers[2]'), 'name': 'test_param_13_markers[2]', 'source': fix_path('./tests/test_pytest.py:140'),",
"[] curfile = None group = [] for test in",
"'markers': [], 'parentid': fix_path('./tests/test_42-43.py'), }, ##### {'id': fix_path('./tests/test_42.py::test_simple'), 'name': 'test_simple',",
"'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestParam'), 'kind': 'suite', 'name': 'TestParam', 'parentid':",
"'name': 'z', 'parentid': fix_path('./tests/x/y'), }, ##### {'id': fix_path('./tests/x/y/z/a'), 'kind': 'folder',",
"in tests: if test['id'] == testid: break else: raise KeyError('test",
"fix_path('./tests/test_pytest.py:62'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_3'), 'name': 'test_dynamic_3',",
"'source': fix_path('./tests/test_pytest.py:70'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestSpam'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_skipped'), 'name':",
"fix_path('./tests/test_pytest.py:113'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x1]'), 'name': 'test_param_13[x1]',",
"}, {'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x2]'), 'name': 'test_param_13[x2]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid':",
"{'id': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest_param.py:14'), 'markers': [], 'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_param_13'),",
"'test_skipped_inside', 'source': fix_path('./tests/test_unittest.py:21'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_with_nested_subtests'),",
"'parentid': fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers':",
"if sys.version_info < (3,): decorated = [ './tests/test_unittest.py::MyTests::test_skipped', './tests/test_unittest.py::MyTests::test_maybe_skipped', './tests/test_unittest.py::MyTests::test_maybe_not_skipped',",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::TestHam'), 'kind': 'suite', 'name': 'TestHam', 'parentid': fix_path('./tests/test_pytest.py::TestSpam'),",
"'parentid': fix_path('./tests/test_pytest_param.py::TestParamAll::test_spam_13'), }, ###### {'id': fix_path('./tests/test_unittest.py::MyTests::test_dynamic_'), 'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'),",
"fix_path('./tests/test_pytest.py::test_param_23_13[0-0-z0]'), 'name': 'test_param_23_13[0-0-z0]', 'source': fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), },",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_dynamic_1'), 'name': 'test_dynamic_1', 'source': fix_path('./tests/test_pytest.py:62'), 'markers': [],",
"'name': 'test_param_13[x0]', 'source': fix_path('./tests/test_pytest.py:167'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::TestParam::test_param_13'), }, {'id':",
"fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::TestSpam::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/test_pytest.py:70'), 'markers': [],",
"in test['id']: fixed.extend(sorted(group, key=lambda t: t['id'])) group = [] curfile",
"'markers': ['expected-failure'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_markers'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x0]'), 'name': 'test_param_13_skipped[x0]', 'source':",
"'source': fix_path('./tests/test_pytest.py:196'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py'), }, {'id': fix_path('./tests/test_pytest.py::test_param_fixture[x0]'), 'name':",
"fix_path('./tests/test_pytest.py:207'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_mark_fixture'), }, {'id': fix_path('./tests/test_pytest.py::test_param_mark_fixture[x1]'), 'name': 'test_param_mark_fixture[x1]',",
"'pytest', '--rootdir', projroot, '--doctest-modules', projroot) result = json.loads(out) result[0]['tests'] =",
"'name': 'test_dynamic_', 'source': fix_path('./tests/test_unittest.py:54'), 'markers': [], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id':",
"fix_path('./mod.py::mod.Spam.eggs'), 'name': 'mod.Spam.eggs', 'source': fix_path('./mod.py:43'), 'markers': [], 'parentid': fix_path('./mod.py'), },",
"fix_path('./tests'), }, # +++ {'id': fix_path('./tests/test_doctest.txt'), 'kind': 'file', 'name': 'test_doctest.txt',",
"{'id': fix_path('./tests/w'), 'kind': 'folder', 'name': 'w', 'parentid': fix_path('./tests'), }, ##",
"fix_path('./tests/test_pytest.py:134'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_23_13'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_13[3-4-z0]'), 'name': 'test_param_23_13[3-4-z0]',",
"fix_path('./tests/test_pytest.py::TestEggs'), }, {'id': fix_path('./tests/test_pytest.py::test_param_01[]'), 'name': 'test_param_01[]', 'source': fix_path('./tests/test_pytest.py:103'), 'markers': [],",
"fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_23_raises[1-None]'), 'name': 'test_param_23_raises[1-None]',",
"}, {'id': fix_path('./tests/test_unittest.py::MyTests::test_known_failure'), 'name': 'test_known_failure', 'source': fix_path('./tests/test_unittest.py:37'), 'markers': [], 'parentid':",
"fix_path('./tests/x/y/z'), }, ##### +++ {'id': fix_path('./tests/x/y/z/a/test_spam.py'), 'kind': 'file', 'name': 'test_spam.py',",
"fix_path('./tests/test_pytest.py::test_param_13_repeat'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_repeat[x1]'), 'name': 'test_param_13_repeat[x1]', 'source': fix_path('./tests/test_pytest.py:118'), 'markers': [],",
"[], 'parentid': fix_path('./tests/test_unittest.py::MyTests'), }, {'id': fix_path('./tests/test_unittest.py::MyTests::test_maybe_skipped'), 'name': 'test_maybe_skipped', 'source': fix_path('./tests/test_unittest.py:13'),",
"'test_simple', 'source': fix_path('./tests/test_foo.py:3'), 'markers': [], 'parentid': fix_path('./tests/test_foo.py'), }, ##### {'id':",
"fix_path('./tests/test_pytest.py:149'), 'markers': ['skip'], 'parentid': fix_path('./tests/test_pytest.py::test_param_13_skipped'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13_skipped[x2]'), 'name': 'test_param_13_skipped[x2]',",
"'name': 'test_param_fixture[x1]', 'source': fix_path('./tests/test_pytest.py:201'), 'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_fixture'), }, {'id':",
"'parentid': fix_path('./tests/w/test_spam.py'), }, {'id': fix_path('./tests/w/test_spam_ex.py::test_simple'), 'name': 'test_simple', 'source': fix_path('./tests/w/test_spam_ex.py:4'), 'markers':",
"[], 'parentid': fix_path('./tests/test_pytest.py::test_param_33'), }, {'id': fix_path('./tests/test_pytest.py::test_param_33[0-0-0]'), 'name': 'test_param_33[0-0-0]', 'source': fix_path('./tests/test_pytest.py:123'),",
"'markers': [], 'parentid': fix_path('./tests/test_pytest.py::test_param_11'), }, {'id': fix_path('./tests/test_pytest.py::test_param_13[x0]'), 'name': 'test_param_13[x0]', 'source':",
"'.', 'parents': [ {'id': fix_path('./tests'), 'kind': 'folder', 'name': 'tests', 'parentid':"
] |
[
"kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1) **2 return kern",
"tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2 = dim_slice(self, points1, points2)",
"as np import tensorflow as tf from .. import util",
"= 0.01 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1,",
"points1, points2 = dim_slice(self, points1, points2) def h(x): # Zhang",
"util.eye(tf.shape(points1)[0]) + 0.1 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else:",
"h(x): # Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet",
"must equal dimension defined by active_dims ''' import numpy as",
"numpy as np import tensorflow as tf from .. import",
"(1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1 - self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale))",
"Wavelet kernel slice allows kernel operation on feature subset active_dims",
"+ 0.1 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise",
"tf.shape(points2)[0]] ) points1, points2 = dim_slice(self, points1, points2) def h(x):",
"hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1 - self.shift)/tf.exp(self.scale)),",
"h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1)",
"def kernel(self, points1, points2=None): if points2 is None: points2 =",
"= active_dims self.white = white def kernel(self, points1, points2=None): if",
"- self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern",
"= tf.einsum('i,j->ij', kern1, kern2) return kern + white_noise def diag_kernel(self,",
"return kern + white_noise def diag_kernel(self, points): def h(x): #",
"active_dims self.white = white def kernel(self, points1, points2=None): if points2",
"#return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points) kern = tf.reduce_prod(h((points -",
"0.01, white=0.01, input_scaling=False): if input_scaling: self.shift = tf.Variable(shift * tf.ones([input_dim]))",
"if points2 is None: points2 = points1 white_noise = (self.white",
"input_dim self.active_dims = active_dims self.white = white def kernel(self, points1,",
"= dim_slice(self, points1, points2) def h(x): # Zhang wavelet #return",
"wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1 - self.shift)/tf.exp(self.scale)), h((points2",
"# Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet #return",
"white=0.01, input_scaling=False): if input_scaling: self.shift = tf.Variable(shift * tf.ones([input_dim])) self.scale",
". import kernel from .kernel_extras import * class WaveletSlice(kernel.Kernel): def",
"tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim self.active_dims",
"kern2 = h((points1 - self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2",
"return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points =",
"from .kernel_extras import * class WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None,",
"tf.shape(points1)[0]])) else: white_noise = 0.01 * self.white * tf.ones( [tf.shape(points1)[0],",
"of feature dimensions to extract input_dim must equal dimension defined",
"from . import kernel from .kernel_extras import * class WaveletSlice(kernel.Kernel):",
"kern1, kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij',",
"= (self.white * util.eye(tf.shape(points1)[0]) + 0.1 * self.white * tf.ones(",
"feature subset active_dims is iterable of feature dimensions to extract",
"allows kernel operation on feature subset active_dims is iterable of",
"np import tensorflow as tf from .. import util from",
"= input_dim self.active_dims = active_dims self.white = white def kernel(self,",
"0.01 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2",
"points): def h(x): # Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican",
"white def kernel(self, points1, points2=None): if points2 is None: points2",
"h((points1 - self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1,",
"equal dimension defined by active_dims ''' import numpy as np",
"self.shift)/tf.exp(self.scale)) , axis=1) **2 return kern + self.white def get_params(self):",
"= tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim self.active_dims = active_dims self.white",
"wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points",
"axis=1) **2 return kern + self.white def get_params(self): return [self.shift,",
"as tf from .. import util from . import kernel",
"points) kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1) **2 return",
"input_scaling=False): if input_scaling: self.shift = tf.Variable(shift * tf.ones([input_dim])) self.scale =",
"feature dimensions to extract input_dim must equal dimension defined by",
"* tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise = 0.01 * self.white",
"kernel slice allows kernel operation on feature subset active_dims is",
"points2=None): if points2 is None: points2 = points1 white_noise =",
"Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2)",
"self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern =",
"- self.shift)/tf.exp(self.scale)) , axis=1) **2 return kern + self.white def",
"white_noise = (self.white * util.eye(tf.shape(points1)[0]) + 0.1 * self.white *",
"= tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim",
"dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim self.active_dims =",
"points1, points2) def h(x): # Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) #",
"hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points) kern =",
"= tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1) **2 return kern +",
"dim_slice(self, points1, points2) def h(x): # Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2)",
"points1, points2=None): if points2 is None: points2 = points1 white_noise",
"kern + white_noise def diag_kernel(self, points): def h(x): # Zhang",
"kern = tf.einsum('i,j->ij', kern1, kern2) return kern + white_noise def",
"**2 return kern + self.white def get_params(self): return [self.shift, self.scale]",
"self.active_dims = active_dims self.white = white def kernel(self, points1, points2=None):",
"self.white = white def kernel(self, points1, points2=None): if points2 is",
"def h(x): # Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat",
".kernel_extras import * class WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None, shift=0,",
"class WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None, shift=0, scale = 0.01,",
"''' import numpy as np import tensorflow as tf from",
"self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim self.active_dims = active_dims",
"= dim_slice_diag(self, points) kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1)",
"scale = 0.01, white=0.01, input_scaling=False): if input_scaling: self.shift = tf.Variable(shift",
"* tf.ones([input_dim])) else: self.shift = tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale],",
"[tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise = 0.01 * self.white * tf.ones(",
"kern1, kern2) return kern + white_noise def diag_kernel(self, points): def",
"* tf.ones([input_dim])) self.scale = tf.Variable(scale * tf.ones([input_dim])) else: self.shift =",
"* self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2 =",
"self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2,",
"dim_slice_diag(self, points) kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1) **2",
"(self.white * util.eye(tf.shape(points1)[0]) + 0.1 * self.white * tf.ones( [tf.shape(points1)[0],",
"tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise = 0.01 * self.white *",
"iterable of feature dimensions to extract input_dim must equal dimension",
"points1 white_noise = (self.white * util.eye(tf.shape(points1)[0]) + 0.1 * self.white",
"points2 = dim_slice(self, points1, points2) def h(x): # Zhang wavelet",
"kernel operation on feature subset active_dims is iterable of feature",
"input_dim must equal dimension defined by active_dims ''' import numpy",
"points2) def h(x): # Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican",
", axis=1) **2 return kern + self.white def get_params(self): return",
"= h((points1 - self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2 =",
"tensorflow as tf from .. import util from . import",
"import tensorflow as tf from .. import util from .",
"active_dims ''' import numpy as np import tensorflow as tf",
"self.scale = tf.Variable(scale * tf.ones([input_dim])) else: self.shift = tf.Variable([shift], dtype=tf.float32)",
"else: self.shift = tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim",
"if input_scaling: self.shift = tf.Variable(shift * tf.ones([input_dim])) self.scale = tf.Variable(scale",
"white_noise = 0.01 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] )",
"def diag_kernel(self, points): def h(x): # Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2)",
"+ white_noise def diag_kernel(self, points): def h(x): # Zhang wavelet",
"0.1 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise =",
"diag_kernel(self, points): def h(x): # Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) #",
"by active_dims ''' import numpy as np import tensorflow as",
"__init__(self, input_dim, active_dims=None, shift=0, scale = 0.01, white=0.01, input_scaling=False): if",
"* util.eye(tf.shape(points1)[0]) + 0.1 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]]))",
"defined by active_dims ''' import numpy as np import tensorflow",
"= tf.Variable(shift * tf.ones([input_dim])) self.scale = tf.Variable(scale * tf.ones([input_dim])) else:",
"mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points) kern",
"# mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1",
"points = dim_slice_diag(self, points) kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) ,",
"return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1 - self.shift)/tf.exp(self.scale)), h((points2 -",
"util from . import kernel from .kernel_extras import * class",
"import kernel from .kernel_extras import * class WaveletSlice(kernel.Kernel): def __init__(self,",
"wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1,",
"''' Wavelet kernel slice allows kernel operation on feature subset",
"import * class WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None, shift=0, scale",
"kern1, kern2 = h((points1 - self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1,",
"axis=1), tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij', kern1, kern2) return kern",
"tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij', kern1, kern2) return kern +",
"tf.Variable([scale], dtype=tf.float32) self.input_dim = input_dim self.active_dims = active_dims self.white =",
"tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale)) , axis=1) **2 return kern + self.white",
"self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2 = dim_slice(self,",
"def h(x): # Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat",
"tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij', kern1, kern2) return",
"self.input_dim = input_dim self.active_dims = active_dims self.white = white def",
"= points1 white_noise = (self.white * util.eye(tf.shape(points1)[0]) + 0.1 *",
".. import util from . import kernel from .kernel_extras import",
"h(x): # Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet",
"WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None, shift=0, scale = 0.01, white=0.01,",
"= white def kernel(self, points1, points2=None): if points2 is None:",
"import numpy as np import tensorflow as tf from ..",
"# Zhang wavelet #return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet return",
"# mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points)",
"mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 = h((points1 -",
"tf from .. import util from . import kernel from",
"active_dims is iterable of feature dimensions to extract input_dim must",
"* self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise = 0.01",
"dtype=tf.float32) self.input_dim = input_dim self.active_dims = active_dims self.white = white",
"kern2 = tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij', kern1,",
"input_scaling: self.shift = tf.Variable(shift * tf.ones([input_dim])) self.scale = tf.Variable(scale *",
"tf.Variable(scale * tf.ones([input_dim])) else: self.shift = tf.Variable([shift], dtype=tf.float32) self.scale =",
"tf.ones([input_dim])) else: self.shift = tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32)",
"self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points1)[0]])) else: white_noise = 0.01 *",
"#return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2",
"kernel(self, points1, points2=None): if points2 is None: points2 = points1",
"white_noise def diag_kernel(self, points): def h(x): # Zhang wavelet return",
"tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self,",
") points1, points2 = dim_slice(self, points1, points2) def h(x): #",
"None: points2 = points1 white_noise = (self.white * util.eye(tf.shape(points1)[0]) +",
"= tf.reduce_prod(kern1, axis=1), tf.reduce_prod(kern2, axis=1) kern = tf.einsum('i,j->ij', kern1, kern2)",
"input_dim, active_dims=None, shift=0, scale = 0.01, white=0.01, input_scaling=False): if input_scaling:",
"import util from . import kernel from .kernel_extras import *",
"operation on feature subset active_dims is iterable of feature dimensions",
"def __init__(self, input_dim, active_dims=None, shift=0, scale = 0.01, white=0.01, input_scaling=False):",
"on feature subset active_dims is iterable of feature dimensions to",
"points2 = points1 white_noise = (self.white * util.eye(tf.shape(points1)[0]) + 0.1",
"active_dims=None, shift=0, scale = 0.01, white=0.01, input_scaling=False): if input_scaling: self.shift",
"dimension defined by active_dims ''' import numpy as np import",
"tf.Variable(shift * tf.ones([input_dim])) self.scale = tf.Variable(scale * tf.ones([input_dim])) else: self.shift",
"slice allows kernel operation on feature subset active_dims is iterable",
"extract input_dim must equal dimension defined by active_dims ''' import",
"else: white_noise = 0.01 * self.white * tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]]",
"- self.shift)/tf.exp(self.scale)), h((points2 - self.shift)/tf.exp(self.scale)) kern1, kern2 = tf.reduce_prod(kern1, axis=1),",
"= tf.Variable(scale * tf.ones([input_dim])) else: self.shift = tf.Variable([shift], dtype=tf.float32) self.scale",
"Zhang wavelet return tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet #return (1-x**2)*tf.exp(-0.5*x**2)",
"* class WaveletSlice(kernel.Kernel): def __init__(self, input_dim, active_dims=None, shift=0, scale =",
"points2 is None: points2 = points1 white_noise = (self.white *",
"is None: points2 = points1 white_noise = (self.white * util.eye(tf.shape(points1)[0])",
"[tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2 = dim_slice(self, points1, points2) def",
"self.shift = tf.Variable(shift * tf.ones([input_dim])) self.scale = tf.Variable(scale * tf.ones([input_dim]))",
"tf.einsum('i,j->ij', kern1, kern2) return kern + white_noise def diag_kernel(self, points):",
"axis=1) kern = tf.einsum('i,j->ij', kern1, kern2) return kern + white_noise",
"shift=0, scale = 0.01, white=0.01, input_scaling=False): if input_scaling: self.shift =",
"subset active_dims is iterable of feature dimensions to extract input_dim",
"kernel from .kernel_extras import * class WaveletSlice(kernel.Kernel): def __init__(self, input_dim,",
"dimensions to extract input_dim must equal dimension defined by active_dims",
"is iterable of feature dimensions to extract input_dim must equal",
"from .. import util from . import kernel from .kernel_extras",
"tf.ones([input_dim])) self.scale = tf.Variable(scale * tf.ones([input_dim])) else: self.shift = tf.Variable([shift],",
"wavelet #return (1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points) kern = tf.reduce_prod(h((points",
"tf.cos(1.75*x)*tf.exp(-0.5*x**2) # mexican hat wavelet return (1-x**2)*tf.exp(-0.5*x**2) kern1, kern2 =",
"to extract input_dim must equal dimension defined by active_dims '''",
"self.shift = tf.Variable([shift], dtype=tf.float32) self.scale = tf.Variable([scale], dtype=tf.float32) self.input_dim =",
"* tf.ones( [tf.shape(points1)[0], tf.shape(points2)[0]] ) points1, points2 = dim_slice(self, points1,",
"(1-x**2)*tf.exp(-0.5*x**2) points = dim_slice_diag(self, points) kern = tf.reduce_prod(h((points - self.shift)/tf.exp(self.scale))",
"= 0.01, white=0.01, input_scaling=False): if input_scaling: self.shift = tf.Variable(shift *",
"kern2) return kern + white_noise def diag_kernel(self, points): def h(x):"
] |
[
"y_pixels, num_channels = image1.array.shape # represents x, y pixels of",
"image def blur(image, k_size): #k_size is the number of pixels",
"= 'input/'+in_image print('file path: '+thefile) is_file = os.path.isfile(thefile) if not",
"print(quit) quit() path = './input/' is_path = os.path.isdir(path) if not",
"parms # optional args have -- # fixed (required args",
"show city.png # python transform.py blur city.png from image import",
"print(quit) quit() #verify output is writeable is_w = os.access(path, os.W_OK)",
"time.time() # brightened_im = adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') # darkened_im",
"c] * kernel_val new_im.array[x, y, c] = total return new_im",
"0 -2] # [1 0 -1] x_pixels, y_pixels, num_channels =",
"# date: 12/27/20 # cmdline: python transform.py cmd show image='city.png'",
"factor, mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for",
"the blur #k_size=3 would be above and below and left",
"# you must have local input/ and output/ directories #",
"y+neighbor_range)+1): total += image.array[x_i, y_i, c] new_im.array[x,y,c] = total /",
"let's combine two images using the squared sum of squares:",
"not is_w: print('local ./output dir must be writeable, cannot continue...')",
"= combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\" and",
"have --) def arg_init(): parser = argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command",
"= blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total execution duration: {time.time()",
"# sobel_x = apply_kernel(city, np.array([[1, 2, 1], [0, 0, 0],",
"if not is_w: print('local ./output dir must be writeable, cannot",
"sake of simiplicity of this implementation, let's assume that the",
"# blur_15.write_image('blur_k15.png') # let's apply a sobel kernel on the",
"./output dir must exist, cannot continue...') print(quit) quit() #verify output",
"quit() path = './input/' is_path = os.path.isdir(path) if not is_path:",
"total += image.array[x_i, y_i, c] * kernel_val new_im.array[x, y, c]",
"-1]])) # sobel_y.write_image('edge_y.png') # # this will show x and",
"12/27/20 # cmdline: python transform.py cmd show image='city.png' --ulx=1 --uly=2",
"MUST be the same x_pixels, y_pixels, num_channels = image1.array.shape #",
"= image.array * factor -# this is faster return new_im",
"making a new array to copy values to! for x",
"kernel is SQUARE # for example the sobel x kernel",
"return new_im def apply_kernel(image, kernel): # the kernel should be",
"[1, 0, -1]])) # sobel_y.write_image('edge_y.png') # # this will show",
"0 -1] x_pixels, y_pixels, num_channels = image.array.shape # represents x,",
"= x_i + neighbor_range - x y_k = y_i +",
"png images and change images # cmd: python3 transform.py #",
"# brightened_im = adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') # darkened_im =",
"file {in_image} must exist, cannot continue...') print(quit) quit() if imghdr.what(thefile)",
"neighbor_range - x y_k = y_i + neighbor_range - y",
"is faster return new_im #adjust the contrast by increasing difference",
"y edges # sobel_xy = combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if",
"range(x_pixels): for y in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c]",
"neighbors we actually look at (ie for a 3x3 kernel,",
"# [1 0 -1] x_pixels, y_pixels, num_channels = image.array.shape #",
"c]**2)**0.5 return new_im def show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image) imgplot",
"+= image.array[x_i, y_i, c] * kernel_val new_im.array[x, y, c] =",
"-2], [1, 0, -1]])) # sobel_y.write_image('edge_y.png') # # this will",
"blur_15.write_image('blur_k15.png') # let's apply a sobel kernel on the x",
"not is_path: print('local ./output dir must exist, cannot continue...') print(quit)",
"apply_kernel(city, np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]))",
"x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1,",
"-1] x_pixels, y_pixels, num_channels = image.array.shape # represents x, y",
"the squared sum of squares: value = sqrt(value_1**2, value_2**2) #",
"in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] *",
"import imghdr import matplotlib.image as mpimg import matplotlib.pyplot as plt",
"mpimg import matplotlib.pyplot as plt def adjust_brightness(image,factor): #scale each value",
"print('local ./output dir must be writeable, cannot continue...') print(quit) quit()",
"y_pixels,num_channels = im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size //",
"# this will show x and y edges # sobel_xy",
"-1]])) # sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city, np.array([[1, 0, -1],",
"kernel_val = kernel[x_k, y_k] total += image.array[x_i, y_i, c] *",
"new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array",
"# size of image1 and image2 MUST be the same",
"of simiplicity of this implementation, let's assume that the kernel",
"group.add_argument('--v', action='store_true',help=\"add more text output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args =",
"range(y_pixels): for c in range(num_channels): total = 0 for x_i",
"c in range(num_channels): new_im.array[x, y, c] = (image1.array[x, y, c]**2",
"in image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text output\")",
"for the sake of simiplicity of this implementation, let's assume",
"in range(y_pixels): for c in range(num_channels): new_im.array[x, y, c] =",
"-2, -1]])) # sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city, np.array([[1, 0,",
"is_file = os.path.isfile(thefile) if not is_file: print(f'local ./input file {in_image}",
"#non vectorized version #vectorized version # new_im.array = image.array *",
"-2] # [1 0 -1] x_pixels, y_pixels, num_channels = image.array.shape",
"blur(image, k_size): #k_size is the number of pixels to use",
"for y in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] =",
"in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor + mid #non",
"x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i,",
"the sake of simiplicity of this implementation, let's assume that",
"= os.access(path, os.W_OK) if not is_w: print('local ./output dir must",
"args have -- # fixed (required args do not have",
"def cmd(): print(\"routine cmd\") # setup command line args and",
"= (image1.array[x, y, c]**2 + image2.array[x, y, c]**2)**0.5 return new_im",
"image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group",
"a variable that tells us how many neighbors we actually",
"be 1) for x in range(x_pixels): for y in range(y_pixels):",
"blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total execution duration: {time.time() -",
"in range(num_channels): total = 0 for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1,",
"# making a new array to copy values to! neighbor_range",
"is the number of pixels to use when doing the",
"of pixels to use when doing the blur #k_size=3 would",
"adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png')",
"this is a variable that tells us how many neighbors",
"date: 12/27/20 # cmdline: python transform.py cmd show image='city.png' --ulx=1",
"print(\"routine cmd\") # setup command line args and parms #",
"min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i + neighbor_range - x y_k",
"user #defined midpoint def adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels =",
"image name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft",
"for example the sobel x kernel (detecting horizontal edges) is",
"kernel[x_k, y_k] total += image.array[x_i, y_i, c] * kernel_val new_im.array[x,",
"# average for kernel size in image return new_im def",
"def adjust_brightness(image,factor): #scale each value by some amount x_pixels, y_pixels,num_channels",
"return new_im # blur and image def blur(image, k_size): #k_size",
"cmd(): print(\"routine cmd\") # setup command line args and parms",
"= adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake, 0.3)",
"value_2**2) # size of image1 and image2 MUST be the",
"should be a 2D array that represents the kernel we'll",
"y kernel_val = kernel[x_k, y_k] total += image.array[x_i, y_i, c]",
"verify that output/input dirs exist: path = './output/' is_path =",
"blur(city,15) # blur_15.write_image('blur_k15.png') # let's apply a sobel kernel on",
"image return new_im def apply_kernel(image, kernel): # the kernel should",
"you must have local input/ and output/ directories # #",
"this is faster return new_im #adjust the contrast by increasing",
"* factor -# this is faster return new_im #adjust the",
"on the x and y axis # sobel_x = apply_kernel(city,",
"parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group =",
"copy values to! neighbor_range = kernel.shape[0] // 2 # this",
"= parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text output\") group.add_argument('--q', action='store_true',help=\"minimal output\")",
"new_im #adjust the contrast by increasing difference from user #defined",
"print(f'local ./input file {in_image} must exist, cannot continue...') print(quit) quit()",
"image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels): for y",
"= adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3) #",
"would be above and below and left neighbor, right neighbor",
"mid #non vectorized version #vectorized version # new_im.array = (image.array",
"#k_size=3 would be above and below and left neighbor, right",
"// 2 for x in range(x_pixels): for y in range(y_pixels):",
"c in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor + mid",
"not is_path: print('local ./input dir must exist, cannot continue...') print(quit)",
"min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k =",
"be writeable, cannot continue...') print(quit) quit() path = './input/' is_path",
"print(quit) quit() #verify input image if in_image: thefile = 'input/'+in_image",
"# let's combine two images using the squared sum of",
"the kernel should be a 2D array that represents the",
"x in range(x_pixels): for y in range(y_pixels): for c in",
"that represents the kernel we'll use! # for the sake",
"dirs exist: path = './output/' is_path = os.path.isdir(path) if not",
"size in image return new_im def apply_kernel(image, kernel): # the",
"= blur(city,15) # blur_15.write_image('blur_k15.png') # let's apply a sobel kernel",
"- x y_k = y_i + neighbor_range - y kernel_val",
"squares: value = sqrt(value_1**2, value_2**2) # size of image1 and",
"python3 transform.py # you must have local input/ and output/",
"must exist, cannot continue...') print(quit) quit() #verify output is writeable",
"start_time = time.time() # brightened_im = adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png')",
"images using the squared sum of squares: value = sqrt(value_1**2,",
"return new_im def show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image) imgplot =",
"image import Image import numpy as np import time, os,",
"a new array to copy values to! for x in",
"= mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show() # check for necessary",
"import * import imghdr import matplotlib.image as mpimg import matplotlib.pyplot",
"new_im.array = (image.array - mid) * factor + mid return",
"image1.array.shape # represents x, y pixels of image, # channels",
"import matplotlib.image as mpimg import matplotlib.pyplot as plt def adjust_brightness(image,factor):",
"os.path.isdir(path) if not is_path: print('local ./input dir must exist, cannot",
"Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy",
"from image import Image import numpy as np import time,",
"continue...') print(quit) quit() #verify output is writeable is_w = os.access(path,",
"# # this will show x and y edges #",
"pixels. im = Image(filename = image) x_pixels, y_pixels,num_channels = im.array.shape",
"-1] # [2 0 -2] # [1 0 -1] x_pixels,",
"total / (k_size **2) # average for kernel size in",
"is_w = os.access(path, os.W_OK) if not is_w: print('local ./output dir",
"exist: path = './output/' is_path = os.path.isdir(path) if not is_path:",
"'+thefile) is_file = os.path.isfile(thefile) if not is_file: print(f'local ./input file",
"for necessary parts of the runtime environment def check_env( in_image):",
"# darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') #",
"vectorized version #vectorized version # new_im.array = (image.array - mid)",
"(detecting horizontal edges) is as follows: # [1 0 -1]",
"#!/usr/bin/python3 #program to parse png images and change images #",
"[1 0 -1] x_pixels, y_pixels, num_channels = image.array.shape # represents",
"+ image2.array[x, y, c]**2)**0.5 return new_im def show_image(in_image): path=\"input/\" img",
"path: '+thefile) is_file = os.path.isfile(thefile) if not is_file: print(f'local ./input",
"# decr_contrast = adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3 =",
"blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png') # let's apply",
"parts of the runtime environment def check_env( in_image): #check to",
"Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels): for y in range(y_pixels): for",
"and diagonal #neighbor pixels. im = Image(filename = image) x_pixels,",
"city = Image(filename='city.png') start_time = time.time() # brightened_im = adjust_brightness(lake,",
"of this implementation, let's assume that the kernel is SQUARE",
"y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in",
"version #vectorized version # new_im.array = (image.array - mid) *",
"new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size // 2 for x",
"in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i, y_i, c] new_im.array[x,y,c]",
"plt def adjust_brightness(image,factor): #scale each value by some amount x_pixels,",
"version # new_im.array = (image.array - mid) * factor +",
"x_i + neighbor_range - x y_k = y_i + neighbor_range",
"in range(y_pixels): for c in range(num_channels): total = 0 for",
"y_i, c] * kernel_val new_im.array[x, y, c] = total return",
"0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png') #",
"imghdr.what(thefile) != 'png': print('wrong image file type, cannot continue...') print(quit)",
"vectorized version #vectorized version # new_im.array = image.array * factor",
"os.path.isfile(thefile) if not is_file: print(f'local ./input file {in_image} must exist,",
"blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15) #",
"name: <NAME> # date: 12/27/20 # cmdline: python transform.py cmd",
"for c in range(num_channels): total = 0 for x_i in",
"argparse, string #from tkinter import * import imghdr import matplotlib.image",
"numpy as np import time, os, argparse, string #from tkinter",
"us how many neighbors we actually look at (ie for",
"y, c]**2 + image2.array[x, y, c]**2)**0.5 return new_im def show_image(in_image):",
"= os.path.isdir(path) if not is_path: print('local ./output dir must exist,",
"dir must exist, cannot continue...') print(quit) quit() #verify input image",
"neighbor_range = kernel.shape[0] // 2 # this is a variable",
"decr_contrast = adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3)",
"array that represents the kernel we'll use! # for the",
"represents the kernel we'll use! # for the sake of",
"# brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') #",
"to verify that output/input dirs exist: path = './output/' is_path",
"#if args.cmd != \"show\" and args.cmd != \"blur\": return args",
"y, c] = (image1.array[x, y, c]**2 + image2.array[x, y, c]**2)**0.5",
"contrast by increasing difference from user #defined midpoint def adjust_contrast(image,",
"--brx=0 --bry=9 # python transform.py show city.png # python transform.py",
"text output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args = parser.parse_args() print(args.image) #if",
"check for necessary parts of the runtime environment def check_env(",
"+ mid #non vectorized version #vectorized version # new_im.array =",
"os.path.isdir(path) if not is_path: print('local ./output dir must exist, cannot",
"return args #def show_image(filename): if __name__ == '__main__': args =",
"follows: # [1 0 -1] # [2 0 -2] #",
"y_i + neighbor_range - y kernel_val = kernel[x_k, y_k] total",
"# python transform.py blur city.png from image import Image import",
"blur city.png from image import Image import numpy as np",
"+ neighbor_range - x y_k = y_i + neighbor_range -",
"is writeable is_w = os.access(path, os.W_OK) if not is_w: print('local",
"--) def arg_init(): parser = argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to",
"# [1 0 -1] # [2 0 -2] # [1",
"return new_im #adjust the contrast by increasing difference from user",
"y, c]**2)**0.5 return new_im def show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image)",
"number of pixels to use when doing the blur #k_size=3",
"in_image: thefile = 'input/'+in_image print('file path: '+thefile) is_file = os.path.isfile(thefile)",
"is a variable that tells us how many neighbors we",
"if args.cmd == \"blur\" and args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png')",
"sobel_y.write_image('edge_y.png') # # this will show x and y edges",
"tkinter import * import imghdr import matplotlib.image as mpimg import",
"# new_im.array = (image.array - mid) * factor + mid",
"blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png') # let's apply a sobel",
"city.png from image import Image import numpy as np import",
"!= 'png': print('wrong image file type, cannot continue...') print(quit) quit()",
"k_size): #k_size is the number of pixels to use when",
"is SQUARE # for example the sobel x kernel (detecting",
"0 -1] # [2 0 -2] # [1 0 -1]",
"when doing the blur #k_size=3 would be above and below",
"new_im.array[x, y, c] = total return new_im def combine_images(image1, image2):",
"= arg_init() check_env(args.image) lake = Image(filename = 'lake.png') city =",
"-- # fixed (required args do not have --) def",
"continue...') print(quit) quit() def cmd(): print(\"routine cmd\") # setup command",
"x and y axis # sobel_x = apply_kernel(city, np.array([[1, 2,",
"sobel_x = apply_kernel(city, np.array([[1, 2, 1], [0, 0, 0], [-1,",
"brightened_im = adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake,",
"new array to copy values to! for x in range(x_pixels):",
"sobel_xy = combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\"",
"input image if in_image: thefile = 'input/'+in_image print('file path: '+thefile)",
"# sobel_xy = combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd ==",
"x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i",
"= './output/' is_path = os.path.isdir(path) if not is_path: print('local ./output",
"adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake, 0.3) #",
"environment def check_env( in_image): #check to verify that output/input dirs",
"== \"show\" and args.image: show_image(args.image) if args.cmd == \"blur\" and",
"have -- # fixed (required args do not have --)",
"for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i +",
"args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total execution",
"parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input image name for the command\",type=str)",
"import time, os, argparse, string #from tkinter import * import",
"path = './input/' is_path = os.path.isdir(path) if not is_path: print('local",
"as mpimg import matplotlib.pyplot as plt def adjust_brightness(image,factor): #scale each",
"arg_init(): parser = argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str)",
"let's assume that the kernel is SQUARE # for example",
"name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y",
"cmd\") # setup command line args and parms # optional",
"args.cmd != \"show\" and args.cmd != \"blur\": return args #def",
"at (ie for a 3x3 kernel, this value should be",
"range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] * factor",
"and left neighbor, right neighbor pixels, and diagonal #neighbor pixels.",
"same x_pixels, y_pixels, num_channels = image1.array.shape # represents x, y",
"should be 1) for x in range(x_pixels): for y in",
"x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in",
"runtime environment def check_env( in_image): #check to verify that output/input",
"x_pixels, y_pixels, num_channels = image.array.shape # represents x, y pixels",
"#def show_image(filename): if __name__ == '__main__': args = arg_init() check_env(args.image)",
"value by some amount x_pixels, y_pixels,num_channels = image.array.shape new_im =",
"and output/ directories # # name: <NAME> # date: 12/27/20",
"blur and image def blur(image, k_size): #k_size is the number",
"for kernel size in image return new_im def apply_kernel(image, kernel):",
"#verify input image if in_image: thefile = 'input/'+in_image print('file path:",
"to! for x in range(x_pixels): for y in range(y_pixels): for",
"# # name: <NAME> # date: 12/27/20 # cmdline: python",
"the kernel is SQUARE # for example the sobel x",
"the contrast by increasing difference from user #defined midpoint def",
"exist, cannot continue...') print(quit) quit() if imghdr.what(thefile) != 'png': print('wrong",
"Image(filename='city.png') start_time = time.time() # brightened_im = adjust_brightness(lake, 1.7) #",
"= (image.array[x,y,c] -mid)* factor + mid #non vectorized version #vectorized",
"factor + mid return new_im # blur and image def",
"kernel size in image return new_im def apply_kernel(image, kernel): #",
"= total return new_im def combine_images(image1, image2): # let's combine",
"(required args do not have --) def arg_init(): parser =",
"matplotlib.image as mpimg import matplotlib.pyplot as plt def adjust_brightness(image,factor): #scale",
"x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in",
"writeable, cannot continue...') print(quit) quit() path = './input/' is_path =",
"left neighbor, right neighbor pixels, and diagonal #neighbor pixels. im",
"darkened_im = adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake,",
"#non vectorized version #vectorized version # new_im.array = (image.array -",
"# for example the sobel x kernel (detecting horizontal edges)",
"cmdline: python transform.py cmd show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9",
"im = Image(filename = image) x_pixels, y_pixels,num_channels = im.array.shape new_im",
"= './input/' is_path = os.path.isdir(path) if not is_path: print('local ./input",
"= apply_kernel(city, np.array([[1, 2, 1], [0, 0, 0], [-1, -2,",
"channels (R, G, B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) #",
"= (image.array - mid) * factor + mid return new_im",
"min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i, y_i, c] new_im.array[x,y,c] = total",
"new_im.array[x,y,c] = total / (k_size **2) # average for kernel",
"total = 0 for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for",
"neighbor pixels, and diagonal #neighbor pixels. im = Image(filename =",
"kernel, this value should be 1) for x in range(x_pixels):",
"cmd: python3 transform.py # you must have local input/ and",
"the sobel x kernel (detecting horizontal edges) is as follows:",
"# decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15",
"# sobel_y.write_image('edge_y.png') # # this will show x and y",
"#program to parse png images and change images # cmd:",
"Image(filename = image) x_pixels, y_pixels,num_channels = im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels)",
"y, c] = total return new_im def combine_images(image1, image2): #",
"exist, cannot continue...') print(quit) quit() #verify input image if in_image:",
"print('wrong image file type, cannot continue...') print(quit) quit() def cmd():",
"= adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake, 2,0.5)",
"sum of squares: value = sqrt(value_1**2, value_2**2) # size of",
"that the kernel is SQUARE # for example the sobel",
"os, argparse, string #from tkinter import * import imghdr import",
"of image1 and image2 MUST be the same x_pixels, y_pixels,",
"from user #defined midpoint def adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels",
"// 2 # this is a variable that tells us",
"new_im def apply_kernel(image, kernel): # the kernel should be a",
"sobel_y = apply_kernel(city, np.array([[1, 0, -1], [2, 0, -2], [1,",
"we actually look at (ie for a 3x3 kernel, this",
"to use when doing the blur #k_size=3 would be above",
"value should be 1) for x in range(x_pixels): for y",
"combine_images(image1, image2): # let's combine two images using the squared",
"version # new_im.array = image.array * factor -# this is",
"{in_image} must exist, cannot continue...') print(quit) quit() if imghdr.what(thefile) !=",
"range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i + neighbor_range - x",
"* import imghdr import matplotlib.image as mpimg import matplotlib.pyplot as",
"for x in range(x_pixels): for y in range(y_pixels): for c",
"# this is a variable that tells us how many",
"# channels (R, G, B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels)",
"line args and parms # optional args have -- #",
"cannot continue...') print(quit) quit() #verify output is writeable is_w =",
"above and below and left neighbor, right neighbor pixels, and",
"print('local ./input dir must exist, cannot continue...') print(quit) quit() #verify",
"# blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15)",
"setup command line args and parms # optional args have",
"for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range),",
"image file type, cannot continue...') print(quit) quit() def cmd(): print(\"routine",
"command line args and parms # optional args have --",
"G, B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a",
"- y kernel_val = kernel[x_k, y_k] total += image.array[x_i, y_i,",
"command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright",
"y axis # sobel_x = apply_kernel(city, np.array([[1, 2, 1], [0,",
"is_file: print(f'local ./input file {in_image} must exist, cannot continue...') print(quit)",
"dir must be writeable, cannot continue...') print(quit) quit() path =",
"0.3) # darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png')",
"use when doing the blur #k_size=3 would be above and",
"we'll use! # for the sake of simiplicity of this",
"program\",type=str) parser.add_argument(\"image\",help=\"input image name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in",
"time, os, argparse, string #from tkinter import * import imghdr",
"--uly=2 --brx=0 --bry=9 # python transform.py show city.png # python",
"in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] * factor #non vectorized version",
"implementation, let's assume that the kernel is SQUARE # for",
"parser.add_argument(\"image\",help=\"input image name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\")",
"c in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] * factor #non vectorized",
"image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 # python transform.py show city.png",
"range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k",
"and args.cmd != \"blur\": return args #def show_image(filename): if __name__",
"amount x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x",
"* kernel_val new_im.array[x, y, c] = total return new_im def",
"def combine_images(image1, image2): # let's combine two images using the",
"# incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') #",
"= time.time() # brightened_im = adjust_brightness(lake, 1.7) # brightened_im.write_image('brightened.png') #",
"x_pixels, y_pixels, num_channels = image1.array.shape # represents x, y pixels",
"# new_im.array = image.array * factor -# this is faster",
"if not is_path: print('local ./input dir must exist, cannot continue...')",
"x and y edges # sobel_xy = combine_images(sobel_x, sobel_y) #",
"image) x_pixels, y_pixels,num_channels = im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range =",
"0], [-1, -2, -1]])) # sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city,",
"#defined midpoint def adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape",
"in range(x_pixels): for y in range(y_pixels): for c in range(num_channels):",
"def apply_kernel(image, kernel): # the kernel should be a 2D",
"= kernel.shape[0] // 2 # this is a variable that",
"mid) * factor + mid return new_im # blur and",
"have local input/ and output/ directories # # name: <NAME>",
"x_pixels, y_pixels,num_channels = im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size",
"squared sum of squares: value = sqrt(value_1**2, value_2**2) # size",
"a 2D array that represents the kernel we'll use! #",
"show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show() #",
"= adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake, 0.5,0.5)",
"np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])) #",
"many neighbors we actually look at (ie for a 3x3",
"(k_size **2) # average for kernel size in image return",
"in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i + neighbor_range -",
"more text output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args = parser.parse_args() print(args.image)",
"group.add_argument('--q', action='store_true',help=\"minimal output\") args = parser.parse_args() print(args.image) #if args.cmd !=",
"thefile = 'input/'+in_image print('file path: '+thefile) is_file = os.path.isfile(thefile) if",
"1], [0, 0, 0], [-1, -2, -1]])) # sobel_x.write_image('edge_x.png') #",
"range(num_channels): total = 0 for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1):",
"the runtime environment def check_env( in_image): #check to verify that",
"copy values to! for x in range(x_pixels): for y in",
"parser.parse_args() print(args.image) #if args.cmd != \"show\" and args.cmd != \"blur\":",
"a sobel kernel on the x and y axis #",
"range(x_pixels): for y in range(y_pixels): for c in range(num_channels): new_im.array[x,",
"python transform.py cmd show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 #",
"2 # this is a variable that tells us how",
"[2, 0, -2], [1, 0, -1]])) # sobel_y.write_image('edge_y.png') # #",
"brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') # incr_contrast",
"of image, # channels (R, G, B) new_im = Image(x_pixels=x_pixels,",
"the same x_pixels, y_pixels, num_channels = image1.array.shape # represents x,",
"= im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size // 2",
"new_im.array[x,y,c] = image.array[x,y,c] * factor #non vectorized version #vectorized version",
"parse png images and change images # cmd: python3 transform.py",
"apply_kernel(city, np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]))",
"version #vectorized version # new_im.array = image.array * factor -#",
"as np import time, os, argparse, string #from tkinter import",
"in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)*",
"do not have --) def arg_init(): parser = argparse.ArgumentParser(description='Process an",
"to! neighbor_range = kernel.shape[0] // 2 # this is a",
"#k_size is the number of pixels to use when doing",
"output is writeable is_w = os.access(path, os.W_OK) if not is_w:",
"num_channels=num_channels) # making a new array to copy values to!",
"image2.array[x, y, c]**2)**0.5 return new_im def show_image(in_image): path=\"input/\" img =",
"image if in_image: thefile = 'input/'+in_image print('file path: '+thefile) is_file",
"cannot continue...') print(quit) quit() def cmd(): print(\"routine cmd\") # setup",
"plt.show() # check for necessary parts of the runtime environment",
"to parse png images and change images # cmd: python3",
"diagonal #neighbor pixels. im = Image(filename = image) x_pixels, y_pixels,num_channels",
"local input/ and output/ directories # # name: <NAME> #",
"new_im def combine_images(image1, image2): # let's combine two images using",
"of the runtime environment def check_env( in_image): #check to verify",
"2D array that represents the kernel we'll use! # for",
"image.array[x,y,c] * factor #non vectorized version #vectorized version # new_im.array",
"not have --) def arg_init(): parser = argparse.ArgumentParser(description='Process an image.')",
"-# this is faster return new_im #adjust the contrast by",
"/ (k_size **2) # average for kernel size in image",
"# blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png') # let's apply a",
"blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total execution duration:",
"is as follows: # [1 0 -1] # [2 0",
"-1], [2, 0, -2], [1, 0, -1]])) # sobel_y.write_image('edge_y.png') #",
"this implementation, let's assume that the kernel is SQUARE #",
"def show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show()",
"quit() #verify input image if in_image: thefile = 'input/'+in_image print('file",
"mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x",
"that tells us how many neighbors we actually look at",
"!= \"blur\": return args #def show_image(filename): if __name__ == '__main__':",
"some amount x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for",
"# incr_contrast = adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast =",
"(image1.array[x, y, c]**2 + image2.array[x, y, c]**2)**0.5 return new_im def",
"path = './output/' is_path = os.path.isdir(path) if not is_path: print('local",
"optional args have -- # fixed (required args do not",
"import matplotlib.pyplot as plt def adjust_brightness(image,factor): #scale each value by",
"def check_env( in_image): #check to verify that output/input dirs exist:",
"\"show\" and args.cmd != \"blur\": return args #def show_image(filename): if",
"difference from user #defined midpoint def adjust_contrast(image, factor, mid=0.5): x_pixels,",
"for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i, y_i,",
"parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args",
"quit() def cmd(): print(\"routine cmd\") # setup command line args",
"+= image.array[x_i, y_i, c] new_im.array[x,y,c] = total / (k_size **2)",
"edges) is as follows: # [1 0 -1] # [2",
"in image return new_im def apply_kernel(image, kernel): # the kernel",
"new_im def show_image(in_image): path=\"input/\" img = mpimg.imread(path+in_image) imgplot = plt.imshow(img)",
"def arg_init(): parser = argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to this",
"args = arg_init() check_env(args.image) lake = Image(filename = 'lake.png') city",
"and args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total",
"transform.py show city.png # python transform.py blur city.png from image",
"kernel (detecting horizontal edges) is as follows: # [1 0",
"use! # for the sake of simiplicity of this implementation,",
"2 for x in range(x_pixels): for y in range(y_pixels): for",
"c] = total return new_im def combine_images(image1, image2): # let's",
"#scale each value by some amount x_pixels, y_pixels,num_channels = image.array.shape",
"= Image(filename='city.png') start_time = time.time() # brightened_im = adjust_brightness(lake, 1.7)",
"x_k = x_i + neighbor_range - x y_k = y_i",
"1.7) # brightened_im.write_image('brightened.png') # darkened_im = adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png')",
"sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\" and args.image: show_image(args.image) if args.cmd",
"0, -1]])) # sobel_y.write_image('edge_y.png') # # this will show x",
"that output/input dirs exist: path = './output/' is_path = os.path.isdir(path)",
"!= \"show\" and args.cmd != \"blur\": return args #def show_image(filename):",
"darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast",
"cmd show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 # python transform.py",
"factor + mid #non vectorized version #vectorized version # new_im.array",
"c] = (image1.array[x, y, c]**2 + image2.array[x, y, c]**2)**0.5 return",
"args.cmd != \"blur\": return args #def show_image(filename): if __name__ ==",
"check_env( in_image): #check to verify that output/input dirs exist: path",
"to copy values to! neighbor_range = kernel.shape[0] // 2 #",
"'./output/' is_path = os.path.isdir(path) if not is_path: print('local ./output dir",
"y_pixels=y_pixels, num_channels=num_channels) # making a new array to copy values",
"(ie for a 3x3 kernel, this value should be 1)",
"look at (ie for a 3x3 kernel, this value should",
"y pixels of image, # channels (R, G, B) new_im",
"range(num_channels): new_im.array[x, y, c] = (image1.array[x, y, c]**2 + image2.array[x,",
"args.cmd == \"show\" and args.image: show_image(args.image) if args.cmd == \"blur\"",
"y in range(y_pixels): for c in range(num_channels): total = 0",
"image2 MUST be the same x_pixels, y_pixels, num_channels = image1.array.shape",
"2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png')",
"= image1.array.shape # represents x, y pixels of image, #",
"is_path = os.path.isdir(path) if not is_path: print('local ./input dir must",
"= os.path.isdir(path) if not is_path: print('local ./input dir must exist,",
"(image.array - mid) * factor + mid return new_im #",
"by some amount x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels)",
"[-1, -2, -1]])) # sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city, np.array([[1,",
"# setup command line args and parms # optional args",
"and y edges # sobel_xy = combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png')",
"x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group = parser.add_mutually_exclusive_group()",
"actually look at (ie for a 3x3 kernel, this value",
"= total / (k_size **2) # average for kernel size",
"continue...') print(quit) quit() #verify input image if in_image: thefile =",
"y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels):",
"mid return new_im # blur and image def blur(image, k_size):",
"cannot continue...') print(quit) quit() path = './input/' is_path = os.path.isdir(path)",
"args.cmd == \"blur\" and args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png)",
"np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])) #",
"== \"blur\" and args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if",
"Image import numpy as np import time, os, argparse, string",
"new array to copy values to! neighbor_range = kernel.shape[0] //",
"= image.array.shape # represents x, y pixels of image, #",
"variable that tells us how many neighbors we actually look",
"apply a sobel kernel on the x and y axis",
"# cmd: python3 transform.py # you must have local input/",
"right neighbor pixels, and diagonal #neighbor pixels. im = Image(filename",
"'__main__': args = arg_init() check_env(args.image) lake = Image(filename = 'lake.png')",
"= Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels): for y in range(y_pixels):",
"be above and below and left neighbor, right neighbor pixels,",
"for y in range(y_pixels): for c in range(num_channels): total =",
"0, 0], [-1, -2, -1]])) # sobel_x.write_image('edge_x.png') # sobel_y =",
"y in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c]",
"and image2 MUST be the same x_pixels, y_pixels, num_channels =",
"y in image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text",
"range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i, y_i, c] new_im.array[x,y,c] =",
"# sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city, np.array([[1, 0, -1], [2,",
"neighbor, right neighbor pixels, and diagonal #neighbor pixels. im =",
"city.png # python transform.py blur city.png from image import Image",
"midpoint def adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape new_im",
"to copy values to! for x in range(x_pixels): for y",
"(image.array[x,y,c] -mid)* factor + mid #non vectorized version #vectorized version",
"two images using the squared sum of squares: value =",
"+ mid return new_im # blur and image def blur(image,",
"output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args = parser.parse_args() print(args.image) #if args.cmd",
"y_pixels, num_channels = image.array.shape # represents x, y pixels of",
"an image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input image name for",
"will show x and y edges # sobel_xy = combine_images(sobel_x,",
"== '__main__': args = arg_init() check_env(args.image) lake = Image(filename =",
"combine two images using the squared sum of squares: value",
"output/input dirs exist: path = './output/' is_path = os.path.isdir(path) if",
"1) for x in range(x_pixels): for y in range(y_pixels): for",
"kernel_val new_im.array[x, y, c] = total return new_im def combine_images(image1,",
"decr_contrast.write_image('decr_contrast.png') # blur_3 = blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15 =",
"adjust_brightness(image,factor): #scale each value by some amount x_pixels, y_pixels,num_channels =",
"# represents x, y pixels of image, # channels (R,",
"num_channels = image1.array.shape # represents x, y pixels of image,",
"./output dir must be writeable, cannot continue...') print(quit) quit() path",
"--ulx=1 --uly=2 --brx=0 --bry=9 # python transform.py show city.png #",
"y+neighbor_range)+1): x_k = x_i + neighbor_range - x y_k =",
"the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\")",
"a 3x3 kernel, this value should be 1) for x",
"if in_image: thefile = 'input/'+in_image print('file path: '+thefile) is_file =",
"= sqrt(value_1**2, value_2**2) # size of image1 and image2 MUST",
"making a new array to copy values to! neighbor_range =",
"#check to verify that output/input dirs exist: path = './output/'",
"= os.path.isfile(thefile) if not is_file: print(f'local ./input file {in_image} must",
"args.image: show_image(args.image) if args.cmd == \"blur\" and args.image: blur_15 =",
"and image def blur(image, k_size): #k_size is the number of",
"continue...') print(quit) quit() if imghdr.what(thefile) != 'png': print('wrong image file",
"sobel x kernel (detecting horizontal edges) is as follows: #",
"# fixed (required args do not have --) def arg_init():",
"image.array * factor -# this is faster return new_im #adjust",
"neighbor_range - y kernel_val = kernel[x_k, y_k] total += image.array[x_i,",
"#verify output is writeable is_w = os.access(path, os.W_OK) if not",
"args #def show_image(filename): if __name__ == '__main__': args = arg_init()",
"new_im.array[x, y, c] = (image1.array[x, y, c]**2 + image2.array[x, y,",
"total += image.array[x_i, y_i, c] new_im.array[x,y,c] = total / (k_size",
"parser = argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input",
"[2 0 -2] # [1 0 -1] x_pixels, y_pixels, num_channels",
"os.access(path, os.W_OK) if not is_w: print('local ./output dir must be",
"string #from tkinter import * import imghdr import matplotlib.image as",
"= argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input image",
"not is_file: print(f'local ./input file {in_image} must exist, cannot continue...')",
"in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\")",
"arg_init() check_env(args.image) lake = Image(filename = 'lake.png') city = Image(filename='city.png')",
"def blur(image, k_size): #k_size is the number of pixels to",
"values to! for x in range(x_pixels): for y in range(y_pixels):",
"apply_kernel(image, kernel): # the kernel should be a 2D array",
"x kernel (detecting horizontal edges) is as follows: # [1",
"for a 3x3 kernel, this value should be 1) for",
"must have local input/ and output/ directories # # name:",
"change images # cmd: python3 transform.py # you must have",
"kernel should be a 2D array that represents the kernel",
"'lake.png') city = Image(filename='city.png') start_time = time.time() # brightened_im =",
"quit() #verify output is writeable is_w = os.access(path, os.W_OK) if",
"args = parser.parse_args() print(args.image) #if args.cmd != \"show\" and args.cmd",
"edges # sobel_xy = combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd",
"argparse.ArgumentParser(description='Process an image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input image name",
"pixels, and diagonal #neighbor pixels. im = Image(filename = image)",
"[1 0 -1] # [2 0 -2] # [1 0",
"os.W_OK) if not is_w: print('local ./output dir must be writeable,",
"\"show\" and args.image: show_image(args.image) if args.cmd == \"blur\" and args.image:",
"* factor #non vectorized version #vectorized version # new_im.array =",
"# the kernel should be a 2D array that represents",
"assume that the kernel is SQUARE # for example the",
"# darkened_im = adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') # incr_contrast =",
"in range(num_channels): new_im.array[x, y, c] = (image1.array[x, y, c]**2 +",
"+ neighbor_range - y kernel_val = kernel[x_k, y_k] total +=",
"blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png') #",
"image.array[x_i, y_i, c] new_im.array[x,y,c] = total / (k_size **2) #",
"the number of pixels to use when doing the blur",
"(R, G, B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making",
"array to copy values to! neighbor_range = kernel.shape[0] // 2",
"print('file path: '+thefile) is_file = os.path.isfile(thefile) if not is_file: print(f'local",
"cannot continue...') print(quit) quit() if imghdr.what(thefile) != 'png': print('wrong image",
"#neighbor pixels. im = Image(filename = image) x_pixels, y_pixels,num_channels =",
"pixels of image, # channels (R, G, B) new_im =",
"mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show() # check for necessary parts",
"show_image(filename): if __name__ == '__main__': args = arg_init() check_env(args.image) lake",
"group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text output\") group.add_argument('--q', action='store_true',help=\"minimal",
"as plt def adjust_brightness(image,factor): #scale each value by some amount",
"and below and left neighbor, right neighbor pixels, and diagonal",
"image.array.shape # represents x, y pixels of image, # channels",
"# making a new array to copy values to! for",
"is_path: print('local ./input dir must exist, cannot continue...') print(quit) quit()",
"imgplot = plt.imshow(img) plt.show() # check for necessary parts of",
"# name: <NAME> # date: 12/27/20 # cmdline: python transform.py",
"args do not have --) def arg_init(): parser = argparse.ArgumentParser(description='Process",
"how many neighbors we actually look at (ie for a",
"\"blur\": return args #def show_image(filename): if __name__ == '__main__': args",
"# for the sake of simiplicity of this implementation, let's",
"range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor + mid #non vectorized",
"axis # sobel_x = apply_kernel(city, np.array([[1, 2, 1], [0, 0,",
"if imghdr.what(thefile) != 'png': print('wrong image file type, cannot continue...')",
"action='store_true',help=\"minimal output\") args = parser.parse_args() print(args.image) #if args.cmd != \"show\"",
"must be writeable, cannot continue...') print(quit) quit() path = './input/'",
"combine_images(sobel_x, sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\" and args.image:",
"to this program\",type=str) parser.add_argument(\"image\",help=\"input image name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft",
"array to copy values to! for x in range(x_pixels): for",
"average for kernel size in image return new_im def apply_kernel(image,",
"pixels to use when doing the blur #k_size=3 would be",
"plt.imshow(img) plt.show() # check for necessary parts of the runtime",
"in_image): #check to verify that output/input dirs exist: path =",
"'./input/' is_path = os.path.isdir(path) if not is_path: print('local ./input dir",
"new_im.array = image.array * factor -# this is faster return",
"= Image(filename = 'lake.png') city = Image(filename='city.png') start_time = time.time()",
"tells us how many neighbors we actually look at (ie",
"for y in range(y_pixels): for c in range(num_channels): new_im.array[x, y,",
"- mid) * factor + mid return new_im # blur",
"if args.cmd == \"show\" and args.image: show_image(args.image) if args.cmd ==",
"--bry=9 # python transform.py show city.png # python transform.py blur",
"c in range(num_channels): total = 0 for x_i in range(max(0,x-neighbor_range),",
"for c in range(num_channels): new_im.array[x, y, c] = (image1.array[x, y,",
"this program\",type=str) parser.add_argument(\"image\",help=\"input image name for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x",
"k_size // 2 for x in range(x_pixels): for y in",
"print(quit) quit() if imghdr.what(thefile) != 'png': print('wrong image file type,",
"print('local ./output dir must exist, cannot continue...') print(quit) quit() #verify",
"in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1):",
"output\") args = parser.parse_args() print(args.image) #if args.cmd != \"show\" and",
"y_k] total += image.array[x_i, y_i, c] * kernel_val new_im.array[x, y,",
"and y axis # sobel_x = apply_kernel(city, np.array([[1, 2, 1],",
"adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake, 0.5,0.5) #",
"matplotlib.pyplot as plt def adjust_brightness(image,factor): #scale each value by some",
"image1 and image2 MUST be the same x_pixels, y_pixels, num_channels",
"example the sobel x kernel (detecting horizontal edges) is as",
"transform.py # you must have local input/ and output/ directories",
"np import time, os, argparse, string #from tkinter import *",
"new_im # blur and image def blur(image, k_size): #k_size is",
"of squares: value = sqrt(value_1**2, value_2**2) # size of image1",
"kernel on the x and y axis # sobel_x =",
"# [2 0 -2] # [1 0 -1] x_pixels, y_pixels,",
"parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x",
"incr_contrast = adjust_contrast(lake, 2,0.5) # incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake,",
"for c in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] * factor #non",
"import Image import numpy as np import time, os, argparse,",
"python transform.py show city.png # python transform.py blur city.png from",
"= blur(city,3) # blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png')",
"a new array to copy values to! neighbor_range = kernel.shape[0]",
"in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\")",
"= Image(filename = image) x_pixels, y_pixels,num_channels = im.array.shape new_im =",
"= parser.parse_args() print(args.image) #if args.cmd != \"show\" and args.cmd !=",
"= image.array[x,y,c] * factor #non vectorized version #vectorized version #",
"imghdr import matplotlib.image as mpimg import matplotlib.pyplot as plt def",
"this will show x and y edges # sobel_xy =",
"y in range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = image.array[x,y,c]",
"import numpy as np import time, os, argparse, string #from",
"below and left neighbor, right neighbor pixels, and diagonal #neighbor",
"image.array[x_i, y_i, c] * kernel_val new_im.array[x, y, c] = total",
"sqrt(value_1**2, value_2**2) # size of image1 and image2 MUST be",
"parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more",
"= kernel[x_k, y_k] total += image.array[x_i, y_i, c] * kernel_val",
"# blur_3.write_image('blur_k3.png') # blur_15 = blur(city,15) # blur_15.write_image('blur_k15.png') # let's",
"directories # # name: <NAME> # date: 12/27/20 # cmdline:",
"continue...') print(quit) quit() path = './input/' is_path = os.path.isdir(path) if",
"im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size // 2 for",
"range(x_pixels): for y in range(y_pixels): for c in range(num_channels): total",
"y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total += image.array[x_i, y_i, c]",
"must exist, cannot continue...') print(quit) quit() if imghdr.what(thefile) != 'png':",
"adjust_brightness(lake, 0.3) # darkened_im.write_image('darkened.png') # incr_contrast = adjust_contrast(lake, 2,0.5) #",
"#vectorized version # new_im.array = image.array * factor -# this",
"value = sqrt(value_1**2, value_2**2) # size of image1 and image2",
"is_path: print('local ./output dir must exist, cannot continue...') print(quit) quit()",
"file type, cannot continue...') print(quit) quit() def cmd(): print(\"routine cmd\")",
"image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add",
"<NAME> # date: 12/27/20 # cmdline: python transform.py cmd show",
"= image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels): for",
"# cmdline: python transform.py cmd show image='city.png' --ulx=1 --uly=2 --brx=0",
"# python transform.py show city.png # python transform.py blur city.png",
"neighbor_range = k_size // 2 for x in range(x_pixels): for",
"# optional args have -- # fixed (required args do",
"as follows: # [1 0 -1] # [2 0 -2]",
"factor -# this is faster return new_im #adjust the contrast",
"necessary parts of the runtime environment def check_env( in_image): #check",
"faster return new_im #adjust the contrast by increasing difference from",
"kernel we'll use! # for the sake of simiplicity of",
"x, y pixels of image, # channels (R, G, B)",
"check_env(args.image) lake = Image(filename = 'lake.png') city = Image(filename='city.png') start_time",
"= Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new array to",
"be the same x_pixels, y_pixels, num_channels = image1.array.shape # represents",
"action='store_true',help=\"add more text output\") group.add_argument('--q', action='store_true',help=\"minimal output\") args = parser.parse_args()",
"for the command\",type=str) parser.add_argument(\"--ulx\",action='store_true',help=\"upperleft x in image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in",
"img = mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show() # check for",
"Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size // 2 for x in range(x_pixels):",
"#vectorized version # new_im.array = (image.array - mid) * factor",
"transform.py blur city.png from image import Image import numpy as",
"'input/'+in_image print('file path: '+thefile) is_file = os.path.isfile(thefile) if not is_file:",
"show x and y edges # sobel_xy = combine_images(sobel_x, sobel_y)",
"and args.image: show_image(args.image) if args.cmd == \"blur\" and args.image: blur_15",
"adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels)",
"./input dir must exist, cannot continue...') print(quit) quit() #verify input",
"# blur and image def blur(image, k_size): #k_size is the",
"values to! neighbor_range = kernel.shape[0] // 2 # this is",
"args and parms # optional args have -- # fixed",
"the kernel we'll use! # for the sake of simiplicity",
"SQUARE # for example the sobel x kernel (detecting horizontal",
"sobel_y) # sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\" and args.image: show_image(args.image)",
"input/ and output/ directories # # name: <NAME> # date:",
"type, cannot continue...') print(quit) quit() def cmd(): print(\"routine cmd\") #",
"print(args.image) #if args.cmd != \"show\" and args.cmd != \"blur\": return",
"if not is_file: print(f'local ./input file {in_image} must exist, cannot",
"must exist, cannot continue...') print(quit) quit() #verify input image if",
"# check for necessary parts of the runtime environment def",
"exist, cannot continue...') print(quit) quit() #verify output is writeable is_w",
"images # cmd: python3 transform.py # you must have local",
"def adjust_contrast(image, factor, mid=0.5): x_pixels, y_pixels,num_channels = image.array.shape new_im =",
"2, 1], [0, 0, 0], [-1, -2, -1]])) # sobel_x.write_image('edge_x.png')",
"and change images # cmd: python3 transform.py # you must",
"image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v', action='store_true',help=\"add more text output\") group.add_argument('--q',",
"new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) for x in range(x_pixels): for y in",
"min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total +=",
"by increasing difference from user #defined midpoint def adjust_contrast(image, factor,",
"writeable is_w = os.access(path, os.W_OK) if not is_w: print('local ./output",
"size of image1 and image2 MUST be the same x_pixels,",
"lake = Image(filename = 'lake.png') city = Image(filename='city.png') start_time =",
"./input file {in_image} must exist, cannot continue...') print(quit) quit() if",
"# sobel_xy.write_image('edge_xy.png') if args.cmd == \"show\" and args.image: show_image(args.image) if",
"image2): # let's combine two images using the squared sum",
"show_image(args.image) if args.cmd == \"blur\" and args.image: blur_15 = blur(args.image,15)",
"y_i, c] new_im.array[x,y,c] = total / (k_size **2) # average",
"= 0 for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i",
"show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 # python transform.py show",
"transform.py cmd show image='city.png' --ulx=1 --uly=2 --brx=0 --bry=9 # python",
"0 for x_i in range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in",
"incr_contrast.write_image('incr_contrast.png') # decr_contrast = adjust_contrast(lake, 0.5,0.5) # decr_contrast.write_image('decr_contrast.png') # blur_3",
"= image) x_pixels, y_pixels,num_channels = im.array.shape new_im = Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range",
"= apply_kernel(city, np.array([[1, 0, -1], [2, 0, -2], [1, 0,",
"range(max(0,x-neighbor_range), min(new_im.x_pixels-1, x+neighbor_range)+1): for y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): total",
"x y_k = y_i + neighbor_range - y kernel_val =",
"* factor + mid return new_im # blur and image",
"y in range(y_pixels): for c in range(num_channels): new_im.array[x, y, c]",
"c]**2 + image2.array[x, y, c]**2)**0.5 return new_im def show_image(in_image): path=\"input/\"",
"kernel.shape[0] // 2 # this is a variable that tells",
"this value should be 1) for x in range(x_pixels): for",
"y_i in range(max(0,y-neighbor_range), min(new_im.y_pixels-1, y+neighbor_range)+1): x_k = x_i + neighbor_range",
"range(y_pixels): for c in range(num_channels): new_im.array[x, y, c] = (image1.array[x,",
"fixed (required args do not have --) def arg_init(): parser",
"print(quit) quit() def cmd(): print(\"routine cmd\") # setup command line",
"quit() if imghdr.what(thefile) != 'png': print('wrong image file type, cannot",
"# let's apply a sobel kernel on the x and",
"sobel kernel on the x and y axis # sobel_x",
"= k_size // 2 for x in range(x_pixels): for y",
"image, # channels (R, G, B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels,",
"Image(filename = 'lake.png') city = Image(filename='city.png') start_time = time.time() #",
"if not is_path: print('local ./output dir must exist, cannot continue...')",
"0, -2], [1, 0, -1]])) # sobel_y.write_image('edge_y.png') # # this",
"parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y",
"new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor + mid #non vectorized version",
"simiplicity of this implementation, let's assume that the kernel is",
"# sobel_y = apply_kernel(city, np.array([[1, 0, -1], [2, 0, -2],",
"in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright y in image\") group = parser.add_mutually_exclusive_group() group.add_argument('--v',",
"be a 2D array that represents the kernel we'll use!",
"factor #non vectorized version #vectorized version # new_im.array = image.array",
"= Image(x_pixels=x_pixels,y_pixels=y_pixels,num_channels=num_channels) neighbor_range = k_size // 2 for x in",
"**2) # average for kernel size in image return new_im",
"blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v: print(f'total execution duration: {time.time() - start_time}s')",
"-mid)* factor + mid #non vectorized version #vectorized version #",
"path=\"input/\" img = mpimg.imread(path+in_image) imgplot = plt.imshow(img) plt.show() # check",
"0, -1], [2, 0, -2], [1, 0, -1]])) # sobel_y.write_image('edge_y.png')",
"each value by some amount x_pixels, y_pixels,num_channels = image.array.shape new_im",
"and parms # optional args have -- # fixed (required",
"for c in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor +",
"sobel_x.write_image('edge_x.png') # sobel_y = apply_kernel(city, np.array([[1, 0, -1], [2, 0,",
"represents x, y pixels of image, # channels (R, G,",
"\"blur\" and args.image: blur_15 = blur(args.image,15) blur_15.write_image(args.image+'blur_k15.png') show_image(blur_k15.png) if args.v:",
"is_path = os.path.isdir(path) if not is_path: print('local ./output dir must",
"#adjust the contrast by increasing difference from user #defined midpoint",
"python transform.py blur city.png from image import Image import numpy",
"total return new_im def combine_images(image1, image2): # let's combine two",
"image.') parser.add_argument(\"cmd\",help=\"command to this program\",type=str) parser.add_argument(\"image\",help=\"input image name for the",
"__name__ == '__main__': args = arg_init() check_env(args.image) lake = Image(filename",
"images and change images # cmd: python3 transform.py # you",
"range(num_channels): new_im.array[x,y,c] = image.array[x,y,c] * factor #non vectorized version #vectorized",
"is_w: print('local ./output dir must be writeable, cannot continue...') print(quit)",
"[0, 0, 0], [-1, -2, -1]])) # sobel_x.write_image('edge_x.png') # sobel_y",
"doing the blur #k_size=3 would be above and below and",
"image\") parser.add_argument(\"--uly\",action='store_true',help=\"upperleft y in image\") parser.add_argument(\"--brx\",action='store_true',help=\"bottomright x in image\") parser.add_argument(\"--bry\",action='store_true',help=\"bottomright",
"= 'lake.png') city = Image(filename='city.png') start_time = time.time() # brightened_im",
"using the squared sum of squares: value = sqrt(value_1**2, value_2**2)",
"3x3 kernel, this value should be 1) for x in",
"B) new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels) # making a new",
"c] new_im.array[x,y,c] = total / (k_size **2) # average for",
"kernel): # the kernel should be a 2D array that",
"cannot continue...') print(quit) quit() #verify input image if in_image: thefile",
"output/ directories # # name: <NAME> # date: 12/27/20 #",
"blur #k_size=3 would be above and below and left neighbor,",
"= plt.imshow(img) plt.show() # check for necessary parts of the",
"if __name__ == '__main__': args = arg_init() check_env(args.image) lake =",
"the x and y axis # sobel_x = apply_kernel(city, np.array([[1,",
"dir must exist, cannot continue...') print(quit) quit() #verify output is",
"= y_i + neighbor_range - y kernel_val = kernel[x_k, y_k]",
"let's apply a sobel kernel on the x and y",
"#from tkinter import * import imghdr import matplotlib.image as mpimg",
"num_channels = image.array.shape # represents x, y pixels of image,",
"increasing difference from user #defined midpoint def adjust_contrast(image, factor, mid=0.5):",
"y_k = y_i + neighbor_range - y kernel_val = kernel[x_k,",
"'png': print('wrong image file type, cannot continue...') print(quit) quit() def",
"return new_im def combine_images(image1, image2): # let's combine two images",
"horizontal edges) is as follows: # [1 0 -1] #",
"range(y_pixels): for c in range(num_channels): new_im.array[x,y,c] = (image.array[x,y,c] -mid)* factor"
] |
[
"you rather **{}** or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied =",
"choice == \"1\": return 0 if choice == \"2\": return",
"in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are ZERO questions saved.",
"db.asyncsave() answer = random.choice(opt) await client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\",",
"this set @plugins.argument(\"{open}option ...{close} or/, {open}other option ...{close}[?]\", allow_spaces=True) async",
"\"\"\" import asyncio import random import re import discord import",
"on timeout except asyncio.TimeoutError: break # Check if the choice",
"\"\"\" if choice == \"1\": return 0 if choice ==",
"total of {0} would **{2}**, while {1} would **{3}**!\".format( *question[\"answers\"],",
"Go through all words in the given message, and find",
"import random import re import discord import bot import plugins",
"lie or be lied to` Asking the bot: `!wouldyourather`\"\"\" #",
"q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message, \"**Entry removed.**\")",
"0 elif word in words[1] and word not in words[0]:",
"are ZERO questions saved. Ask me one!**\" question = random.choice(db.data[\"questions\"])",
"check=check) # Break on timeout except asyncio.TimeoutError: break # Check",
"is already in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are ZERO",
"get_choice(choices: list, choice: str): \"\"\" Get the chosen option. This",
"return None @plugins.command(aliases=\"wyr rather either\") async def wouldyourather(message: discord.Message, opt:",
"ZERO questions saved. Ask me one!**\" question = random.choice(db.data[\"questions\"]) choices",
"list, choice: str): \"\"\" Get the chosen option. This accept",
"be the same.**\" return match.group(1), match.group(2) def get_choice(choices: list, choice:",
"be lied to` Asking the bot: `!wouldyourather`\"\"\" # If there",
"while True: def check(m): return m.channel == message.channel and m.author",
"= plugins.client # type: bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}**",
"member asked a question to the bot else: db.data[\"questions\"].append(dict( choices=list(opt),",
"== message.channel and m.author not in replied try: reply =",
"m.author not in replied try: reply = await client.wait_for_message(timeout=timeout, check=check)",
"the questions (if there are any to choose from) if",
"Get the chosen option. This accept 1 and 2 as",
"the answers in the DB # We don't care about",
"not in words[1]: return 0 elif word in words[1] and",
"valid choice = get_choice(choices, reply.content) if choice is None: continue",
"\"\"\" Get the chosen option. This accept 1 and 2",
"in choice.lower().split(): if word in words[0] and word not in",
"ask you. **Examples:** Registering a choice: `!wouldyourather lie or be",
"{0} would **{2}**, while {1} would **{3}**!\".format( *question[\"answers\"], *choices)) await",
"he would rather, or have the bot ask you. **Examples:**",
"timeout = db.data[\"timeout\"] replied = [] # Wait for replies",
"if q[\"choices\"][0] == opt[0] and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await",
"don't care about multiples, just the amount (yes it will",
"get_choice(choices, reply.content) if choice is None: continue # Register that",
"\"**Entry removed.**\") break else: await client.say(message, \"**Could not find the",
"Check if the choice is valid choice = get_choice(choices, reply.content)",
"sessions, \"**A would you rather session is already in progress.**\"",
"just the amount (yes it will probably be biased) question[\"answers\"][choice]",
"+= 1 name = reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice])",
"you rather's are in this set @plugins.argument(\"{open}option ...{close} or/, {open}other",
"(if there are any to choose from) if opt is",
"[] # Wait for replies from anyone in the channel",
"question[\"answers\"][choice] += 1 name = reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(),",
"**Examples:** Registering a choice: `!wouldyourather lie or be lied to`",
"choice=choices[choice]) await client.say(message, response) # Say the total tallies await",
"`!wouldyourather lie or be lied to` Asking the bot: `!wouldyourather`\"\"\"",
"def options(arg): \"\"\" Command argument for receiving two options. \"\"\"",
"from pcbot import Config client = plugins.client # type: bot.Client",
"client.say(message, response) # Say the total tallies await client.say(message, \"A",
"1 choices = list(map(str.lower, choices)) words = list(map(str.split, choices)) #",
"choices)) # Go through all words in the given message,",
"Remove a wouldyourather question with the given options. \"\"\" for",
"Wait for replies from anyone in the channel while True:",
"def wouldyourather(message: discord.Message, opt: options = None): \"\"\" Ask the",
"`!wouldyourather`\"\"\" # If there are no options, the bot will",
"None: continue # Register that this author has replied replied.append(reply.author)",
"replied.append(reply.author) # Update the answers in the DB # We",
"the bot will ask the questions (if there are any",
"except asyncio.TimeoutError: break # Check if the choice is valid",
"import bot import plugins from pcbot import Config client =",
"the bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] )) await db.asyncsave()",
"else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] )) await db.asyncsave() answer =",
"# Register that this author has replied replied.append(reply.author) # Update",
"anyone in the channel while True: def check(m): return m.channel",
"choices=list(opt), answers=[0, 0] )) await db.asyncsave() answer = random.choice(opt) await",
"opt[0] and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message,",
"and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message, \"**Entry",
"db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the member asked a question to",
"not in sessions, \"**A would you rather session is already",
"async def remove(message: discord.Message, opt: options): \"\"\" Remove a wouldyourather",
"not match.group(1).lower() == match.group(2).lower(), \"**The choices cannot be the same.**\"",
"Registering a choice: `!wouldyourather lie or be lied to` Asking",
"is None: assert message.channel.id not in sessions, \"**A would you",
"about multiples, just the amount (yes it will probably be",
"channel while True: def check(m): return m.channel == message.channel and",
"import discord import bot import plugins from pcbot import Config",
"Invalid choice return None @plugins.command(aliases=\"wyr rather either\") async def wouldyourather(message:",
"in words[1]: return 0 elif word in words[1] and word",
"allow_spaces=True) async def options(arg): \"\"\" Command argument for receiving two",
"client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message: discord.Message,",
"in the channel while True: def check(m): return m.channel ==",
"rather, or have the bot ask you. **Examples:** Registering a",
"tallies await client.say(message, \"A total of {0} would **{2}**, while",
"words unique to a choice for word in choice.lower().split(): if",
"argument for receiving two options. \"\"\" match = command_pattern.match(arg) assert",
"import plugins from pcbot import Config client = plugins.client #",
"choice: `!wouldyourather lie or be lied to` Asking the bot:",
"bot ask you. **Examples:** Registering a choice: `!wouldyourather lie or",
"await client.wait_for_message(timeout=timeout, check=check) # Break on timeout except asyncio.TimeoutError: break",
"if word in words[0] and word not in words[1]: return",
"choices)) words = list(map(str.split, choices)) # Go through all words",
"**{choice}**!\"], questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() #",
"options(arg): \"\"\" Command argument for receiving two options. \"\"\" match",
"\"\"\" Would you rather? This plugin includes would you rather",
"would you rather's are in this set @plugins.argument(\"{open}option ...{close} or/,",
"receiving two options. \"\"\" match = command_pattern.match(arg) assert match assert",
"the given message, and find any words unique to a",
"async def wouldyourather(message: discord.Message, opt: options = None): \"\"\" Ask",
"Break on timeout except asyncio.TimeoutError: break # Check if the",
"probably be biased) question[\"answers\"][choice] += 1 name = reply.author.display_name response",
"name = reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message,",
"if choice == \"1\": return 0 if choice == \"2\":",
"reply = await client.wait_for_message(timeout=timeout, check=check) # Break on timeout except",
"# We don't care about multiples, just the amount (yes",
"== opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message, \"**Entry removed.**\") break",
"if choice is None: continue # Register that this author",
"match assert not match.group(1).lower() == match.group(2).lower(), \"**The choices cannot be",
"choice is valid choice = get_choice(choices, reply.content) if choice is",
"Config client = plugins.client # type: bot.Client db = Config(\"would-you-rather\",",
"asyncio import random import re import discord import bot import",
"We don't care about multiples, just the amount (yes it",
"be biased) question[\"answers\"][choice] += 1 name = reply.author.display_name response =",
"async def options(arg): \"\"\" Command argument for receiving two options.",
"1 name = reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await",
"bot import plugins from pcbot import Config client = plugins.client",
"total tallies await client.say(message, \"A total of {0} would **{2}**,",
"random.choice(opt) await client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def",
"and find any words unique to a choice for word",
"db.data[\"questions\"]: if q[\"choices\"][0] == opt[0] and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q)",
"choices cannot be the same.**\" return match.group(1), match.group(2) def get_choice(choices:",
"True: def check(m): return m.channel == message.channel and m.author not",
"# Otherwise, the member asked a question to the bot",
"type: bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]),",
"timeout except asyncio.TimeoutError: break # Check if the choice is",
"Register that this author has replied replied.append(reply.author) # Update the",
"m.channel == message.channel and m.author not in replied try: reply",
"word in words[1] and word not in words[0]: return 1",
"discord.Message, opt: options): \"\"\" Remove a wouldyourather question with the",
"with the given options. \"\"\" for q in db.data[\"questions\"]: if",
"...{close} or/, {open}other option ...{close}[?]\", allow_spaces=True) async def options(arg): \"\"\"",
"= re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() # All running would you",
"choice == \"2\": return 1 choices = list(map(str.lower, choices)) words",
"word not in words[0]: return 1 # Invalid choice return",
"== \"1\": return 0 if choice == \"2\": return 1",
"saved. Ask me one!**\" question = random.choice(db.data[\"questions\"]) choices = question[\"choices\"]",
"if choice == \"2\": return 1 choices = list(map(str.lower, choices))",
"and word not in words[0]: return 1 # Invalid choice",
"= db.data[\"timeout\"] replied = [] # Wait for replies from",
"\"**A would you rather session is already in progress.**\" sessions.add(message.channel.id)",
"questions saved. Ask me one!**\" question = random.choice(db.data[\"questions\"]) choices =",
"plugins from pcbot import Config client = plugins.client # type:",
"return 1 # Invalid choice return None @plugins.command(aliases=\"wyr rather either\")",
"client.say(message, \"Would you rather **{}** or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"]",
"reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message, response) #",
"cannot be the same.**\" return match.group(1), match.group(2) def get_choice(choices: list,",
"to` Asking the bot: `!wouldyourather`\"\"\" # If there are no",
"= Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True) command_pattern =",
"any to choose from) if opt is None: assert message.channel.id",
"# If there are no options, the bot will ask",
"for receiving two options. \"\"\" match = command_pattern.match(arg) assert match",
"is valid choice = get_choice(choices, reply.content) if choice is None:",
"words = list(map(str.split, choices)) # Go through all words in",
"while {1} would **{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id) #",
"import Config client = plugins.client # type: bot.Client db =",
"sessions = set() # All running would you rather's are",
"discord import bot import plugins from pcbot import Config client",
"NAME=name.upper(), choice=choices[choice]) await client.say(message, response) # Say the total tallies",
"= reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message, response)",
"**{2}**, while {1} would **{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id)",
"accept 1 and 2 as numbers. \"\"\" if choice ==",
"break # Check if the choice is valid choice =",
"random import re import discord import bot import plugins from",
"{open}other option ...{close}[?]\", allow_spaces=True) async def options(arg): \"\"\" Command argument",
"All running would you rather's are in this set @plugins.argument(\"{open}option",
")) await db.asyncsave() answer = random.choice(opt) await client.say(message, \"**I would",
"or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied = [] # Wait",
"running would you rather's are in this set @plugins.argument(\"{open}option ...{close}",
"question = random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await client.say(message, \"Would you",
"await client.say(message, \"Would you rather **{}** or **{}**?\".format(*choices)) timeout =",
"# Update the answers in the DB # We don't",
"\"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message: discord.Message, opt:",
"the member asked a question to the bot else: db.data[\"questions\"].append(dict(",
"are any to choose from) if opt is None: assert",
"return 0 if choice == \"2\": return 1 choices =",
"def check(m): return m.channel == message.channel and m.author not in",
"wouldyourather(message: discord.Message, opt: options = None): \"\"\" Ask the bot",
"rather functionality \"\"\" import asyncio import random import re import",
"owner=True) async def remove(message: discord.Message, opt: options): \"\"\" Remove a",
"= random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message, response) # Say the",
"in the given message, and find any words unique to",
"includes would you rather functionality \"\"\" import asyncio import random",
"q[\"choices\"][0] == opt[0] and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave()",
"# Say the total tallies await client.say(message, \"A total of",
"= question[\"choices\"] await client.say(message, \"Would you rather **{}** or **{}**?\".format(*choices))",
"\"2\": return 1 choices = list(map(str.lower, choices)) words = list(map(str.split,",
"if the choice is valid choice = get_choice(choices, reply.content) if",
"\"**The choices cannot be the same.**\" return match.group(1), match.group(2) def",
"to a choice for word in choice.lower().split(): if word in",
"plugins.client # type: bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would",
"db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True) command_pattern",
"db.asyncsave() await client.say(message, \"**Entry removed.**\") break else: await client.say(message, \"**Could",
"would you rather functionality \"\"\" import asyncio import random import",
"words in the given message, and find any words unique",
"2 as numbers. \"\"\" if choice == \"1\": return 0",
"str): \"\"\" Get the chosen option. This accept 1 and",
"chosen option. This accept 1 and 2 as numbers. \"\"\"",
"question[\"choices\"] await client.say(message, \"Would you rather **{}** or **{}**?\".format(*choices)) timeout",
"assert db.data[\"questions\"], \"**There are ZERO questions saved. Ask me one!**\"",
"as numbers. \"\"\" if choice == \"1\": return 0 if",
"would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message: discord.Message, opt: options):",
"import re import discord import bot import plugins from pcbot",
"= list(map(str.lower, choices)) words = list(map(str.split, choices)) # Go through",
"words[0] and word not in words[1]: return 0 elif word",
"client = plugins.client # type: bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10,",
"discord.Message, opt: options = None): \"\"\" Ask the bot if",
"<gh_stars>0 \"\"\" Would you rather? This plugin includes would you",
"care about multiples, just the amount (yes it will probably",
"@plugins.command(aliases=\"wyr rather either\") async def wouldyourather(message: discord.Message, opt: options =",
"== \"2\": return 1 choices = list(map(str.lower, choices)) words =",
"\"A total of {0} would **{2}**, while {1} would **{3}**!\".format(",
"**{}** or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied = [] #",
"has replied replied.append(reply.author) # Update the answers in the DB",
"set() # All running would you rather's are in this",
"will ask the questions (if there are any to choose",
"question to the bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] ))",
"asked a question to the bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0,",
"\"Would you rather **{}** or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied",
"are in this set @plugins.argument(\"{open}option ...{close} or/, {open}other option ...{close}[?]\",",
"answers in the DB # We don't care about multiples,",
"= list(map(str.split, choices)) # Go through all words in the",
"in words[0]: return 1 # Invalid choice return None @plugins.command(aliases=\"wyr",
"message.channel.id not in sessions, \"**A would you rather session is",
"{1} would **{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id) # Otherwise,",
"for q in db.data[\"questions\"]: if q[\"choices\"][0] == opt[0] and q[\"choices\"][1]",
"**{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied = [] # Wait for",
"await client.say(message, \"A total of {0} would **{2}**, while {1}",
"return 1 choices = list(map(str.lower, choices)) words = list(map(str.split, choices))",
"option ...{close}[?]\", allow_spaces=True) async def options(arg): \"\"\" Command argument for",
"options = None): \"\"\" Ask the bot if he would",
"option. This accept 1 and 2 as numbers. \"\"\" if",
"the bot ask you. **Examples:** Registering a choice: `!wouldyourather lie",
"choice.lower().split(): if word in words[0] and word not in words[1]:",
"bot: `!wouldyourather`\"\"\" # If there are no options, the bot",
"session is already in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are",
"responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions =",
"try: reply = await client.wait_for_message(timeout=timeout, check=check) # Break on timeout",
"sessions.remove(message.channel.id) # Otherwise, the member asked a question to the",
"word in words[0] and word not in words[1]: return 0",
"== match.group(2).lower(), \"**The choices cannot be the same.**\" return match.group(1),",
"questions (if there are any to choose from) if opt",
"None @plugins.command(aliases=\"wyr rather either\") async def wouldyourather(message: discord.Message, opt: options",
"the bot if he would rather, or have the bot",
"bot will ask the questions (if there are any to",
"Would you rather? This plugin includes would you rather functionality",
"match.group(2).lower(), \"**The choices cannot be the same.**\" return match.group(1), match.group(2)",
"message.channel and m.author not in replied try: reply = await",
"\"\"\" Command argument for receiving two options. \"\"\" match =",
"message, and find any words unique to a choice for",
"random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await client.say(message, \"Would you rather **{}**",
"client.say(message, \"**Entry removed.**\") break else: await client.say(message, \"**Could not find",
"and m.author not in replied try: reply = await client.wait_for_message(timeout=timeout,",
"not in replied try: reply = await client.wait_for_message(timeout=timeout, check=check) #",
"question with the given options. \"\"\" for q in db.data[\"questions\"]:",
"This plugin includes would you rather functionality \"\"\" import asyncio",
"response) # Say the total tallies await client.say(message, \"A total",
"replies from anyone in the channel while True: def check(m):",
"biased) question[\"answers\"][choice] += 1 name = reply.author.display_name response = random.choice(db.data[\"responses\"]).format(name=name,",
"for word in choice.lower().split(): if word in words[0] and word",
"DB # We don't care about multiples, just the amount",
"the chosen option. This accept 1 and 2 as numbers.",
"(yes it will probably be biased) question[\"answers\"][choice] += 1 name",
"would you rather session is already in progress.**\" sessions.add(message.channel.id) assert",
"unique to a choice for word in choice.lower().split(): if word",
"no options, the bot will ask the questions (if there",
"client.say(message, \"A total of {0} would **{2}**, while {1} would",
"check(m): return m.channel == message.channel and m.author not in replied",
"= get_choice(choices, reply.content) if choice is None: continue # Register",
"= random.choice(opt) await client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async",
"*question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the member asked",
"same.**\" return match.group(1), match.group(2) def get_choice(choices: list, choice: str): \"\"\"",
"opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message, \"**Entry removed.**\") break else:",
"you rather session is already in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"],",
"the same.**\" return match.group(1), match.group(2) def get_choice(choices: list, choice: str):",
"Command argument for receiving two options. \"\"\" match = command_pattern.match(arg)",
"pcbot import Config client = plugins.client # type: bot.Client db",
"one!**\" question = random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await client.say(message, \"Would",
"rather **{}** or **{}**?\".format(*choices)) timeout = db.data[\"timeout\"] replied = []",
"0] )) await db.asyncsave() answer = random.choice(opt) await client.say(message, \"**I",
"Ask me one!**\" question = random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await",
"elif word in words[1] and word not in words[0]: return",
"= random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await client.say(message, \"Would you rather",
"# type: bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"],",
"re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() # All running would you rather's",
"None): \"\"\" Ask the bot if he would rather, or",
"{}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message: discord.Message, opt: options): \"\"\"",
"remove(message: discord.Message, opt: options): \"\"\" Remove a wouldyourather question with",
"bot if he would rather, or have the bot ask",
"client.wait_for_message(timeout=timeout, check=check) # Break on timeout except asyncio.TimeoutError: break #",
"the given options. \"\"\" for q in db.data[\"questions\"]: if q[\"choices\"][0]",
"for replies from anyone in the channel while True: def",
"from) if opt is None: assert message.channel.id not in sessions,",
"assert match assert not match.group(1).lower() == match.group(2).lower(), \"**The choices cannot",
"= command_pattern.match(arg) assert match assert not match.group(1).lower() == match.group(2).lower(), \"**The",
"list(map(str.lower, choices)) words = list(map(str.split, choices)) # Go through all",
"@plugins.argument(\"{open}option ...{close} or/, {open}other option ...{close}[?]\", allow_spaces=True) async def options(arg):",
"rather session is already in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There",
"you rather functionality \"\"\" import asyncio import random import re",
"words[1]: return 0 elif word in words[1] and word not",
"assert message.channel.id not in sessions, \"**A would you rather session",
"# Wait for replies from anyone in the channel while",
"numbers. \"\"\" if choice == \"1\": return 0 if choice",
"reply.content) if choice is None: continue # Register that this",
"a question to the bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0]",
"word in choice.lower().split(): if word in words[0] and word not",
"rather either\") async def wouldyourather(message: discord.Message, opt: options = None):",
"await client.say(message, response) # Say the total tallies await client.say(message,",
"# All running would you rather's are in this set",
"choices = question[\"choices\"] await client.say(message, \"Would you rather **{}** or",
"replied try: reply = await client.wait_for_message(timeout=timeout, check=check) # Break on",
"return m.channel == message.channel and m.author not in replied try:",
"find any words unique to a choice for word in",
"author has replied replied.append(reply.author) # Update the answers in the",
"= None): \"\"\" Ask the bot if he would rather,",
"there are no options, the bot will ask the questions",
"functionality \"\"\" import asyncio import random import re import discord",
"you rather? This plugin includes would you rather functionality \"\"\"",
"either\") async def wouldyourather(message: discord.Message, opt: options = None): \"\"\"",
"await client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message:",
"to the bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] )) await",
"are no options, the bot will ask the questions (if",
"two options. \"\"\" match = command_pattern.match(arg) assert match assert not",
"would **{2}**, while {1} would **{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave()",
"# Break on timeout except asyncio.TimeoutError: break # Check if",
"\"\"\" match = command_pattern.match(arg) assert match assert not match.group(1).lower() ==",
"Asking the bot: `!wouldyourather`\"\"\" # If there are no options,",
"the amount (yes it will probably be biased) question[\"answers\"][choice] +=",
"in this set @plugins.argument(\"{open}option ...{close} or/, {open}other option ...{close}[?]\", allow_spaces=True)",
"If there are no options, the bot will ask the",
"None: assert message.channel.id not in sessions, \"**A would you rather",
"ask the questions (if there are any to choose from)",
"from anyone in the channel while True: def check(m): return",
"any words unique to a choice for word in choice.lower().split():",
"set @plugins.argument(\"{open}option ...{close} or/, {open}other option ...{close}[?]\", allow_spaces=True) async def",
"Say the total tallies await client.say(message, \"A total of {0}",
"asyncio.TimeoutError: break # Check if the choice is valid choice",
"word not in words[1]: return 0 elif word in words[1]",
"def get_choice(choices: list, choice: str): \"\"\" Get the chosen option.",
"is None: continue # Register that this author has replied",
"multiples, just the amount (yes it will probably be biased)",
"or/, {open}other option ...{close}[?]\", allow_spaces=True) async def options(arg): \"\"\" Command",
"list(map(str.split, choices)) # Go through all words in the given",
"= [] # Wait for replies from anyone in the",
"**{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the member",
"plugin includes would you rather functionality \"\"\" import asyncio import",
"@wouldyourather.command(aliases=\"delete\", owner=True) async def remove(message: discord.Message, opt: options): \"\"\" Remove",
"of {0} would **{2}**, while {1} would **{3}**!\".format( *question[\"answers\"], *choices))",
"match.group(1).lower() == match.group(2).lower(), \"**The choices cannot be the same.**\" return",
"Otherwise, the member asked a question to the bot else:",
"\"1\": return 0 if choice == \"2\": return 1 choices",
"opt: options): \"\"\" Remove a wouldyourather question with the given",
"...{close}[?]\", allow_spaces=True) async def options(arg): \"\"\" Command argument for receiving",
"return match.group(1), match.group(2) def get_choice(choices: list, choice: str): \"\"\" Get",
"return 0 elif word in words[1] and word not in",
"or be lied to` Asking the bot: `!wouldyourather`\"\"\" # If",
"wouldyourather question with the given options. \"\"\" for q in",
"options. \"\"\" for q in db.data[\"questions\"]: if q[\"choices\"][0] == opt[0]",
"answer = random.choice(opt) await client.say(message, \"**I would {}**!\".format(answer)) @wouldyourather.command(aliases=\"delete\", owner=True)",
"a choice: `!wouldyourather lie or be lied to` Asking the",
"replied = [] # Wait for replies from anyone in",
"db.data[\"timeout\"] replied = [] # Wait for replies from anyone",
"0 if choice == \"2\": return 1 choices = list(map(str.lower,",
"to choose from) if opt is None: assert message.channel.id not",
"answers=[0, 0] )) await db.asyncsave() answer = random.choice(opt) await client.say(message,",
"\"**There are ZERO questions saved. Ask me one!**\" question =",
"and 2 as numbers. \"\"\" if choice == \"1\": return",
"would **{choice}**!\"], questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set()",
"# Check if the choice is valid choice = get_choice(choices,",
"rather's are in this set @plugins.argument(\"{open}option ...{close} or/, {open}other option",
"await db.asyncsave() answer = random.choice(opt) await client.say(message, \"**I would {}**!\".format(answer))",
"command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() # All running would",
"choice is None: continue # Register that this author has",
"== opt[0] and q[\"choices\"][1] == opt[1]: db.data[\"questions\"].remove(q) await db.asyncsave() await",
"words[0]: return 1 # Invalid choice return None @plugins.command(aliases=\"wyr rather",
"\"\"\" Remove a wouldyourather question with the given options. \"\"\"",
"you. **Examples:** Registering a choice: `!wouldyourather lie or be lied",
"\"\"\" for q in db.data[\"questions\"]: if q[\"choices\"][0] == opt[0] and",
"the choice is valid choice = get_choice(choices, reply.content) if choice",
"await db.asyncsave() await client.say(message, \"**Entry removed.**\") break else: await client.say(message,",
"bot else: db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] )) await db.asyncsave() answer",
"db.data[\"questions\"].remove(q) await db.asyncsave() await client.say(message, \"**Entry removed.**\") break else: await",
"that this author has replied replied.append(reply.author) # Update the answers",
"await db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the member asked a question",
"not in words[0]: return 1 # Invalid choice return None",
"= set() # All running would you rather's are in",
"words[1] and word not in words[0]: return 1 # Invalid",
"choice for word in choice.lower().split(): if word in words[0] and",
"the bot: `!wouldyourather`\"\"\" # If there are no options, the",
"have the bot ask you. **Examples:** Registering a choice: `!wouldyourather",
"data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions",
"match.group(1), match.group(2) def get_choice(choices: list, choice: str): \"\"\" Get the",
"all words in the given message, and find any words",
"pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() # All running",
"q in db.data[\"questions\"]: if q[\"choices\"][0] == opt[0] and q[\"choices\"][1] ==",
"already in progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are ZERO questions",
"match = command_pattern.match(arg) assert match assert not match.group(1).lower() == match.group(2).lower(),",
"# Go through all words in the given message, and",
"options, the bot will ask the questions (if there are",
"re import discord import bot import plugins from pcbot import",
"amount (yes it will probably be biased) question[\"answers\"][choice] += 1",
"choices = list(map(str.lower, choices)) words = list(map(str.split, choices)) # Go",
"\"\"\" Ask the bot if he would rather, or have",
"lied to` Asking the bot: `!wouldyourather`\"\"\" # If there are",
"the total tallies await client.say(message, \"A total of {0} would",
"db.data[\"questions\"].append(dict( choices=list(opt), answers=[0, 0] )) await db.asyncsave() answer = random.choice(opt)",
"Ask the bot if he would rather, or have the",
"await client.say(message, \"**Entry removed.**\") break else: await client.say(message, \"**Could not",
"response = random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message, response) # Say",
"choice = get_choice(choices, reply.content) if choice is None: continue #",
"command_pattern.match(arg) assert match assert not match.group(1).lower() == match.group(2).lower(), \"**The choices",
"match.group(2) def get_choice(choices: list, choice: str): \"\"\" Get the chosen",
"in sessions, \"**A would you rather session is already in",
"a choice for word in choice.lower().split(): if word in words[0]",
"through all words in the given message, and find any",
"opt: options = None): \"\"\" Ask the bot if he",
"continue # Register that this author has replied replied.append(reply.author) #",
"it will probably be biased) question[\"answers\"][choice] += 1 name =",
"given message, and find any words unique to a choice",
"in db.data[\"questions\"]: if q[\"choices\"][0] == opt[0] and q[\"choices\"][1] == opt[1]:",
"Update the answers in the DB # We don't care",
"in replied try: reply = await client.wait_for_message(timeout=timeout, check=check) # Break",
"will probably be biased) question[\"answers\"][choice] += 1 name = reply.author.display_name",
"import asyncio import random import re import discord import bot",
"1 and 2 as numbers. \"\"\" if choice == \"1\":",
"questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\") sessions = set() # All",
"choose from) if opt is None: assert message.channel.id not in",
"choice return None @plugins.command(aliases=\"wyr rather either\") async def wouldyourather(message: discord.Message,",
"or have the bot ask you. **Examples:** Registering a choice:",
"me one!**\" question = random.choice(db.data[\"questions\"]) choices = question[\"choices\"] await client.say(message,",
"Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True) command_pattern = re.compile(r\"(.+)(?:\\s+or|\\s*,)\\s+([^?]+)\\?*\")",
"sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are ZERO questions saved. Ask me",
"# Invalid choice return None @plugins.command(aliases=\"wyr rather either\") async def",
"random.choice(db.data[\"responses\"]).format(name=name, NAME=name.upper(), choice=choices[choice]) await client.say(message, response) # Say the total",
"if he would rather, or have the bot ask you.",
"would **{3}**!\".format( *question[\"answers\"], *choices)) await db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the",
"in the DB # We don't care about multiples, just",
"a wouldyourather question with the given options. \"\"\" for q",
"if opt is None: assert message.channel.id not in sessions, \"**A",
"opt is None: assert message.channel.id not in sessions, \"**A would",
"progress.**\" sessions.add(message.channel.id) assert db.data[\"questions\"], \"**There are ZERO questions saved. Ask",
"choice: str): \"\"\" Get the chosen option. This accept 1",
"in words[1] and word not in words[0]: return 1 #",
"rather? This plugin includes would you rather functionality \"\"\" import",
"removed.**\") break else: await client.say(message, \"**Could not find the question.**\")",
"= await client.wait_for_message(timeout=timeout, check=check) # Break on timeout except asyncio.TimeoutError:",
"would rather, or have the bot ask you. **Examples:** Registering",
"This accept 1 and 2 as numbers. \"\"\" if choice",
"replied replied.append(reply.author) # Update the answers in the DB #",
"assert not match.group(1).lower() == match.group(2).lower(), \"**The choices cannot be the",
"and word not in words[1]: return 0 elif word in",
"bot.Client db = Config(\"would-you-rather\", data=dict(timeout=10, responses=[\"**{name}** would **{choice}**!\"], questions=[]), pretty=True)",
"the channel while True: def check(m): return m.channel == message.channel",
"def remove(message: discord.Message, opt: options): \"\"\" Remove a wouldyourather question",
"this author has replied replied.append(reply.author) # Update the answers in",
"the DB # We don't care about multiples, just the",
"db.data[\"questions\"], \"**There are ZERO questions saved. Ask me one!**\" question",
"in words[0] and word not in words[1]: return 0 elif",
"*choices)) await db.asyncsave() sessions.remove(message.channel.id) # Otherwise, the member asked a",
"given options. \"\"\" for q in db.data[\"questions\"]: if q[\"choices\"][0] ==",
"options): \"\"\" Remove a wouldyourather question with the given options.",
"1 # Invalid choice return None @plugins.command(aliases=\"wyr rather either\") async",
"options. \"\"\" match = command_pattern.match(arg) assert match assert not match.group(1).lower()",
"there are any to choose from) if opt is None:"
] |
[
"of the key to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout)",
"level of console output.') parser.add_argument('--version', action='version', version=__version__, help='display the version'",
"subparsers.add_parser('keygen', help='Create a signing key. Not for production use') keygen_parser.add_argument('-t',",
"2.0 (the \"License\"); # you may not use this file",
"the update. The file must be formated as JSON. The",
"is described in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f',",
"more severable elements from the manifest, if present.') sever_parser.add_argument('-m', '--manifest',",
"{} [command] -h for help on each command.'.format(sys.argv[0])) # Add",
"re.split(r'=',e, maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class",
"a manifest.' ' Use {} [command] -h for help on",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"help='display the version' ) subparsers = parser.add_subparsers(dest=\"action\") subparsers.required = True",
"-*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or its",
"on each command.'.format(sys.argv[0])) # Add all top-level commands parser.add_argument('-l', '--log-level',",
"'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large elements to severable",
"levels', type=int, default=2) sever_parser = subparsers.add_parser('sever', help='Remove one or more",
"transform a manifest.' ' Use {} [command] -h for help",
"default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False) return parser def parse_args(self, args=None):",
"use this file except in compliance with the License. #",
"output.') parser.add_argument('--version', action='version', version=__version__, help='display the version' ) subparsers =",
"create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components', default=[]) sign_parser = subparsers.add_parser('sign', help='Sign",
"= subparsers.add_parser('keygen', help='Create a signing key. Not for production use')",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create a signing key.",
"key for a supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'),",
"License. # You may obtain a copy of the License",
"self._make_parser() def _make_parser(self): parser = argparse.ArgumentParser(description = 'Create or transform",
"get_pubkey import json import re def str_to_component(s): types = {",
"suit_tool import __version__ from suit_tool import keygen from suit_tool import",
"in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT',",
"def __init__(self): self.parser = self._make_parser() def _make_parser(self): parser = argparse.ArgumentParser(description",
"private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(),",
"under the License is distributed on an \"AS IS\" BASIS,",
"default='secp256r1', help='The type of the key to generate') keygen_parser.add_argument('-o', '--output-file',",
"License for the specific language governing permissions and # limitations",
"type=argparse.FileType('r'), help='An input file describing the update. The file must",
"its affiliates # # SPDX-License-Identifier: Apache-2.0 # # Licensed under",
"required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append', type=str,",
"metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m',",
"= subparsers.add_parser('pubkey', help='Get the public key for a supplied private",
"subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k',",
"'--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of the key to generate')",
"described in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format',",
"one or more severable elements from the manifest, if present.')",
"hss-lms levels', type=int, default=2) sever_parser = subparsers.add_parser('sever', help='Remove one or",
"keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of the key to",
"= subparsers.add_parser('sever', help='Remove one or more severable elements from the",
"default='info', help='Set the verbosity level of console output.') parser.add_argument('--version', action='version',",
"update. The file must be formated as JSON. The overal",
"action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the public key for",
"eval(x) ]), 'uri' : ('uri', lambda x : str(x.strip('\"'))) }",
"each command.'.format(sys.argv[0])) # Add all top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'],",
"the manifest, if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o',",
"type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s',",
"in compliance with the License. # You may obtain a",
"software # distributed under the License is distributed on an",
"sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements',",
"generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem')",
"type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'),",
"Apache-2.0 # # Licensed under the Apache License, Version 2.0",
"type=int, default=2) sever_parser = subparsers.add_parser('sever', help='Remove one or more severable",
"dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the public key for a",
"y in eval(x) ]), 'uri' : ('uri', lambda x :",
"from suit_tool import __version__ from suit_tool import keygen from suit_tool",
"subparsers.add_parser('sever', help='Remove one or more severable elements from the manifest,",
"to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(),",
"'--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json') get_pubkey_parser",
"-*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM",
"Copyright 2019-2020 ARM Limited or its affiliates # # SPDX-License-Identifier:",
"metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit')",
"required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str)",
"of hss-lms levels', type=int, default=2) sever_parser = subparsers.add_parser('sever', help='Remove one",
"type=str_to_component, dest='components', default=[]) sign_parser = subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m',",
"Use {} [command] -h for help on each command.'.format(sys.argv[0])) #",
"re def str_to_component(s): types = { 'file' : ('file', lambda",
"for a supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True)",
"get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create a",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The number of hss-lms levels', type=int,",
"d class MainArgumentParser(object): def __init__(self): self.parser = self._make_parser() def _make_parser(self):",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append',",
"'--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input file describing the update. The",
"# See the License for the specific language governing permissions",
"type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey',",
"console output.') parser.add_argument('--version', action='version', version=__version__, help='display the version' ) subparsers",
"keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The number of hss-lms",
"dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False) return parser def parse_args(self,",
"language governing permissions and # limitations under the License. #",
"version' ) subparsers = parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser =",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser = subparsers.add_parser('create', help='Create a new",
"metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE',",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json')",
"keygen_parser = subparsers.add_parser('keygen', help='Create a signing key. Not for production",
"with the License. # You may obtain a copy of",
"default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create a signing key. Not for",
"maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class MainArgumentParser(object):",
"# Add all top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set",
"'--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file',",
"type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all',",
": [ str(y) for y in eval(x) ]), 'uri' :",
"types = { 'file' : ('file', lambda x : str(x.strip('\"'))),",
"metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element',",
"help='Set the verbosity level of console output.') parser.add_argument('--version', action='version', version=__version__,",
"compliance with the License. # You may obtain a copy",
"a new manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file',",
"agreed to in writing, software # distributed under the License",
"distributed under the License is distributed on an \"AS IS\"",
"= subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True)",
"-h for help on each command.'.format(sys.argv[0])) # Add all top-level",
"Not for production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type",
"and # limitations under the License. # ---------------------------------------------------------------------------- import sys,",
"required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get",
"express or implied. # See the License for the specific",
"in eval(x) ]), 'uri' : ('uri', lambda x : str(x.strip('\"')))",
"'--levels', help='The number of hss-lms levels', type=int, default=2) sever_parser =",
"except in compliance with the License. # You may obtain",
"required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True)",
"def _make_parser(self): parser = argparse.ArgumentParser(description = 'Create or transform a",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"not use this file except in compliance with the License.",
"writing, software # distributed under the License is distributed on",
"action='store_true', default=False) return parser def parse_args(self, args=None): self.options = self.parser.parse_args(args)",
"required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable',",
"you may not use this file except in compliance with",
"lambda x : str(x.strip('\"'))), # 'desc' : ('component-description', lambda x",
"lambda x : str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v) for k,v",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'),",
"elements to severable fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components', default=[])",
"_make_parser(self): parser = argparse.ArgumentParser(description = 'Create or transform a manifest.'",
"('component-description', lambda x : str(x.strip('\"'))), 'inst' : ('install-id', lambda x",
"json import re def str_to_component(s): types = { 'file' :",
"'file' : ('file', lambda x : str(x.strip('\"'))), # 'desc' :",
"of console output.') parser.add_argument('--version', action='version', version=__version__, help='display the version' )",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"create_parser = subparsers.add_parser('create', help='Create a new manifest') # create_parser.add_argument('-v', '--manifest-version',",
"type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse', help='Parse",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser",
"'--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels',",
"keygen from suit_tool import get_pubkey import json import re def",
"os from suit_tool import __version__ from suit_tool import keygen from",
"import __version__ from suit_tool import keygen from suit_tool import get_pubkey",
"severable fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components', default=[]) sign_parser =",
"get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o',",
"help='An input file describing the update. The file must be",
": str(x.strip('\"'))), 'inst' : ('install-id', lambda x : [ str(y)",
"choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen',",
"utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or",
"the version' ) subparsers = parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser",
"large elements to severable fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components',",
"signing key. Not for production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1',",
"use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of the key",
"overal structure is described in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'),",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"help='Create a new manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i',",
"sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse', help='Parse a",
"the License is distributed on an \"AS IS\" BASIS, #",
"keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l',",
"if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE',",
"subparsers.required = True create_parser = subparsers.add_parser('create', help='Create a new manifest')",
"a supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f',",
"from suit_tool import keygen from suit_tool import get_pubkey import json",
"# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020",
"import sys, argparse, os from suit_tool import __version__ from suit_tool",
"# ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or its affiliates",
"Add all top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the",
"parse_parser = subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'),",
"create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input",
"import json import re def str_to_component(s): types = { 'file'",
"{types[k][0]:types[k][1](v) for k,v in [ re.split(r'=',e, maxsplit=1) for e in",
"default=False) return parser def parse_args(self, args=None): self.options = self.parser.parse_args(args) return",
"'--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the verbosity level of console output.')",
"x : str(x.strip('\"'))), # 'desc' : ('component-description', lambda x :",
"law or agreed to in writing, software # distributed under",
"= True create_parser = subparsers.add_parser('create', help='Create a new manifest') #",
"fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components', default=[]) sign_parser = subparsers.add_parser('sign',",
"__version__ from suit_tool import keygen from suit_tool import get_pubkey import",
"describing the update. The file must be formated as JSON.",
"type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create a signing key. Not",
"severable elements from the manifest, if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE',",
"# # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache",
"__init__(self): self.parser = self._make_parser() def _make_parser(self): parser = argparse.ArgumentParser(description =",
"action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False) return parser",
"type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False) return parser def",
"ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 #",
"top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the verbosity level",
"for k,v in [ re.split(r'=',e, maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''',",
"]), 'uri' : ('uri', lambda x : str(x.strip('\"'))) } d",
"in [ re.split(r'=',e, maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return",
"argparse.ArgumentParser(description = 'Create or transform a manifest.' ' Use {}",
"sever_parser.add_argument('-a', '--all', action='store_true', default=False) return parser def parse_args(self, args=None): self.options",
"metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id',",
"may obtain a copy of the License at # #",
"parser = argparse.ArgumentParser(description = 'Create or transform a manifest.' '",
"metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a',",
"re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class MainArgumentParser(object): def __init__(self): self.parser =",
"('file', lambda x : str(x.strip('\"'))), # 'desc' : ('component-description', lambda",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"be formated as JSON. The overal structure is described in",
"('uri', lambda x : str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v) for",
"may not use this file except in compliance with the",
"action='version', version=__version__, help='display the version' ) subparsers = parser.add_subparsers(dest=\"action\") subparsers.required",
"key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem')",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"import keygen from suit_tool import get_pubkey import json import re",
"this file except in compliance with the License. # You",
"type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m', '--manifest',",
"get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the public key for a supplied",
"type of the key to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'),",
"choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of the key to generate') keygen_parser.add_argument('-o',",
"'uri' : ('uri', lambda x : str(x.strip('\"'))) } d =",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# # Licensed under the Apache License, Version 2.0 (the",
"sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o',",
"version=__version__, help='display the version' ) subparsers = parser.add_subparsers(dest=\"action\") subparsers.required =",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"from suit_tool import get_pubkey import json import re def str_to_component(s):",
"help='Create a signing key. Not for production use') keygen_parser.add_argument('-t', '--type',",
"public key for a supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE',",
"suit_tool import keygen from suit_tool import get_pubkey import json import",
"# 'desc' : ('component-description', lambda x : str(x.strip('\"'))), 'inst' :",
"= argparse.ArgumentParser(description = 'Create or transform a manifest.' ' Use",
"metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large",
"= self._make_parser() def _make_parser(self): parser = argparse.ArgumentParser(description = 'Create or",
"get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser",
"'inst' : ('install-id', lambda x : [ str(y) for y",
"create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input file describing the update.",
"'--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create a signing",
": ('component-description', lambda x : str(x.strip('\"'))), 'inst' : ('install-id', lambda",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j',",
"metavar='FILE', type=argparse.FileType('r'), help='An input file describing the update. The file",
"= parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser = subparsers.add_parser('create', help='Create a",
"'--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser =",
"'--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements', default=[])",
"return parser def parse_args(self, args=None): self.options = self.parser.parse_args(args) return self",
"keygen_parser.add_argument('-l', '--levels', help='The number of hss-lms levels', type=int, default=2) sever_parser",
"# ---------------------------------------------------------------------------- import sys, argparse, os from suit_tool import __version__",
"d = {types[k][0]:types[k][1](v) for k,v in [ re.split(r'=',e, maxsplit=1) for",
"help='Get the public key for a supplied private key.') get_pubkey_parser.add_argument('-k',",
"help='Sign a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key',",
"[ str(y) for y in eval(x) ]), 'uri' : ('uri',",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"file must be formated as JSON. The overal structure is",
"s)]} return d class MainArgumentParser(object): def __init__(self): self.parser = self._make_parser()",
"commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the verbosity level of",
"= subparsers.add_parser('create', help='Create a new manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'],",
": ('file', lambda x : str(x.strip('\"'))), # 'desc' : ('component-description',",
"or implied. # See the License for the specific language",
"the public key for a supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key',",
"'--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file',",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large elements",
"help on each command.'.format(sys.argv[0])) # Add all top-level commands parser.add_argument('-l',",
"or transform a manifest.' ' Use {} [command] -h for",
"lambda x : str(x.strip('\"'))), 'inst' : ('install-id', lambda x :",
"key. Not for production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The",
"to severable fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component, dest='components', default=[]) sign_parser",
"str(x.strip('\"'))), 'inst' : ('install-id', lambda x : [ str(y) for",
"License. # ---------------------------------------------------------------------------- import sys, argparse, os from suit_tool import",
"parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the verbosity level of console",
"(the \"License\"); # you may not use this file except",
"required=True) parse_parser = subparsers.add_parser('parse', help='Parse a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE',",
"argparse, os from suit_tool import __version__ from suit_tool import keygen",
"# you may not use this file except in compliance",
": str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v) for k,v in [",
"return d class MainArgumentParser(object): def __init__(self): self.parser = self._make_parser() def",
"number of hss-lms levels', type=int, default=2) sever_parser = subparsers.add_parser('sever', help='Remove",
"create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large elements to severable fields.') create_parser.add_argument('-c',",
"parser.add_argument('--version', action='version', version=__version__, help='display the version' ) subparsers = parser.add_subparsers(dest=\"action\")",
"import re def str_to_component(s): types = { 'file' : ('file',",
"sys, argparse, os from suit_tool import __version__ from suit_tool import",
"subparsers = parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser = subparsers.add_parser('create', help='Create",
"'--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert",
"key to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format',",
"default=2) sever_parser = subparsers.add_parser('sever', help='Remove one or more severable elements",
"str_to_component(s): types = { 'file' : ('file', lambda x :",
"dest='components', default=[]) sign_parser = subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m', '--manifest',",
"# # Unless required by applicable law or agreed to",
"the verbosity level of console output.') parser.add_argument('--version', action='version', version=__version__, help='display",
"or more severable elements from the manifest, if present.') sever_parser.add_argument('-m',",
"metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The",
"help='Remove one or more severable elements from the manifest, if",
"The file must be formated as JSON. The overal structure",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"' Use {} [command] -h for help on each command.'.format(sys.argv[0]))",
"[command] -h for help on each command.'.format(sys.argv[0])) # Add all",
"Version 2.0 (the \"License\"); # you may not use this",
"default='pem') keygen_parser.add_argument('-l', '--levels', help='The number of hss-lms levels', type=int, default=2)",
"self.parser = self._make_parser() def _make_parser(self): parser = argparse.ArgumentParser(description = 'Create",
"'--add-component', action='append', type=str_to_component, dest='components', default=[]) sign_parser = subparsers.add_parser('sign', help='Sign a",
"default=False, action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the public key",
"formated as JSON. The overal structure is described in README.')",
"sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False)",
"'desc' : ('component-description', lambda x : str(x.strip('\"'))), 'inst' : ('install-id',",
"implied. # See the License for the specific language governing",
": ('uri', lambda x : str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v)",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"affiliates # # SPDX-License-Identifier: Apache-2.0 # # Licensed under the",
"as JSON. The overal structure is described in README.') create_parser.add_argument('-o',",
"x : [ str(y) for y in eval(x) ]), 'uri'",
": str(x.strip('\"'))), # 'desc' : ('component-description', lambda x : str(x.strip('\"'))),",
"---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or its affiliates #",
"by applicable law or agreed to in writing, software #",
"or its affiliates # # SPDX-License-Identifier: Apache-2.0 # # Licensed",
"structure is described in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True)",
"# limitations under the License. # ---------------------------------------------------------------------------- import sys, argparse,",
"choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input file describing",
"type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'),",
"help='The type of the key to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE',",
"def str_to_component(s): types = { 'file' : ('file', lambda x",
"k,v in [ re.split(r'=',e, maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]}",
"str(x.strip('\"'))), # 'desc' : ('component-description', lambda x : str(x.strip('\"'))), 'inst'",
"help='The number of hss-lms levels', type=int, default=2) sever_parser = subparsers.add_parser('sever',",
"sever_parser = subparsers.add_parser('sever', help='Remove one or more severable elements from",
"[ re.split(r'=',e, maxsplit=1) for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d",
"x : str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v) for k,v in",
"help='Convert large elements to severable fields.') create_parser.add_argument('-c', '--add-component', action='append', type=str_to_component,",
"metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse',",
"'--all', action='store_true', default=False) return parser def parse_args(self, args=None): self.options =",
"type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The number",
"= { 'file' : ('file', lambda x : str(x.strip('\"'))), #",
"manifest.' ' Use {} [command] -h for help on each",
"('install-id', lambda x : [ str(y) for y in eval(x)",
"under the License. # ---------------------------------------------------------------------------- import sys, argparse, os from",
") subparsers = parser.add_subparsers(dest=\"action\") subparsers.required = True create_parser = subparsers.add_parser('create',",
"for production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of",
"'--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'],",
"SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version",
"new manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE',",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json') get_pubkey_parser =",
"default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input file describing the",
"sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True)",
"# Copyright 2019-2020 ARM Limited or its affiliates # #",
"present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'),",
"governing permissions and # limitations under the License. # ----------------------------------------------------------------------------",
"= {types[k][0]:types[k][1](v) for k,v in [ re.split(r'=',e, maxsplit=1) for e",
"the specific language governing permissions and # limitations under the",
"'--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) sever_parser.add_argument('-e',",
"'--json-output', default=False, action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the public",
"metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE',",
"applicable law or agreed to in writing, software # distributed",
"# SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License,",
"default=[]) sign_parser = subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE',",
"type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i', '--key-id', metavar='ID',",
"manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False, action='store_true',",
"import get_pubkey import json import re def str_to_component(s): types =",
"in writing, software # distributed under the License is distributed",
"'--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser = subparsers.add_parser('parse', help='Parse a manifest')",
"MainArgumentParser(object): def __init__(self): self.parser = self._make_parser() def _make_parser(self): parser =",
"default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser = subparsers.add_parser('keygen', help='Create",
"str(x.strip('\"'))) } d = {types[k][0]:types[k][1](v) for k,v in [ re.split(r'=',e,",
"True create_parser = subparsers.add_parser('create', help='Create a new manifest') # create_parser.add_argument('-v',",
"supplied private key.') get_pubkey_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) get_pubkey_parser.add_argument('-f', '--output-format',",
"required=True) sever_parser.add_argument('-e', '--element', action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true',",
"the License. # ---------------------------------------------------------------------------- import sys, argparse, os from suit_tool",
"subparsers.add_parser('create', help='Create a new manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1')",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"file describing the update. The file must be formated as",
"# You may obtain a copy of the License at",
"lambda x : [ str(y) for y in eval(x) ]),",
"'--severable', action='store_true', help='Convert large elements to severable fields.') create_parser.add_argument('-c', '--add-component',",
"coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited",
"class MainArgumentParser(object): def __init__(self): self.parser = self._make_parser() def _make_parser(self): parser",
"action='append', type=str_to_component, dest='components', default=[]) sign_parser = subparsers.add_parser('sign', help='Sign a manifest')",
"'--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-i',",
"in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class MainArgumentParser(object): def __init__(self): self.parser",
"sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True)",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true',",
"create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit', 'suit-debug',",
"must be formated as JSON. The overal structure is described",
"help='Parse a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output',",
"choices=['debug','info','warning','exception'], default='info', help='Set the verbosity level of console output.') parser.add_argument('--version',",
"parse_parser.add_argument('-j', '--json-output', default=False, action='store_true', dest='json') get_pubkey_parser = subparsers.add_parser('pubkey', help='Get the",
"the License for the specific language governing permissions and #",
"JSON. The overal structure is described in README.') create_parser.add_argument('-o', '--output-file',",
"elements from the manifest, if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'),",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"{ 'file' : ('file', lambda x : str(x.strip('\"'))), # 'desc'",
"all top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info', help='Set the verbosity",
"either express or implied. # See the License for the",
"'suit-debug', 'json'], default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large elements to",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"'--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The number of hss-lms levels',",
"permissions and # limitations under the License. # ---------------------------------------------------------------------------- import",
"README.') create_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) create_parser.add_argument('-f', '--format', metavar='FMT', choices=['suit',",
"'--element', action='append', type=str, dest='elements', default=[]) sever_parser.add_argument('-a', '--all', action='store_true', default=False) return",
"manifest') # create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'),",
"limitations under the License. # ---------------------------------------------------------------------------- import sys, argparse, os",
"2019-2020 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the key to generate') keygen_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout) keygen_parser.add_argument('-f',",
"verbosity level of console output.') parser.add_argument('--version', action='version', version=__version__, help='display the",
"= 'Create or transform a manifest.' ' Use {} [command]",
"The overal structure is described in README.') create_parser.add_argument('-o', '--output-file', metavar='FILE',",
"manifest, if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sever_parser.add_argument('-o', '--output-file',",
"for y in eval(x) ]), 'uri' : ('uri', lambda x",
"default=sys.stdout) keygen_parser.add_argument('-f', '--output-format', choices=keygen.OutputFormaters.keys(), default='pem') keygen_parser.add_argument('-l', '--levels', help='The number of",
": ('install-id', lambda x : [ str(y) for y in",
"command.'.format(sys.argv[0])) # Add all top-level commands parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info',",
"production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(), default='secp256r1', help='The type of the",
"'Create or transform a manifest.' ' Use {} [command] -h",
"# create_parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An",
"---------------------------------------------------------------------------- import sys, argparse, os from suit_tool import __version__ from",
"\"License\"); # you may not use this file except in",
"for e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class MainArgumentParser(object): def",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"'--manifest-version', choices=['1'], default='1') create_parser.add_argument('-i', '--input-file', metavar='FILE', type=argparse.FileType('r'), help='An input file",
"default='suit') create_parser.add_argument('-s', '--severable', action='store_true', help='Convert large elements to severable fields.')",
"action='store_true', help='Convert large elements to severable fields.') create_parser.add_argument('-c', '--add-component', action='append',",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"x : str(x.strip('\"'))), 'inst' : ('install-id', lambda x : [",
"subparsers.add_parser('pubkey', help='Get the public key for a supplied private key.')",
"str(y) for y in eval(x) ]), 'uri' : ('uri', lambda",
"a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) sign_parser.add_argument('-k', '--private-key', metavar='FILE',",
"for help on each command.'.format(sys.argv[0])) # Add all top-level commands",
"from the manifest, if present.') sever_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True)",
"sign_parser = subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'),",
"'--key-id', metavar='ID', type=str) sign_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), required=True) parse_parser =",
"input file describing the update. The file must be formated",
"You may obtain a copy of the License at #",
"a manifest') parse_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True) parse_parser.add_argument('-j', '--json-output', default=False,",
"required=True) get_pubkey_parser.add_argument('-f', '--output-format', choices=get_pubkey.OutputFormaters.keys(), default='pem') get_pubkey_parser.add_argument('-o', '--output-file', metavar='FILE', type=argparse.FileType('wb'), default=sys.stdout)",
"suit_tool import get_pubkey import json import re def str_to_component(s): types",
"= subparsers.add_parser('sign', help='Sign a manifest') sign_parser.add_argument('-m', '--manifest', metavar='FILE', type=argparse.FileType('rb'), required=True)",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"} d = {types[k][0]:types[k][1](v) for k,v in [ re.split(r'=',e, maxsplit=1)",
"a signing key. Not for production use') keygen_parser.add_argument('-t', '--type', choices=keygen.KeyGenerators.keys(),",
"e in re.split(r''',\\s*(?=[\"']?[a-zA-Z0-9_-]+[\"']?=)''', s)]} return d class MainArgumentParser(object): def __init__(self):",
"Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # #"
] |
[
"def worker(name: str) -> None: print(f'Started worker {name}') worker_time =",
"print(f'{name} worker finished in {worker_time} seconds') if __name__ == '__main__':",
"time.sleep(worker_time) print(f'{name} worker finished in {worker_time} seconds') if __name__ ==",
"worker {name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished",
"-> None: print(f'Started worker {name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time)",
"{worker_time} seconds') if __name__ == '__main__': process_names = [f'computer_{i}' for",
"import time from multiprocessing import Pool def worker(name: str) ->",
"= [f'computer_{i}' for i in range(15)] pool = Pool(processes=5) pool.map(worker,",
"for i in range(15)] pool = Pool(processes=5) pool.map(worker, process_names) #",
"finished in {worker_time} seconds') if __name__ == '__main__': process_names =",
"worker finished in {worker_time} seconds') if __name__ == '__main__': process_names",
"worker(name: str) -> None: print(f'Started worker {name}') worker_time = random.choice(range(1,",
"= random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished in {worker_time} seconds')",
"<reponame>y2ghost/study import random import time from multiprocessing import Pool def",
"if __name__ == '__main__': process_names = [f'computer_{i}' for i in",
"process_names = [f'computer_{i}' for i in range(15)] pool = Pool(processes=5)",
"multiprocessing import Pool def worker(name: str) -> None: print(f'Started worker",
"5)) time.sleep(worker_time) print(f'{name} worker finished in {worker_time} seconds') if __name__",
"== '__main__': process_names = [f'computer_{i}' for i in range(15)] pool",
"worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished in {worker_time}",
"'__main__': process_names = [f'computer_{i}' for i in range(15)] pool =",
"None: print(f'Started worker {name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name}",
"str) -> None: print(f'Started worker {name}') worker_time = random.choice(range(1, 5))",
"[f'computer_{i}' for i in range(15)] pool = Pool(processes=5) pool.map(worker, process_names)",
"time from multiprocessing import Pool def worker(name: str) -> None:",
"__name__ == '__main__': process_names = [f'computer_{i}' for i in range(15)]",
"i in range(15)] pool = Pool(processes=5) pool.map(worker, process_names) # pool.terminate()",
"seconds') if __name__ == '__main__': process_names = [f'computer_{i}' for i",
"{name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished in",
"Pool def worker(name: str) -> None: print(f'Started worker {name}') worker_time",
"import Pool def worker(name: str) -> None: print(f'Started worker {name}')",
"random import time from multiprocessing import Pool def worker(name: str)",
"random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker finished in {worker_time} seconds') if",
"import random import time from multiprocessing import Pool def worker(name:",
"in {worker_time} seconds') if __name__ == '__main__': process_names = [f'computer_{i}'",
"from multiprocessing import Pool def worker(name: str) -> None: print(f'Started",
"print(f'Started worker {name}') worker_time = random.choice(range(1, 5)) time.sleep(worker_time) print(f'{name} worker"
] |
[
"an adjusted train dataset | a. Remove test instances from",
"path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom)",
"Phase 4: Get metric axe per model: min(|FVC_true - FVC_predicted|,",
"print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard",
"sort=False) filename_population = 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build",
"== True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset",
"= pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric import math from",
"= c return resultFunction if testMode == True: # Set",
"fitting scope: (1) Data: FVC predictions; (2) Probability density function",
"to include and their corresponding metrics ModelToInclude = IDList_columns[2:] ##",
"== 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from",
"Adjust train dataset | Phase 3: Create an adjusted train",
"a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns)",
"train dataset | Phase 2: Get submission instances from train",
"range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get submission data as",
"submission file | FVC FVCDataList = [] for k in",
"= FVCDataList # Get submission data as required in submission",
"'test.csv' test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get models",
"= list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists =",
"DataFrameToInclude]) # nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype",
"samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling",
"model: (-1 * differential * 2^0.5 / SDC ) -",
"Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage = round(Percentage,6) DICOMFilePercentage_list =",
"Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction[1]) print(\"=========================================\")",
"| Phase 3: Get correlative files_list = os.listdir(path_output) try: maxNumber",
"= len(IDcases_List) for i in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4]",
"train dataset (an aleatory grouping of IDs; tree-copy task) from",
"distutils.dir_util import create_tree from distutils.dir_util import remove_tree from distutils.dir_util import",
"FVCDataList = [] for k in range(0,submissionNumber_range): for j in",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome = path_ProductType + 'outcome/'",
"= list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] #",
"= len(submission_dataset.index) for i in metricLabels: j = 0 while",
"Model path = path_ProductType + 'outcome/' filename = 'result.csv' y_pred",
"testMode == True: ProductType = 'prototype' PydicomMode = True reportMode",
"additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset",
"(template) import numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if",
"date reportDate = date.today() print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' )",
"Get test dataset (tree-copy task) ## Assumption: The complete test",
"IDList) # Get confidence measure | Phase 2: Get standard-deviation-clipped",
"of Train dataset (just information) available in file: \", filename_sampling)",
"result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) #",
"print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom",
"print(\"=========================================\") print(\"-Sampling Size :\", samplingSize, \"%\") print(\"-Test Mode : False\")",
"FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List =",
"train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index",
"= 0 ## Get submission files | Phase 4: Get",
"+ k + '/' path_destination_unitary = path_destination + k +",
"shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\") print(\"Shape Parameter - Laplace Log",
"os os.chdir(path_ProductType + 'outcome/') # Get result data and test",
"'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import",
"= [] for k in range(0,instancesPopulation): for l in IDList:",
"if ProductType == 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' #",
"+ [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary]",
"if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m] for n in range",
"Tester.py): Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size",
"an adjusted train dataset | b. Get Transferring data from",
"based on IDs\") print(\"-Train dataset percentage to sample (base): \",",
"\", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input",
"== True): import pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1",
"models # ========================================= # Purpose: Build an input dataset to",
"File saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type of the dataset\")",
"= submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) #",
"== []): shapeParameter_dictionary = {} shapeParameter = 0.126074 MLModelList =",
"| Phase 4: Create an adjusted train dataset | e.",
"import log1p for k in IDList: for i in metric_lists:",
"Get IDs to test path = path_ProductType filename = 'test.csv'",
"Aleatory Sampling ========================================= Purpose: Build an aleatory sample given a",
"[Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary",
"aleatory grouping of IDs; tree-copy task) from distutils.dir_util import create_tree",
"|FVC_true - FVC_predicted| ## Metric - Part 1: |FVC_true -",
"tolerance. if(accuracy == True): accuracy = 'Equal case' else: accuracy",
"Pydicom mode pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape",
"has been computed deeming the following data fitting scope: (1)",
"[DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list",
"submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy",
"in metricLabels: j = 0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000)",
"[train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List +",
"i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude #",
"ML models ========================================= Purpose: Build an input dataset to be",
"shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3",
"= np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1",
"reportMode = False Test mode 2 | Function Report testMode",
"= Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j",
"productType and splitType if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/'",
"# Set Pydicom mode pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode)",
"SDC: Standard Deviation Clipped ## Metric - Part 2: min(|FVC_true",
"for competition\") print(\"=========================================\") for k in Population_DataFrame_IDToSample: path_source_unitary = path_source",
"+ 1 ## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) #",
"c = 0.12607421874999922 for every instance in the oject of",
"Purpose: Build a submission CSV file (Stacking solution case) Raw",
"print(\"=========================================\") print(\"Location of Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File saved",
"import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True: print(\"=========================================\") print(\"Building",
"result data and test dataset import pandas as pd if(pydicomMode",
"IDs to test import os import pandas as pd ##",
"as required in submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List =",
"= [] Percent_List = [] Age_List = [] Sex_List =",
"filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a",
"required in submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy()",
"resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\")",
"= pd.DataFrame(data = shapeParameter_dictionary, index = IDList) # Get confidence",
"file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5]",
"{submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary)",
"within a tolerance. if(accuracy == True): accuracy = 'Equal case'",
"'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset =",
"test dataset is copied. from distutils.dir_util import create_tree from distutils.dir_util",
"Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) #",
"distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if",
"and splitType if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if",
"Phase 2: Get submission instances from train dataset instancesPopulation =",
"Basics testMode = True reportMode = False Test mode 2",
"default per model and ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary",
"Function 2: Success\") print(\"=========================================\") \"\"\" ========================================= Function 3: Dataset builder",
"instancesPopulation = len(train_dataset.Patient) indexList = [] for i in IDList:",
"ML outcome ========================================= Purpose: Build a submission CSV file (Stacking",
"= Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal",
"os.chdir(path_ProductType) # Get train dataset and test dataset import pandas",
"submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted",
"= np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5,",
"Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]]",
"\", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset (just information) available in",
"Get ID list of the test dataset IDList = list(test_dataset.Patient)",
"Get shape parameter visualization for loglaplace Raw code reference (see",
"100 Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary",
"Scenario to replace NaN values: Average FVC for a given",
"builder (Stacking solution case) to process with ML models =========================================",
"path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/'",
"InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation =",
"an adjusted train dataset | d. Add common values to",
"str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum",
"\"\"\" Created on Mon Sep 7 11:48:59 2020 @author: mazal",
"sharey=False, figsize=(32, 24)) ## Get IDs to test import os",
"processed with an stacking solution Raw code reference (see Tester.py):",
"dataset) | Phase 1: Get pydicom train dataset if(PydicomMode ==",
"= False \"\"\" testMode = False reportMode = False \"\"\"",
"= 'Equal case' else: accuracy = 'Unequal case' # Set",
"| Phase 1: Get shape Parameter DataFrame by default ##",
"= path_source + ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list",
"FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]]",
"filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset",
"scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and its",
"k in SDModel_List: itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL",
"#ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1)",
"into adjusted train dataset if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient)",
"= path_destination + k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode",
"FileNotFoundError: import distutils.ccompiler path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ##",
"loglaplace.stats(c, moments='mvsk') # Display the probability density function (pdf): x",
"loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals,",
"SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 * differential /",
"(including percentage). ## Improvement: (3) # of other registers (not",
"Pydicom image-processing solution # Raw code reference (see Tester.py): 15",
"train dataset | Phase 3: Create an adjusted train dataset",
"Tester.py): Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os import pandas",
"3: Create an adjusted train dataset | c. Update the",
"Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data =",
"\", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the outcome expressed",
"train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode == True: print(\"=========================================\") print(\"Function",
"Parameter DataFrame by default ## When shapeParameter_DataFrame==[], parameter c =",
"replace NaN values: Average FVC for a given Patient averageFVC",
"sampling import os import pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/'",
"Get submission files | Phase 5: Build Files for i",
"train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan)",
"maxNumber+1 except ValueError: nextNumber = 0 ## Get submission files",
"print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation",
"list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:]",
"= submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances | Phase 4: Sort",
"Check Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy =",
"i in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get submission",
"= 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling",
"concern. c value has been computed deeming the following data",
"= pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get models model_List =",
"print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of sample: Aleatory based on",
"result, outcomes are as follows:\") print(\"result[0] -> Dataframe for Population\")",
"Inputs\") print(\"=========================================\") print(\"-Sampling Size :\", samplingSize, \"%\") print(\"-Test Mode :",
"(1) the source path of the train data; (2) the",
"l + 1 plt.tight_layout() plt.show() resultFunction = c return resultFunction",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType",
"Shape Parameter: It amounts to c = 0.12607421874999922 for every",
"= submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k]",
"index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed:",
"path_destination_test + l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode ==",
"'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\")",
"= repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] =",
"submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances | Phase 4:",
"metric = metric_part1 + metric_part2 submission_dataset[i][j] = metric # Result",
"submission_dataset[i][j] = metric # Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame",
"for i in ModelToInclude: filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename)",
"print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") \"\"\"",
"submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m]",
"measure | Phase 1: Get shape Parameter DataFrame by default",
"== i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step",
"import os os.chdir(path_ProductType) # Get train dataset and test dataset",
"Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \",",
"False if (example == True): import pandas as pd shapeParameter_IDList",
"a Sampling dataset | Phase 1: Determine: (1) the source",
"pd # Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType",
"## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling",
"True) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5)",
"= pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted =",
"print(\"ID tree copied: \",l) if (testMode == False and reportMode",
"= metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence measure |",
"print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") # \"\"\" #",
"try: os.chdir(path_destination) GetCreation = True except FileNotFoundError: GetCreation = False",
"submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode if testMode == True:",
"np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array",
"'outcome/') # Get result data and test dataset import pandas",
"plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24)) ## Get IDs to",
"metric_part1 = -1* 2**0.5 * differential / SDC metric_part2 =",
"========================================= Purpose: Build a submission CSV file (Stacking solution case)",
"## Build a DataFrame with standard-deviation-clipped values given an ID",
"path_destination_unitary = path_destination + k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if",
"## Improvement: (3) # of other registers (not related to",
"- FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List =",
"include and their corresponding metrics ModelToInclude = IDList_columns[2:] ## Get",
"numy = numy + 1 numy = 0 # Get",
"train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset | Phase 3: Create",
"adjusted train dataset if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient",
"print(\"Standard Deviation Clipped - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\")",
"Kaggle for competition and a sample size Raw code reference",
"Build a Sampling dataset | Phase 2: Build dataset using",
"files_list = os.listdir(path_output) try: maxNumber = max(files_list) maxNumber = maxNumber[:-4]",
"a tolerance. if(accuracy == True): accuracy = 'Equal case' else:",
"copied. from distutils.dir_util import create_tree from distutils.dir_util import remove_tree from",
"- FVC_pred| if(pydicomMode == True): variableNumber = 10 else: variableNumber",
"3: Success\") print(\"=========================================\") return resultFunction if testMode == True: ProductType",
"path_output = path_ProductType +'outcome/' if(PydicomMode == False): filename_output = 'train_adjusted.csv'",
"= pd.read_csv('sample_submission.csv') # Get submission data as required in submission",
"# Raw code reference (see Tester.py): 15 # \"\"\" #",
"dataset | Phase 3: Create an adjusted train dataset |",
"MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j in MLModelList:",
"4: Get metric axe per model: min(|FVC_true - FVC_predicted|, 1000)",
"ax = plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24)) ## Get",
"True: ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode)",
"(just information) available in file: \", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\")",
"for i in ID_List: k = 0 for j in",
"sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (adjustment):",
"result Function 3: Success\") print(\"=========================================\") return resultFunction if testMode ==",
"tree-copy task) from distutils.dir_util import create_tree from distutils.dir_util import remove_tree",
"= plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24)) ## Get IDs",
"= os.listdir(path_source_test) for l in IDList_test: path_source_unitary = path_source +",
"print(\"-Train dataset percentage to sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset",
"reference (see Tester.py): Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy",
"os.chdir(path_destination) submissionList = os.listdir(path_destination) number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv'",
"= submission_dataset.join(metric_DataFrame) # Get confidence measure | Phase 5: Get",
"raw data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') #",
"dataset of Kaggle for competition and a sample size Raw",
"2: Include values from train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode",
"using the following features from train data: (1) ID; (2)",
"2: Create directory try: path_output = path_ProductType + 'submission/' os.chdir(path_output)",
"resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\") print(\"Shape Parameter -",
"result_dataset.loc[IDList_index] # Get submission instances | Phase 3: Extract duplicated",
"instancesToInclude_List: # Get instance to transfer InstanceToInclude_Patient = i InstanceToInclude_Week",
"tree copied: \",l) if (testMode == False and reportMode ==",
"submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission data as required in",
"ID | k: SD_Clipped_(ML Model) numy = numy + 1",
"dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function 1: Success\") print(\"=========================================\")",
"corresponding metrics ModelToInclude = IDList_columns[2:] ## Get submission files |",
"submission instances from result dataset IDList_index = [] IDList_columns =",
"Set Product Type and its corresponding path # if ProductType",
"Report Mode if reportMode == True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\")",
"= IDList) # Get confidence measure | Phase 2: Get",
"\"\"\" ========================================= Function 4: Submission dataset builder (Stacking solution case)",
"ID and Model path = path_ProductType + 'outcome/' filename =",
"print(\"=========================================\") print(\"Location of Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File saved",
"[3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient",
"DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex = newIndex +",
"to test import os import pandas as pd ## Set",
"dataset and test dataset import pandas as pd filename_trainDataset =",
"Set datum in submission file FVCDataList = FVCDataList + [datum]",
"and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m] =",
"values to submission dataset given those from the test dataset",
"Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 =",
"Function 3: Success\") print(\"=========================================\") return resultFunction if testMode == True:",
"DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex']",
"metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i in metricLabels:",
"an ID and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy()",
"= 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data",
"submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m]",
"= path_source + l + '/' path_destination_unitary = path_destination_test +",
"if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index indexToComplete",
"| Phase 2: Extract submission instances from result dataset IDList_index",
"= False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function",
"Phase 3: Get an aleatory grouping of IDs (just tags)",
"saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\")",
"for l in MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] =",
"in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks",
"create_tree(path_destination_test,[]) if testMode == True: print(\"=========================================\") print(\"Building the Test Dataset",
"indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric import math",
"data: (1) ID; (2) # of DICOM files per ID",
"FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get submission data",
"| Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\")",
"l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer",
"+ l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True:",
"Success\") print(\"=========================================\") # \"\"\" # ========================================= # Function : Dataset",
"deeming the following data fitting scope: (1) Data: FVC predictions;",
"= timesCopy + 1 else: # Additional instances to include",
"print(\"-Population of Train dataset (just information) available in file: \",",
"scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set",
"timesCopy = timesCopy + 1 else: # Additional instances to",
"train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset | Phase 3: Create",
"file | FVC FVCDataList = [] for k in range(0,submissionNumber_range):",
"= list(test_dataset.Patient) ## Get models model_List = ['Random Forest', 'Lasso',",
"i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient",
"solution but including Pydicom image-processing solution # Raw code reference",
"PydicomMode = True reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode,",
"False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function Report\")",
"in MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame",
"========================================= Function 3: Dataset builder (Stacking solution case) to process",
"reportMode = False \"\"\" ========================================= Function 1: Aleatory Sampling =========================================",
"assigned by default per model and ID if (shapeParameter_DataFrame ==",
"IDList_index_dictionary[i] = itemToInclude # Get submission instances | Phase 2:",
"= Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\")",
"| b. Get Transferring data from train dataset instanceToTrasferList_index =",
"parameter visualization for loglaplace Raw code reference (see Tester.py): Test",
"metric_differential = list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame",
"Build an aleatory sample given a train dataset of Kaggle",
"InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2",
"IDList): referenceWeek = submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n]",
"# \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product",
"renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode):",
"j = 0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j =",
"Get probabilities from predicted values grouping by ID and Model",
"adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List,",
"i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient ==",
"0 for j in model_List: # Data Fit task #r",
"# Add new instance ## Get repeatable instances repeatableInstance1 =",
"Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files",
"Transferring data from train dataset instanceToTrasferList_index = [] for k",
"print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom",
"models to include and their corresponding metrics ModelToInclude = IDList_columns[2:]",
"= sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] /",
"in IDList_test: path_source_unitary = path_source + l + '/' path_destination_unitary",
"resultFunction3[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\")",
"math import log1p for k in IDList: for i in",
"= samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary)",
"train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n]",
"the location path of the sampling import os import pandas",
"stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\")",
"{} for j in MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j])",
"path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset =",
"train_dataset.index[j] indexList = indexList + [indexToInclude] # Adjust train dataset",
"# Set working directory import os os.chdir(path_ProductType + 'outcome/') #",
"frozen pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen",
"Dataset of Kaggle for competition\") print(\"=========================================\") for k in Population_DataFrame_IDToSample:",
"os.listdir(path_output) try: maxNumber = max(files_list) maxNumber = maxNumber[:-4] maxNumber =",
"print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \",",
"# Report Mode if reportMode == True: print(\"=========================================\") print(\"Function Report\")",
"submission dataset (template) import numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data",
"else: accuracy = 'Unequal case' # Set title title =",
"list(test_dataset.Patient) ## Get models model_List = ['Random Forest', 'Lasso', 'Gradient",
"with an stacking solution Raw code reference (see Tester.py): Test",
"+ [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index')",
"dataset | Phase 4: Create an adjusted train dataset |",
"import pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/'",
"samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\")",
"= train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN",
"= str('Probability density function for loglaplace'+'\\n'+i + '\\n' + j",
"matplotlib.pyplot as plt fig, ax = plt.subplots(4, 5, sharex=False, sharey=False,",
"submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission files | Phase 2:",
"path_source + ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list =",
"8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os import pandas as pd",
"'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train",
"samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame =",
"= list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation",
"for i in metric_lists: for j in list(indexPerID_DataFrame[k]): differential =",
"testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\")",
"== False and reportMode == True): from datetime import date",
"(2) the location path of the sampling import os import",
"dataset | Phase 3: Get train dataset (an aleatory grouping",
"in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List =",
"Purpose: Build an aleatory sample given a train dataset of",
"compute for i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index)",
"k in IDList: for i in metric_lists: for j in",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType +",
"SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0 from",
"testMode == True: ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2",
"Mode if reportMode == True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\")",
"{} shapeParameter = 0.126074 MLModelList = IDList_columns[2:] for l in",
"for j in ID_List: for k in SDModel_List: itemToInclude =",
"[shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = IDList) #",
"= list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists =",
"scipy.stats import loglaplace import matplotlib.pyplot as plt fig, ax =",
"Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes",
"k = 0 for j in model_List: # Data Fit",
"range(0,ID_list_range): path_ID = path_source + ID_list[i] + '/' DICOMFile_list_unitary =",
"DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation']",
"'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report",
"is ID | k: SD_Clipped_(ML Model) numy = numy +",
"required in submission file | Confidence CONDataList = [] for",
"= [] DICOMFileNumber_list = [] for i in range(0,ID_list_range): path_ID",
"files | Phase 3: Get correlative files_list = os.listdir(path_output) try:",
"= 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset =",
"round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame",
"train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes",
"the submission dataset with the transferring data in b. submission_dataset_range",
"= 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array =",
"Tester.py): Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy as np",
"if train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index",
"'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files | Phase 3: Get",
"and their corresponding metrics ModelToInclude = IDList_columns[2:] ## Get submission",
"SDC) metric = metric_part1 + metric_part2 submission_dataset[i][j] = metric #",
"= loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index",
"0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete]",
"'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome =",
"submission data as required in submission file | FVC FVCDataList",
"a must-usage of a log-laplace distribution (i.e. Laplace Log Likelihood)",
"# j: index is ID | k: SD_Clipped_(ML Model) numy",
"'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset =",
"(% of the train population) samplingSize = 5 # Build",
"pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')",
"an input dataset to be processed with an stacking solution",
"'O'}).dtypes # Get CSV file path_output = path_ProductType +'outcome/' if(PydicomMode",
"submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and",
"a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file",
"'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType == 'sampling': # path_ProductType =",
"print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") return resultFunction",
"filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset",
"2020 @author: mazal \"\"\" \"\"\" ========================================= Support functions of pydicom",
"pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get models model_List = ['Random",
"import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode",
"print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") #",
"path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType if ProductType",
"= str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set",
"os import pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test =",
"Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List =",
"given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC",
"instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"+ list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get submission instances |",
"'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType)",
"by Weeks (ascending) and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset",
"== 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType",
"# Get submission instances | Phase 3: Extract duplicated instances",
"| Phase 4: Get models to include and their corresponding",
"= [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted =",
"= str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber",
"label='frozen pdf') # Generate random numbers: r = loglaplace.rvs(c1, loc=0,",
"of the sampling import os import pandas as pd path_source",
"print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function 1: Success\") print(\"=========================================\") \"\"\" =========================================",
"submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy +",
"FVC FVCDataList = [] for k in range(0,submissionNumber_range): for j",
"= train_dataset.index[j] indexList = indexList + [indexToInclude] # Adjust train",
"the following data fitting scope: (1) Data: FVC predictions; (2)",
"submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {} ###",
"= 'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1*",
"as required in submission file | Confidence CONDataList = []",
"# Build a Sampling dataset | Phase 1: Determine: (1)",
"DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame =",
"FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get",
"= Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List",
"path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType == 'sampling': #",
"-1* 2**0.5 * differential / SDC metric_part2 = -1 *",
"train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to",
"Grouping task k = 0 l = 0 for i",
"and test dataset import pandas as pd filename_trainDataset = 'train.csv'",
"========================================= Function 5: Get parameters given a must-usage of a",
"Regressor'] for j in IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j])",
"accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) # Returns True",
"(Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ##",
"'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType ==",
"pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex = newIndex + 1 ##",
"== False): filename_output = 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output)",
"= 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get",
"instances | Phase 4: Sort submission instances by Weeks (ascending)",
"FVC_predicted|, 1000) ## SDC: Standard Deviation Clipped ## Metric -",
"b. Get Transferring data from train dataset instanceToTrasferList_index = []",
"dataset | a. Remove test instances from train dataset and",
"moments # mean, var, skew, kurt = loglaplace.stats(c, moments='mvsk') #",
"if(PydicomMode == False): filename_output = 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv'",
"submission CSV file (Stacking solution case) Raw code reference (see",
"os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list",
"DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template",
"= trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\")",
"Phase 1: Get pydicom train dataset if(PydicomMode == True): filename_pydicom",
"k = 0 l = 0 for i in ID_List:",
"from train dataset instancesPopulation = len(train_dataset.Patient) indexList = [] for",
"columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np",
"+ '/' path_destination_unitary = path_destination + k + '/' create_tree(path_destination_unitary,[])",
"Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List =",
"standard_deviation_clipped = max(standard_deviation, 70) ## Build a DataFrame with standard-deviation-clipped",
"for l in IDList_test: path_source_unitary = path_source + l +",
"values from train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode == True):",
"1: Aleatory Sampling ========================================= Purpose: Build an aleatory sample given",
"transfer InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation",
"= 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv'",
"= shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL)",
"instances | Phase 1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary =",
"| Phase 3: Get train dataset (an aleatory grouping of",
"0 from scipy.stats import loglaplace for j in ID_List: for",
"c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') # Freeze the distribution and",
"date.today() print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\")",
"= list(test_dataset.Patient) IDList_index_dictionary = {} for i in IDList: itemToInclude",
"'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary,",
"Submission dataset builder (Stacking solution case) after ML outcome =========================================",
"= -1 * math.log1p(2**0.5 * SDC) metric = metric_part1 +",
"= rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum in submission",
"'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType if ProductType == 'population':",
"2: Get standard-deviation-clipped per instance ## Metric - Part 1:",
"loglaplace'+'\\n'+i + '\\n' + j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title)",
"confidence measure | Phase 4: Get metric axe per model:",
"standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan)",
"= pd.DataFrame(data=metric_dictionary) # Get confidence measure | Phase 4: Get",
"confidence measure | Phase 3: Get metric axe per model:",
"measure | Phase 2: Get standard-deviation-clipped per instance ## Metric",
"measure | Phase 4: Get metric axe per model: min(|FVC_true",
"rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template as a",
"= True) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\")",
"= list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] =",
"on IDs\") print(\"-Train dataset percentage to sample (base): \", round(abs(samplingSize),6),\"%\")",
"testMode = False reportMode = False \"\"\" testMode = False",
"IDcases_List: # Get datum in raw data IDlabel_rawFile = str(j)+str('_FVC')",
"Get submission data as required in submission file submissionNumber_range =",
"17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy as np from scipy.stats",
"Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample",
"== True: print(\"=========================================\") print(\"Building the Test Dataset given the Test",
"= 'prototype' PydicomMode = True reportMode = False resultFunction3 =",
"= abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude = 'metric_'+j",
"path = path_ProductType filename = 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List",
"Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o in range(0,submission_dataset_range):",
"submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array",
"submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index'])",
"IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i in range",
"for k in SDModel_List: itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j]",
"NaN values: Average FVC for a given Patient averageFVC =",
"Get submission files | Phase 1: Get submission file template",
"CSV file path_output = path_ProductType +'outcome/' if(PydicomMode == False): filename_output",
"Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary =",
"\"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set Product Type",
"stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product Type and its corresponding",
"submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset",
"InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0]",
"print(\"=========================================\") print(\"-Type of sample: Aleatory based on IDs\") print(\"-Train dataset",
"Calculate a few first moments # mean, var, skew, kurt",
"Build a Sampling dataset | Phase 3: Get train dataset",
"a Sampling dataset | Phase 3: Get train dataset (an",
"### Step 3: Compute metric import math from math import",
"a Sampling dataset | Phase 4: Get test dataset (tree-copy",
"= os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary)",
"print(resultFunction4[1]) print(\"Standard Deviation Clipped - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2])",
"if testMode == True: print(\"=========================================\") print(\"Building the Test Dataset given",
"| Confidence CONDataList = [] for k in range(0,submissionNumber_range): for",
"Get confidence measure | Phase 5: Get metric axe per",
"len(ID_list) DICOMFile_list = [] DICOMFileNumber_list = [] for i in",
"scope: (1) Data: FVC predictions; (2) Probability density function as",
"- FVC_predicted| ## Metric - Part 1: |FVC_true - FVC_pred|",
"i in ModelToInclude: filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns",
"dataset (just information) available in file: \", filename_sampling) print(\"=========================================\") print(\"(2)",
": False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of sample: Aleatory",
"submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range",
"path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset |",
"as required in submission file | FVC FVCDataList = []",
"y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c",
"# nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient':",
"submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files | Phase 1: Get submission",
"histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits",
"str(InstanceToInclude_ImageType) else: # Add new instance ## Get repeatable instances",
"create_tree from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination)",
"InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add new instance ##",
"# # Set Product Type and its corresponding path #",
"= 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template)",
"# Set title title = str('Probability density function for loglaplace'+'\\n'+i",
"\"\"\" # ========================================= # Function : Dataset builder 2 (Stacking",
"from predicted values grouping by ID and Model path =",
"loglaplace.pdf(x, c, loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product",
"\", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\")",
"random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal <=",
"common values to submission dataset given those from the test",
"True if two arrays are element-wise equal within a tolerance.",
"(1) Data: FVC predictions; (2) Probability density function as follows",
"of the train data; (2) the location path of the",
"must-usage of a log-laplace distribution (i.e. Laplace Log Likelihood) =========================================",
"= train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1",
"'prototype' PydicomMode = True reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType,",
"loc=0, scale=1, size=1000) # And compare the histogram: #ax[k,l].hist(r, density=True,",
") - ln(2^0.5 * SCD) ## metric per instance ##",
"== 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling':",
"timesCopy + 1 else: # Additional instances to include Patient_List",
"mazal \"\"\" \"\"\" ========================================= Support functions of pydicom (Not sourced)",
"with pydicom train dataset) | Phase 2: Include values from",
"| Phase 2: Create directory try: path_output = path_ProductType +",
"= InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get",
"l = 0 for i in ID_List: k = 0",
"builder 2 (Stacking solution case) to process with ML models",
"train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train dataset with",
"(0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get submission data as required",
"dataset import pandas as pd filename_trainDataset = 'train.csv' train_dataset =",
"Dataset builder 2 (Stacking solution case) to process with ML",
"indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance",
"# Get confidence measure | Phase 2: Get standard-deviation-clipped per",
"reportMode if testMode == True: samplingSize = 5 resultFunction1 =",
"from scipy.stats import loglaplace import matplotlib.pyplot as plt fig, ax",
"of Kaggle for competition\") print(\"=========================================\") for k in Population_DataFrame_IDToSample: path_source_unitary",
"(Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' #",
"Get confidence measure | Phase 1: Get shape Parameter DataFrame",
"submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames",
"ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType if",
"dataset | Phase 3: Get an aleatory grouping of IDs",
"Type and its corresponding path if ProductType == 'population': path_ProductType",
"Adjust train dataset | Phase 2: Get submission instances from",
"['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for",
"in file: \", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the",
"dataset given those from the test dataset (Features: Age, Sex,",
"a log-laplace distribution (i.e. Laplace Log Likelihood) ========================================= Purpose: Get",
"{'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population",
"ID_List: k = 0 for j in model_List: # Data",
"Build a DataFrame with standard-deviation-clipped values given an ID and",
"train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes",
"os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template as",
"l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID",
"print(\"-Type of sample: Aleatory based on IDs\") print(\"-Train dataset percentage",
"-*- \"\"\" Created on Mon Sep 7 11:48:59 2020 @author:",
"import pandas as pd if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv'",
"dataset (an aleatory grouping of IDs; tree-copy task) from distutils.dir_util",
"distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number =",
"in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). \"\"\"",
"Part 2: min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List =",
"log1p for k in IDList: for i in metric_lists: for",
"example = False if (example == True): import pandas as",
"== i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary",
"def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (% of the train",
"if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy ==",
"4: Submission dataset builder (Stacking solution case) after ML outcome",
"= Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample",
"Sep 7 11:48:59 2020 @author: mazal \"\"\" \"\"\" ========================================= Support",
"def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set Product Type and",
"for l in IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index =",
"= 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission files |",
"print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function",
"os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list = []",
"Function 2: Submission Builder ========================================= Purpose: Build a submission CSV",
"= list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ##",
"input dataset to be processed with an stacking solution but",
"[3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3]",
"| Phase 3: Get an aleatory grouping of IDs (just",
"amounts to c = 0.12607421874999922 for every instance in the",
"print(\"=========================================\") \"\"\" ========================================= Function 5: Get parameters given a must-usage",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from predicted values grouping by",
"## Get IDs to test import os import pandas as",
"try: maxNumber = max(files_list) maxNumber = maxNumber[:-4] maxNumber = int(maxNumber)",
"datum in raw data IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k]",
"= 'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True)",
"Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals",
"fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence']",
"2: min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index)",
"indexList = indexList + [indexToInclude] # Adjust train dataset |",
"\", filename_population) print(\"-Sample of Train dataset (just information) available in",
"pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population",
"'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if",
"reportMode, testMode): # Set Product Type and its corresponding path",
"[] for k in range(0,submissionNumber_range): for j in IDcases_List: #",
"in ID_List: for k in SDModel_List: itemToInclude = CParameter_List[numy] c",
"index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset |",
"indexList = [] for i in IDList: for j in",
"distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True: print(\"=========================================\")",
"Get submission files | Phase 4: Get models to include",
"= len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: # Get instance to",
"'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train dataset",
"Build a Sampling dataset | Phase 1: Determine: (1) the",
"= pd.read_csv(path+filename) ## Get IDs to test path = path_ProductType",
"corresponding path # if ProductType == 'population': # path_ProductType =",
"list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get submission instances | Phase",
"scale=1, size=1000) # And compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled',",
"maxNumber = maxNumber[:-4] maxNumber = int(maxNumber) nextNumber = maxNumber+1 except",
"# Build a Sampling dataset | Phase 3: Get train",
"test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template) import numpy",
"1: Success\") print(\"=========================================\") \"\"\" ========================================= Function 2: Submission Builder =========================================",
"= 'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType if ProductType ==",
"ID; (2) # of DICOM files per ID (including percentage).",
"Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list =",
"Kaggle for competition\") print(\"=========================================\") for k in Population_DataFrame_IDToSample: path_source_unitary =",
"Phase 1: Get submission file template filename = 'sample_submission.csv' submissionFile",
"submission dataset with the transferring data in b. submission_dataset_range =",
"of other registers (not related to DICOM files) os.chdir(path_source) ID_list",
"Outputs\") print(\"=========================================\") print(\"-Type of sample: Aleatory based on IDs\") print(\"-Train",
"k = k + 1 l = l + 1",
"= IDcases_List[i][:-4] # Get submission data as required in submission",
"dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o",
"train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation':",
"Function 4: Success\") print(\"=========================================\") \"\"\" ========================================= Function 5: Get parameters",
"if(submission_dataset.Patient[o] in IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]):",
"3: Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission",
"= train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust train",
"print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test",
"= path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset | Phase",
"j in MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential =",
"## Get submission files | Phase 2: Create directory try:",
"Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy as np from",
"True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient)",
"itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0,",
"testMode == True: print(\"ID tree copied: \",k) # Build a",
"the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\")",
"== True): from datetime import date reportDate = date.today() print(\"=========================================\")",
"pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train",
"IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i in range (0,IDcases_List_range): IDcases_List[i]",
"Purpose: Build a submission CSV file Raw code reference (see",
"= IDList_columns[2:] for l in MLModelList: keyShapeParameter = 'c Parameter_'+l",
"for competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test) for l in IDList_test:",
"\"\"\" ========================================= Support functions of pydicom (Not sourced) ========================================= Purpose:",
"distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if",
"i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList = indexList +",
"in metric_lists: for j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label",
"models ========================================= Purpose: Build an input dataset to be processed",
"Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage = round(Percentage,6)",
"oject of concern. c value has been computed deeming the",
"{'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data",
"= len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample):",
"for loglaplace Raw code reference (see Tester.py): Test 17 \"\"\"",
"file CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList #",
"== True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get",
"'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for j",
"Get submission files | Phase 3: Get correlative files_list =",
"submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure | Phase 1: Get",
"ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working",
"submission files | Phase 4: Get models to include and",
"ProductType = 'prototype' # ShapeParameter_Dataframe example = False if (example",
"Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe example =",
"fvc_array submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv' path_output = path_ProductType",
"max(files_list) maxNumber = maxNumber[:-4] maxNumber = int(maxNumber) nextNumber = maxNumber+1",
"if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType",
"a. Remove test instances from train dataset and reset index",
"= pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template) import numpy as",
"indexToInclude = train_dataset.index[j] indexList = indexList + [indexToInclude] # Adjust",
"range(0,submissionNumber_range): for j in IDcases_List: # Get datum in raw",
"else: variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {}",
"to be processed with an stacking solution Raw code reference",
"instance ## differential = min(|FVC_true - FVC_predicted|, 1000) ## SDC:",
"== True): accuracy = 'Equal case' else: accuracy = 'Unequal",
"= 0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1",
"Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List =",
"- Part 1: |FVC_true - FVC_pred| if(pydicomMode == True): variableNumber",
"| c. Update the submission dataset with the transferring data",
"SDC_Label = 'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 =",
"Boosting', 'Stacking Regressor'] for j in IDList: IDList_index = IDList_index",
"== True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/'",
"| Phase 3: Create an adjusted train dataset | c.",
"parameter c = 0.126074 is assigned by default per model",
"np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) # Returns True if two",
"in ID_List: k = 0 for j in model_List: #",
"len(submission_dataset.index) for i in metricLabels: j = 0 while (j<instancesNumber):",
"It amounts to c = 0.12607421874999922 for every instance in",
"= [] Sex_List = [] SmokingStatus_List = [] for m",
"samplingSize = 5 # Build a Sampling dataset | Phase",
"and a sample size Raw code reference (see Tester.py): Test",
"Log Likelihood) ========================================= Purpose: Get shape parameter visualization for loglaplace",
"the adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List,",
"(3) # of other registers (not related to DICOM files)",
"of the test dataset IDList = list(test_dataset.Patient) # Adjust train",
"an aleatory grouping of IDs (just tags) import random Population_DataFrame_IndexToSample=[]",
"(tree-copy task) ## Assumption: The complete test dataset is copied.",
"c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1 # #",
"loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And compare the histogram: #ax[k,l].hist(r,",
"print(\"=========================================\") IDList_test = os.listdir(path_source_test) for l in IDList_test: path_source_unitary =",
"train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) #",
"i in ID_List: k = 0 for j in model_List:",
"num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') # Freeze",
"Get confidence measure | Phase 4: Get metric axe per",
"DICOM files per ID (including percentage). ## Improvement: (3) #",
"stacking solution Raw code reference (see Tester.py): Test 15 \"\"\"",
"keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) #",
"of a log-laplace distribution (i.e. Laplace Log Likelihood) ========================================= Purpose:",
"file template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') #",
"of DICOM files per ID (including percentage). ## Improvement: (3)",
"4: Sort submission instances by Weeks (ascending) and reset index",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks ==",
"# And compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best',",
"print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\")",
"+ [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List",
"print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function 1: Success\") print(\"=========================================\") \"\"\"",
"submission dataset given those from the test dataset (Features: Age,",
"(adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (fitted): \",",
"data; (2) the location path of the sampling import os",
"submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset | Phase 1:",
"test dataset IDList = list(test_dataset.Patient) # Adjust train dataset |",
"train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add new",
"'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes",
"dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\")",
"CONDataList = [] for k in range(0,submissionNumber_range): for j in",
"Generate random numbers: r = loglaplace.rvs(c1, loc=0, scale=1, size=1000) #",
"for loglaplace'+'\\n'+i + '\\n' + j + ' | Accuracy:'+accuracy)",
"path_ID = path_source + ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID)",
"solution case) after ML outcome ========================================= Purpose: Build a submission",
"= 0 l = 0 for i in ID_List: k",
"from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[])",
"import numpy as np from scipy.stats import loglaplace import matplotlib.pyplot",
"random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample +",
"= pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset |",
"= submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure",
"= result_dataset.loc[IDList_index] # Get submission instances | Phase 3: Extract",
"train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train dataset with pydicom train",
"j: index is ID | k: SD_Clipped_(ML Model) numy =",
"case) to process with ML models ========================================= Purpose: Build an",
"= j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence measure |",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data",
"print(\"Test result Function 4: Success\") print(\"=========================================\") \"\"\" ========================================= Function 5:",
"as plt fig, ax = plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32,",
"Age_List = [] Sex_List = [] SmokingStatus_List = [] for",
"= pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex = newIndex + 1",
"Part 1: |FVC_true - FVC_pred| if(pydicomMode == True): variableNumber =",
"'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances | Phase",
"1: Get index per ID to compute for i in",
"print(\"Input File saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type of the",
"nextNumber = nextNumber + 1 return resultFunction if testMode ==",
"number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame,",
"Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]]",
"train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') #",
"IDs (just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal =",
"= train_dataset_adjusted.drop(columns='index') # Adjust train dataset with pydicom train dataset)",
"\",l) if (testMode == False and reportMode == True): from",
"template filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission",
"= list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber =",
"= list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats",
"train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList = indexList + [indexToInclude] #",
"# if ProductType == 'sampling': # path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/'",
"## Get models model_List = ['Random Forest', 'Lasso', 'Gradient Boosting',",
"False and reportMode == True): from datetime import date reportDate",
"5: Get parameters given a must-usage of a log-laplace distribution",
"{} for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame =",
"mean, var, skew, kurt = loglaplace.stats(c, moments='mvsk') # Display the",
"- Part 1: standard_deviation_clipped = max(standard_deviation, 70) ## Build a",
"indexPerID_dictionary = {} ### Step 1: Get index per ID",
"print(\"=========================================\") print(\"Test result Function 2: Success\") print(\"=========================================\") \"\"\" ========================================= Function",
"ID (including percentage). ## Improvement: (3) # of other registers",
"print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction[1])",
"repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5",
"testMode == True: print(\"=========================================\") print(\"Building the Test Dataset given the",
"= InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] =",
"FVC_predicted| ## Metric - Part 1: |FVC_true - FVC_pred| if(pydicomMode",
"in submission file | FVC FVCDataList = [] for k",
"plt fig, ax = plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24))",
"\"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product Type",
"## Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks']",
"Tester.py): Test 17 About the Shape Parameter: It amounts to",
"print(\"result[2] -> Test Mode\") print(\"result[3] -> Rerport Mode\") print(\"=========================================\") return",
"SmokingStatus_List = [] for m in range (0,submission_dataset_range): timesCopy =",
"= list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient) for i",
"# Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission",
"raw data IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum =",
"= train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode == True: print(\"=========================================\")",
"Metric - Part 1: standard_deviation_clipped = max(standard_deviation, 70) ## Build",
"randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not in",
"'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\")",
"list(test_dataset.Patient) IDList_index_dictionary = {} for i in IDList: itemToInclude =",
"submission file | Confidence CONDataList = [] for k in",
"= random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample",
"in raw data IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum",
"(see Tester.py): Test 15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode):",
"filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission files",
"'outcome/' filename = 'result.csv' y_pred = pd.read_csv(path+filename) ## Get IDs",
"submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence",
"Metric - Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns)",
"= [] for m in range (0,submission_dataset_range): timesCopy = 0",
"'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5",
"Add common values to submission dataset given those from the",
"train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy",
"Create an adjusted train dataset | d. Add common values",
"Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] =",
"Get submission dataset (template) import numpy as np path_resources =",
"in submission file FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC'] =",
"sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset (just information)",
"input dataset to be processed with an stacking solution Raw",
"'Equal case' else: accuracy = 'Unequal case' # Set title",
"including Pydicom image-processing solution # Raw code reference (see Tester.py):",
"0.126074 is assigned by default per model and ID if",
"datetime import date reportDate = date.today() print(\"=========================================\") print(\"Function Report |",
"= InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] =",
"np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6,",
"= round(datum,0) # Set datum in submission file CONDataList =",
"m in range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in IDList):",
"train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation':",
"available in file: \", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being",
"And compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False)",
"[] FVC_List = [] Percent_List = [] Age_List = []",
"and display the frozen pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x),",
"differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:] SDC =",
"print(\"=========================================\") print(\"Building the Test Dataset given the Test Dataset of",
"given the Test Dataset of Kaggle for competition\") print(\"=========================================\") IDList_test",
"samplingSize, \"%\") print(\"-Test Mode : False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\")",
"round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset (just information) available in file:",
"in instancesToInclude_List: # Get instance to transfer InstanceToInclude_Patient = i",
"False reportMode = False \"\"\" testMode = False reportMode =",
"True): import pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 =",
"size=1000) # And compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2)",
"[] for m in range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m]",
"for i in instancesToInclude_List: # Get instance to transfer InstanceToInclude_Patient",
"train dataset with pydicom train dataset) | Phase 2: Include",
"= path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset | Phase",
"# Function Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode if",
"Purpose: Create support functions for the pydicom project \"\"\" \"\"\"",
"Outcomes:\") print(\"=========================================\") print(\"Being the outcome expressed under the variable result,",
"per instance ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000)",
"= standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List",
"testMode, reportMode if testMode == True: samplingSize = 5 resultFunction1",
"Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber =",
"list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List)",
"|FVC_true - FVC_pred| if(pydicomMode == True): variableNumber = 10 else:",
"= 0.126074 is assigned by default per model and ID",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling",
"= -1* 2**0.5 * differential / SDC metric_part2 = -1",
"== i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient",
"alpha=0.6, label='loglaplace pdf') # Freeze the distribution and display the",
"train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1 else: # Additional instances",
"= {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] =",
"reportMode == True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0])",
"DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list +",
"loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1 # # Calculate",
"indexList + [indexToInclude] # Adjust train dataset | Phase 3:",
"* SDC) metric = metric_part1 + metric_part2 submission_dataset[i][j] = metric",
"for i in IDList: for j in range(0,instancesPopulation): if i",
"return resultFunction if testMode == True: ProductType = 'prototype' PydicomMode",
"+ [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset | Phase 3: Create",
"the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\")",
"[] Week_List = [] FVC_List = [] Percent_List = []",
"list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put",
"of the train population) samplingSize = 5 # Build a",
"its corresponding path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/'",
"= True Commisionning mode testMode = False reportMode = False",
"as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function 2: Success\") print(\"=========================================\")",
"c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4",
"as pd if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset",
"== 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory",
"submission instances from train dataset instancesPopulation = len(train_dataset.Patient) indexList =",
"Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\")",
"\"\"\" Test mode 1 | Basics testMode = True reportMode",
"ID_List = list(test_dataset.Patient) ## Get models model_List = ['Random Forest',",
"a Sampling dataset | Phase 2: Build dataset using the",
"train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust train dataset",
"print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") \"\"\" =========================================",
"## SDC: Standard Deviation Clipped ## Metric - Part 2:",
"to be processed with an stacking solution but including Pydicom",
"Set Product Type and its corresponding path if ProductType ==",
"Population_DataFrame_IDToSample: path_source_unitary = path_source + k + '/' path_destination_unitary =",
"c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary",
"+ ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list",
"be processed with an stacking solution but including Pydicom image-processing",
"raw data IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum =",
"'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ## Grouping task k =",
"data IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0)",
"Kaggle for competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test) for l in",
"1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary = {} for i",
"= os.listdir(path_output) try: maxNumber = max(files_list) maxNumber = maxNumber[:-4] maxNumber",
"Accuracy:'+accuracy) ax[k,l].set_title(title) k = k + 1 l = l",
"filename_output = 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function",
"== True: ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 =",
"Raw code reference (see Tester.py): Test 17 About the Shape",
"sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j:",
"histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x')",
"min(|FVC_true - FVC_predicted|, 1000) ## metric per instance ## Metric",
"instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step 1: Get",
"Sampling Dataset given the Train Dataset of Kaggle for competition\")",
"i in metricLabels: j = 0 while (j<instancesNumber): metric_DataFrame[i][j] =",
"dataset if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType",
"in range(0,instancesPopulation): for l in IDList: if train_dataset.Patient[k] == l:",
"File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data",
"InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance into train_dataset_adjusted",
"submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv' path_output",
"Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction3[2]) print(\"=========================================\")",
"lw=2, label='frozen pdf') # Generate random numbers: r = loglaplace.rvs(c1,",
"Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population =",
"and the adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List,",
"True Commisionning mode testMode = False reportMode = False \"\"\"",
"train dataset with pydicom train dataset) | Phase 1: Get",
"* 2^0.5 / SDC ) - ln(2^0.5 * SCD) ##",
"as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 =",
"SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List",
"Mon Sep 7 11:48:59 2020 @author: mazal \"\"\" \"\"\" =========================================",
"sample given a train dataset of Kaggle for competition and",
"IDList_test: path_source_unitary = path_source + l + '/' path_destination_unitary =",
"pandas as pd # Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' #",
"len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List = []",
"Put instance into train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"from scipy.stats import loglaplace for j in ID_List: for k",
"TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j]",
"pdf') # Generate random numbers: r = loglaplace.rvs(c1, loc=0, scale=1,",
"Size :\", samplingSize, \"%\") print(\"-Test Mode : False\") print(\"=========================================\") print(\"(2)",
"instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer",
"= train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario",
"the sampling import os import pandas as pd path_source =",
"index is ID | k: SD_Clipped_(ML Model) numy = numy",
"str('Probability density function for loglaplace'+'\\n'+i + '\\n' + j +",
"print(\"result[3] -> Rerport Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode",
"the variable result, outcomes are as follows:\") print(\"result[0] -> Dataframe",
"l = l + 1 plt.tight_layout() plt.show() resultFunction = c",
"aleatory sample given a train dataset of Kaggle for competition",
"(shapeParameter_DataFrame == []): shapeParameter_dictionary = {} shapeParameter = 0.126074 MLModelList",
"= Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List",
"PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File",
"newIndex + 1 ## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude])",
"n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] ==",
"source path of the train data; (2) the location path",
"np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv'",
"correlative files_list = os.listdir(path_output) try: maxNumber = max(files_list) maxNumber =",
"[] for k in range(0,instancesPopulation): for l in IDList: if",
"Phase 3: Create an adjusted train dataset | d. Add",
"Confidence CONDataList = [] for k in range(0,submissionNumber_range): for j",
"dataset | d. Add common values to submission dataset given",
"Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC #",
"try: path_output = path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError: import",
"metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence measure",
"shape parameter visualization for loglaplace Raw code reference (see Tester.py):",
"= [] for k in range(0,submissionNumber_range): for j in IDcases_List:",
"CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save",
"pd if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset =",
"Parameter: It amounts to c = 0.12607421874999922 for every instance",
"following data fitting scope: (1) Data: FVC predictions; (2) Probability",
"ID_list_range = len(ID_list) DICOMFile_list = [] DICOMFileNumber_list = [] for",
"newIndex = len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: # Get instance",
"0 l = 0 for i in ID_List: k =",
"\"\"\" ========================================= Function 1: Aleatory Sampling ========================================= Purpose: Build an",
"train dataset | d. Add common values to submission dataset",
"file Raw code reference (see Tester.py): Test 8 \"\"\" def",
"MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame =",
"= False if (example == True): import pandas as pd",
"[indexToInclude] # Adjust train dataset | Phase 3: Create an",
"if GetCreation == False: from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination)",
"by ID and Model path = path_ProductType + 'outcome/' filename",
"= train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset | Phase 3:",
"ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome",
"def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product Type and its",
"IDs\") print(\"-Train dataset percentage to sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train",
"# ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\") print(\"Shape",
"3: Compute metric import math from math import log1p for",
"dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\")",
"train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode == True): instancesToInclude_List =",
"dataset | c. Update the submission dataset with the transferring",
"IDList = list(test_dataset.Patient) # Adjust train dataset | Phase 2:",
"= path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files |",
"submission_dataset.join(metric_DataFrame) # Get confidence measure | Phase 5: Get metric",
"return resultFunction if testMode == True: # Set Product type",
"pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame = []",
"== True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex =",
"Get CSV file path_output = path_ProductType +'outcome/' if(PydicomMode == False):",
"Get standard-deviation-clipped per instance ## Metric - Part 1: standard_deviation_clipped",
"ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities",
"adjusted train dataset | a. Remove test instances from train",
"= True reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode,",
"maxNumber[:-4] maxNumber = int(maxNumber) nextNumber = maxNumber+1 except ValueError: nextNumber",
"Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1])",
"import date reportDate = date.today() print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/'",
"competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test) for l in IDList_test: path_source_unitary",
"[train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index')",
"\", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of",
"4: Get test dataset (tree-copy task) ## Assumption: The complete",
"{} for i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] =",
"5, sharex=False, sharey=False, figsize=(32, 24)) ## Get IDs to test",
"probabilities from predicted values grouping by ID and Model path",
"# Get train dataset and test dataset import pandas as",
"type ProductType = 'prototype' # ShapeParameter_Dataframe example = False if",
"code reference (see Tester.py): Test 15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode,",
"== l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index]",
"repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0]",
"metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary",
"testMode = True) print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\")",
"value has been computed deeming the following data fitting scope:",
"sharex=False, sharey=False, figsize=(32, 24)) ## Get IDs to test import",
"# Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete]",
"j in IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset =",
"Get models model_List = ['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking",
"copied: \",l) if (testMode == False and reportMode == True):",
"= CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save file",
"Phase 1: Get ID list of the test dataset IDList",
"'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output = path_ProductType +",
"= submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m]",
"round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population",
"Get an aleatory grouping of IDs (just tags) import random",
"## Get submission files | Phase 4: Get models to",
"p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o]",
"# Adjust train dataset | Phase 1: Get ID list",
"'Stacking Regressor'] ## Grouping task k = 0 l =",
"train data; (2) the location path of the sampling import",
"='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame",
"Get pydicom train dataset if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv'",
"IDList_columns = ['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking",
"pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data",
"SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in",
"submission_dataset = result_dataset.loc[IDList_index] # Get submission instances | Phase 3:",
"path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1",
"= loglaplace.stats(c, moments='mvsk') # Display the probability density function (pdf):",
"CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save file |",
"= len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list}",
"+ [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List",
"Phase 3: Get correlative files_list = os.listdir(path_output) try: maxNumber =",
"standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 * differential / SDC metric_part2",
"reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\")",
"Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function 4:",
"return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode == True: samplingSize",
"else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN')",
"Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os import pandas as",
"the following features from train data: (1) ID; (2) #",
"\"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os import pandas as pd #",
"= k + 1 l = l + 1 plt.tight_layout()",
"GetCreation == False: from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList",
"pd.DataFrame(data=metric_dictionary) # Get confidence measure | Phase 4: Get metric",
"import os import pandas as pd ## Set Product Type",
"Metric - Part 2: min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient)",
"pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3]",
"are element-wise equal within a tolerance. if(accuracy == True): accuracy",
"| Function Report testMode = False reportMode = True Commisionning",
"instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer =",
"[3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random",
"0.5, 0.999], c) accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c))",
"'/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary",
"project \"\"\" \"\"\" Test mode 1 | Basics testMode =",
"0.126074 MLModelList = IDList_columns[2:] for l in MLModelList: keyShapeParameter =",
"solution case) to process with ML models ========================================= Purpose: Build",
"r = np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c =",
"1: |FVC_true - FVC_pred| if(pydicomMode == True): variableNumber = 10",
"submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset]",
"Get submission instances | Phase 2: Extract submission instances from",
"import loglaplace import matplotlib.pyplot as plt fig, ax = plt.subplots(4,",
"= numy + 1 numy = 0 # Get confidence",
"import os import pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test",
"filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array",
"Success\") print(\"=========================================\") \"\"\" ========================================= Function 4: Submission dataset builder (Stacking",
"Build Files for i in ModelToInclude: filename = 'sample_submission.csv' submissionFile",
"= pd.read_csv(path_ProductType+filename) ## Get submission files | Phase 2: Create",
"for i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude",
"True: ProductType = 'prototype' PydicomMode = True reportMode = False",
"task) from distutils.dir_util import create_tree from distutils.dir_util import remove_tree from",
"reportMode == True): from datetime import date reportDate = date.today()",
"= 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/'",
"list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] =",
"= list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats import loglaplace for",
"metric per instance ## Metric - Part 2: min(|FVC_true -",
"pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population)",
"len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step 1: Get index per",
"= [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary =",
"== i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"variableNumber = 10 else: variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:])",
"Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample +",
"path_ProductType + 'outcome/' filename = 'result.csv' y_pred = pd.read_csv(path+filename) ##",
"samplingDataset_DataFrame, testMode, reportMode if testMode == True: samplingSize = 5",
"InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame",
"if (testMode == False and reportMode == True): from datetime",
"as np from scipy.stats import loglaplace import matplotlib.pyplot as plt",
"== i].Weeks)): # Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient",
"print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File saved as:\") print(\"=========================================\")",
"train dataset and reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index #",
"'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode",
"instance ## Metric - Part 1: standard_deviation_clipped = max(standard_deviation, 70)",
"for j in MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential",
"var, skew, kurt = loglaplace.stats(c, moments='mvsk') # Display the probability",
"+ '\\n' + j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k",
"Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\")",
"in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy",
"# Put instance into train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function 2: Success\") print(\"=========================================\") \"\"\" =========================================",
"Function 4: Success\") print(\"=========================================\") # \"\"\" # ========================================= # Function",
"-*- coding: utf-8 -*- \"\"\" Created on Mon Sep 7",
"the train population) samplingSize = 5 # Build a Sampling",
"percentage). ## Improvement: (3) # of other registers (not related",
"Get confidence measure | Phase 3: Get metric axe per",
"3: Dataset builder (Stacking solution case) to process with ML",
"print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \", ProductType)",
"path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome =",
"= path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True except FileNotFoundError: GetCreation",
"= {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling =",
"= 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/'",
"'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test =",
"= {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = []",
"dataset | Phase 1: Get ID list of the test",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling dataset | Phase 2:",
"# Get instance to transfer InstanceToInclude_Patient = i InstanceToInclude_Week =",
"Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and its corresponding path if",
"instances | Phase 3: Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks'])",
"Raw code reference (see Tester.py): 15 # \"\"\" # def",
"competition and a sample size Raw code reference (see Tester.py):",
"Metric - Part 1: |FVC_true - FVC_pred| if(pydicomMode == True):",
"rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Generate random numbers: r",
"IDcases_List: # Get datum in raw data IDlabel_rawFile = str(j)+str('_CON')",
"standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List =",
"from train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode == True): instancesToInclude_List",
"distutils.dir_util.mkpath(path_output) ## Get submission files | Phase 3: Get correlative",
"Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result Function 4: Success\")",
"per ID (including percentage). ## Improvement: (3) # of other",
"\",k) # Build a Sampling dataset | Phase 4: Get",
"code reference (see Tester.py): Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import",
"== i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"in IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index]",
"(fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset (just information) available",
"= shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame = [] #",
"a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] =",
"'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True):",
"train_dataset_adjusted.drop(columns='index') # Adjust train dataset with pydicom train dataset) |",
"newIndex = newIndex + 1 ## Concatenate DataFrame train_dataset_adjusted =",
"stacking solution but including Pydicom image-processing solution # Raw code",
"k + '/' path_destination_unitary = path_destination + k + '/'",
"Phase 4: Get test dataset (tree-copy task) ## Assumption: The",
"0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n]",
"path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome = path_ProductType",
"randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample =",
"process with ML models ========================================= Purpose: Build an input dataset",
"i in metric_lists: for j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j]",
"print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode:",
"## Metric - Part 1: standard_deviation_clipped = max(standard_deviation, 70) ##",
"= list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j in MLModelList: metric_differential",
"if testMode == True: print(\"ID tree copied: \",l) if (testMode",
"Create an adjusted train dataset | c. Update the submission",
"by default ## When shapeParameter_DataFrame==[], parameter c = 0.126074 is",
"1000) ## metric per instance ## Metric - Part 2:",
"- Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber",
"the Test Dataset given the Test Dataset of Kaggle for",
"= i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient",
"grouping by ID and Model path = path_ProductType + 'outcome/'",
"instances from result dataset IDList_index = [] IDList_columns = ['Patient',",
"case' else: accuracy = 'Unequal case' # Set title title",
"range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] ==",
"(Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' #",
"IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame",
"in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:]",
"in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] =",
"resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission",
"# Set outcome path_outcome = path_ProductType + 'outcome/' # Get",
"in range(0,ID_list_range): path_ID = path_source + ID_list[i] + '/' DICOMFile_list_unitary",
"follows (staistical function in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c,",
"pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission",
"the frozen pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2,",
"Product Type and its corresponding path if ProductType == 'population':",
"to process with ML models # ========================================= # Purpose: Build",
"distribution (i.e. Laplace Log Likelihood) ========================================= Purpose: Get shape parameter",
"print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\")",
"(testMode == False and reportMode == True): from datetime import",
"computed deeming the following data fitting scope: (1) Data: FVC",
"'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode if testMode ==",
"list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step 1:",
"as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes)",
"ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') #",
"Success\") print(\"=========================================\") \"\"\" ========================================= Function 2: Submission Builder ========================================= Purpose:",
"[train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset",
"= len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List =",
"dataset (template) import numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/'",
"False \"\"\" testMode = False reportMode = False \"\"\" =========================================",
"list(test_dataset.Patient) # Adjust train dataset | Phase 2: Get submission",
"to include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List",
"two arrays are element-wise equal within a tolerance. if(accuracy ==",
"= False \"\"\" ========================================= Function 1: Aleatory Sampling ========================================= Purpose:",
"standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {}",
"| Phase 3: Create an adjusted train dataset | b.",
"IDList = list(test_dataset.Patient) IDList_index_dictionary = {} for i in IDList:",
"c value has been computed deeming the following data fitting",
"given the Train Dataset of Kaggle for competition\") print(\"=========================================\") for",
"= CONDataList # Save file | Get directory path_destination =",
"# Adjust train dataset with pydicom train dataset) | Phase",
"round(datum,0) # Set datum in submission file FVCDataList = FVCDataList",
"False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset =",
"========================================= Purpose: Build a submission CSV file Raw code reference",
"== referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m]",
"print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test",
"# ShapeParameter_Dataframe example = False if (example == True): import",
"task k = 0 l = 0 for i in",
"DictionaryToInclude, index=[newIndex]) newIndex = newIndex + 1 ## Concatenate DataFrame",
"== 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType",
"#ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals = loglaplace.ppf([0.001, 0.5,",
"- submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] =",
"from train data: (1) ID; (2) # of DICOM files",
"as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): #",
"Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample",
"ProductType == 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType",
"image-processing solution # Raw code reference (see Tester.py): 15 #",
"\"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy as np from scipy.stats import",
"Get datum in raw data IDlabel_rawFile = str(j)+str('_FVC') datum =",
"for j in range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude =",
"Concatenate the submission dataset (and additional instance) and the adjusted",
"list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i in metricLabels: j =",
"Phase 2: Extract submission instances from result dataset IDList_index =",
"print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped - Laplace Log Likelihood:\") print(\"=========================================\")",
"if (timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n]",
"max(70,sd_LL) # j: index is ID | k: SD_Clipped_(ML Model)",
"pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying",
"= pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances | Phase 1: Index",
"ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999],",
"submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1",
"submission CSV file Raw code reference (see Tester.py): Test 8",
"Adjust train dataset with pydicom train dataset) | Phase 2:",
"kurt = loglaplace.stats(c, moments='mvsk') # Display the probability density function",
"per instance ## differential = min(|FVC_true - FVC_predicted|, 1000) ##",
"functions of pydicom (Not sourced) ========================================= Purpose: Create support functions",
"in range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList",
"= SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset | Phase",
"ModelToInclude: filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns)",
"location path of the sampling import os import pandas as",
"train dataset instanceToTrasferList_index = [] for k in range(0,instancesPopulation): for",
"include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List +",
"submission instances | Phase 2: Extract submission instances from result",
"Determine: (1) the source path of the train data; (2)",
"Freeze the distribution and display the frozen pdf: rv =",
"= shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\") print(\"Shape Parameter - Laplace",
"averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust",
"DICOMFileNumber_list = [] for i in range(0,ID_list_range): path_ID = path_source",
"3: Create an adjusted train dataset | b. Get Transferring",
"if i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList = indexList",
"in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get submission data",
"shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame",
"solution case) to process with ML models # ========================================= #",
"| Phase 1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary = {}",
"per ID to compute for i in IDList: listToInclude =",
"to transfer InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0]",
"== True: print(\"ID tree copied: \",l) if (testMode == False",
"if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset = 'result.csv'",
"Sampling ========================================= Purpose: Build an aleatory sample given a train",
"filename = 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ##",
"Dataframe for Population\") print(\"result[1] -> Dataframe for Sample\") print(\"result[2] ->",
"DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame",
"the pydicom project \"\"\" \"\"\" Test mode 1 | Basics",
"as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission",
"in Population_DataFrame_IDToSample: path_source_unitary = path_source + k + '/' path_destination_unitary",
"= list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType",
"nextNumber = maxNumber+1 except ValueError: nextNumber = 0 ## Get",
"# Get submission instances | Phase 4: Sort submission instances",
"= {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False)",
"Sample\") print(\"result[2] -> Test Mode\") print(\"result[3] -> Rerport Mode\") print(\"=========================================\")",
"Build an input dataset to be processed with an stacking",
"Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped - Laplace",
"'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from predicted",
"= 0.12607421874999922 for every instance in the oject of concern.",
"os import pandas as pd ## Set Product Type and",
"Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction3[1]) print(\"=========================================\")",
"Get result data and test dataset import pandas as pd",
"import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode",
"differential / SDC metric_part2 = -1 * math.log1p(2**0.5 * SDC)",
"data in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List",
"train dataset | Phase 1: Get ID list of the",
"instance in the oject of concern. c value has been",
"- Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function",
"Tester.py): 15 # \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # #",
"Train Dataset of Kaggle for competition\") print(\"=========================================\") for k in",
"dataset is copied. from distutils.dir_util import create_tree from distutils.dir_util import",
"shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) #",
"= {} for i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i]",
"x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-',",
"resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode == True:",
"submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset | Phase 1: Get ID",
"= round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list}",
"(example == True): import pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466']",
"path of the sampling import os import pandas as pd",
"SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File saved",
"a DataFrame with standard-deviation-clipped values given an ID and a",
"path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os",
"## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) IDList =",
"k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID",
"+ 1 else: # Additional instances to include Patient_List =",
"standard-deviation-clipped values given an ID and a ML Model: standardDeviationClipped_DataFrame",
"np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns)",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient']",
"Get DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex =",
"# Get submission file template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame",
"required in submission file | FVC FVCDataList = [] for",
"+ j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k = k",
"filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks':",
"DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame =",
"Dataframe for Sample\") print(\"result[2] -> Test Mode\") print(\"result[3] -> Rerport",
"scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1 # # Calculate a",
"standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns)",
"len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List = [] FVC_List = []",
"range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in IDList): referenceWeek =",
"= pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get",
"pd.DataFrame(data = shapeParameter_dictionary, index = IDList) # Get confidence measure",
"path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset | Phase 3:",
"ProductType) print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input",
"# Get confidence measure | Phase 3: Get metric axe",
"pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index()",
"b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = []",
"= 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset =",
"= 0 while (samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber",
"## Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2",
"= list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i in columnLabels: columnLabels_item",
"Get submission file template filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename)",
"path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files | Phase",
"(Sampling)/' # Set working directory import os os.chdir(path_ProductType + 'outcome/')",
"== 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome",
"= [] IDList_columns = ['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient",
"train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN values:",
"the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set",
"= [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3] c_List4 =",
"print(\"-Train dataset percentage to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset",
"str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum",
"and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset",
"import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal",
"print(\"Input File saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type of the",
"print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \",",
"submissionList = os.listdir(path_destination) number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename,",
"print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction3[1])",
"in range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in IDList): referenceWeek",
"= [] Age_List = [] Sex_List = [] SmokingStatus_List =",
"# Calculate a few first moments # mean, var, skew,",
"range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage =",
"submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames)",
"Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal <= samplingSize):",
"moments='mvsk') # Display the probability density function (pdf): x =",
"nextNumber = 0 ## Get submission files | Phase 4:",
"## Metric - Part 1: |FVC_true - FVC_pred| if(pydicomMode ==",
"print(\"-Sample of Train dataset (just information) available in file: \",",
"[] for i in IDList: for j in range(0,instancesPopulation): if",
"else: shapeParameter_DataFrame = [] # Set Pydicom mode pydicomMode =",
"Report testMode = False reportMode = True Commisionning mode testMode",
"| Phase 2: Include values from train_adjusted_pydicom.py into adjusted train",
"Create support functions for the pydicom project \"\"\" \"\"\" Test",
"= FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get submission",
"Function Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode",
"y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1, scale1",
"in MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential)",
"# ========================================= # Purpose: Build an input dataset to be",
"print(\"Being the outcome expressed under the variable result, outcomes are",
"Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction[2]) print(\"=========================================\")",
"print(\"-Test Mode : False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of",
"os.listdir(path_destination) number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return",
"print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode == True:",
"print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test",
"element-wise equal within a tolerance. if(accuracy == True): accuracy =",
"4: Get models to include and their corresponding metrics ModelToInclude",
"mode testMode = False reportMode = False \"\"\" testMode =",
"a sample size Raw code reference (see Tester.py): Test 5",
"variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for",
"+ 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train",
"metric_dictionary = {} for j in MLModelList: metric_differential = abs(submission_dataset.FVC",
"index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete",
"with ML models # ========================================= # Purpose: Build an input",
"= {} for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame",
"= [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2,",
"= list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude = {}",
"= loglaplace.fit(r,floc=0,fscale=1) c = c1 # # Calculate a few",
"pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train dataset with pydicom train",
"values given an ID and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame",
"# Build a Sampling dataset | Phase 3: Get an",
"pd ## Set Product Type and its corresponding path if",
"Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result",
"The complete test dataset is copied. from distutils.dir_util import create_tree",
"if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber]",
"{'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome",
"filename_output = str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber =",
"except FileNotFoundError: GetCreation = False if GetCreation == False: from",
"True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product",
"(timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m]",
"train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode ==",
"(Stacking solution case) Raw code reference (see Tester.py): Test 17",
"(Features: Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o in",
"submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential",
"listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame =",
"3: Get correlative files_list = os.listdir(path_output) try: maxNumber = max(files_list)",
"path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data",
"splitType if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType",
"print(\"=========================================\") print(\"Submission File saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result",
"os.chdir(path_ProductType + 'outcome/') # Get result data and test dataset",
"for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p in",
"datum in submission file CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence']",
"import pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3]",
"Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (%",
"+ l + '/' path_destination_unitary = path_destination_test + l +",
"File saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function 2:",
"loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') # Freeze the distribution",
"test dataset (tree-copy task) ## Assumption: The complete test dataset",
"submissionFile_DataFrame, filename, testMode if testMode == True: ProductType = 'population'",
"if (PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset =",
"directory import os os.chdir(path_ProductType) # Get train dataset and test",
"print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function 1:",
"'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence",
"Display the probability density function (pdf): x = np.linspace(loglaplace.ppf(0.01, c),",
"directory try: path_output = path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError:",
"samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset | Phase 3: Get",
"15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set Product",
"testMode == True: print(\"ID tree copied: \",l) if (testMode ==",
"c. Update the submission dataset with the transferring data in",
"numy = 0 from scipy.stats import loglaplace for j in",
"if (shapeParameter_DataFrame == []): shapeParameter_dictionary = {} shapeParameter = 0.126074",
"import numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index)",
"========================================= Purpose: Get shape parameter visualization for loglaplace Raw code",
"range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p]",
"submission data as required in submission file submissionNumber_range = len(rawFile_DataFrame.index)",
"round(datum,0) # Set datum in submission file CONDataList = CONDataList",
"ID_List: for k in SDModel_List: itemToInclude = CParameter_List[numy] c =",
"import distutils.ccompiler path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get",
"Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) #",
"for competition and a sample size Raw code reference (see",
"per model: (-1 * differential * 2^0.5 / SDC )",
"## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels =",
"except ValueError: nextNumber = 0 ## Get submission files |",
"Train dataset (just information) available in file: \", filename_sampling) print(\"=========================================\")",
"loglaplace for j in ID_List: for k in SDModel_List: itemToInclude",
"mode pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter",
"plt.show() resultFunction = c return resultFunction if testMode == True:",
"= ['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ## Grouping",
"outcome ========================================= Purpose: Build a submission CSV file (Stacking solution",
"c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] =",
"= loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And compare the histogram:",
"if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes #",
"Build a submission CSV file Raw code reference (see Tester.py):",
"dataset instancesPopulation = len(train_dataset.Patient) indexList = [] for i in",
"train dataset instancesPopulation = len(train_dataset.Patient) indexList = [] for i",
"be processed with an stacking solution Raw code reference (see",
"frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted",
"= train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset | Phase 3:",
"+ [datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save file | Get",
"Get submission data as required in submission file | Confidence",
"0 if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m] for n in",
"= newIndex + 1 ## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted,",
"for Population\") print(\"result[1] -> Dataframe for Sample\") print(\"result[2] -> Test",
"= train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] =",
"# Adjust train dataset | Phase 2: Get submission instances",
"itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get submission instances",
"pd.read_csv(path+filename) ## Get IDs to test path = path_ProductType filename",
"= True except FileNotFoundError: GetCreation = False if GetCreation ==",
"print(\"Test result Function 2: Success\") print(\"=========================================\") \"\"\" ========================================= Function 3:",
"result Function 2: Success\") print(\"=========================================\") \"\"\" ========================================= Function 3: Dataset",
"train dataset | b. Get Transferring data from train dataset",
"datum = round(datum,0) # Set datum in submission file CONDataList",
"print(\"=========================================\") return resultFunction if testMode == True: ProductType = 'prototype'",
"IDcases_List[i][:-4] # Get submission data as required in submission file",
"'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for j in",
"instance into train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)):",
"= ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 =",
"'O'}).dtypes train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes",
"processed with an stacking solution but including Pydicom image-processing solution",
"title title = str('Probability density function for loglaplace'+'\\n'+i + '\\n'",
"IDs to test path = path_ProductType filename = 'test.csv' test_dataset",
"range(0,instancesPopulation): for l in IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index",
"5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (% of",
"test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get models model_List",
"train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file path_output =",
"filename_pydicom) # Adjust train dataset with pydicom train dataset) |",
"## When shapeParameter_DataFrame==[], parameter c = 0.126074 is assigned by",
"| k: SD_Clipped_(ML Model) numy = numy + 1 numy",
"Test mode 1 | Basics testMode = True reportMode =",
"per instance ## Metric - Part 1: standard_deviation_clipped = max(standard_deviation,",
"index = IDList) # Get confidence measure | Phase 2:",
"= {} for j in MLModelList: metric_differential = abs(submission_dataset.FVC -",
"#ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals = loglaplace.ppf([0.001,",
"Set outcome path_outcome = path_ProductType + 'outcome/' # Get raw",
"[] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage =",
"IDList_columns[2:] ## Get submission files | Phase 5: Build Files",
"FVC_pred| if(pydicomMode == True): variableNumber = 10 else: variableNumber =",
"accuracy = 'Equal case' else: accuracy = 'Unequal case' #",
"+'outcome/' if(PydicomMode == False): filename_output = 'train_adjusted.csv' else: filename_output =",
"Phase 1: Determine: (1) the source path of the train",
"Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal +",
"submissionFile_DataFrame['Confidence'] = CONDataList # Save file | Get directory path_destination",
"(0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m]",
"print(\"=========================================\") print(\"Input File saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type of",
"given a train dataset of Kaggle for competition and a",
"# Get submission data as required in submission file submissionNumber_range",
"samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not",
"instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index()",
"Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result Function 4:",
"| e. Concatenate the submission dataset (and additional instance) and",
"pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances | Phase 1: Index IDList",
"0 # Get confidence measure | Phase 3: Get metric",
"(randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary",
"list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j in MLModelList: metric_differential =",
"Test Dataset given the Test Dataset of Kaggle for competition\")",
"4: Success\") print(\"=========================================\") # \"\"\" # ========================================= # Function :",
"== i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] =",
"duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances |",
"type ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode",
"= Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get",
"'prototype' # ShapeParameter_Dataframe example = False if (example == True):",
"code reference (see Tester.py): Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import",
"+ [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary]",
"Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy = np.allclose([0.001,",
"= metric_part1 + metric_part2 submission_dataset[i][j] = metric # Result function",
"as pd # Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set",
"scipy.stats import loglaplace for j in ID_List: for k in",
"to sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to sample",
"from train dataset instanceToTrasferList_index = [] for k in range(0,instancesPopulation):",
"mode 1 | Basics testMode = True reportMode = False",
"0.999], loglaplace.cdf(vals, c)) # Returns True if two arrays are",
"train_dataset_adjusted.astype({'FVC': 'float64'}).dtypes if(PydicomMode == True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType':",
"ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy",
"### Step 1: Get index per ID to compute for",
"| Phase 4: Get metric axe per model: min(|FVC_true -",
"as pd ## Set Product Type and its corresponding path",
"submission instances | Phase 1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary",
"FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index)",
"filename = 'result.csv' y_pred = pd.read_csv(path+filename) ## Get IDs to",
"indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute",
"Returns True if two arrays are element-wise equal within a",
"+ [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary",
"path_ProductType +'outcome/' if(PydicomMode == False): filename_output = 'train_adjusted.csv' else: filename_output",
"submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List =",
"ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\")",
"print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function 2: Success\") print(\"=========================================\") \"\"\"",
"## Set Product Type and its corresponding path if ProductType",
"accuracy = 'Unequal case' # Set title title = str('Probability",
"IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for",
"submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] #",
"list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats import",
"metrics ModelToInclude = IDList_columns[2:] ## Get submission files | Phase",
"task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r = np.array(r)",
"sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles",
"solution Raw code reference (see Tester.py): Test 15 \"\"\" def",
"1 else: # Additional instances to include Patient_List = Patient_List",
"metric # Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get",
"Phase 4: Sort submission instances by Weeks (ascending) and reset",
"numy = 0 # Get confidence measure | Phase 3:",
"SDC ) - ln(2^0.5 * SCD) ## metric per instance",
"while (samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1)",
"datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum in",
"metric axe per model: min(|FVC_true - FVC_predicted|, 1000) ## metric",
"= [] # Set Pydicom mode pydicomMode = True resultFunction4",
"= loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Generate",
"testMode == True: samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\")",
"for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n]",
"True reportMode = False Test mode 2 | Function Report",
"adjusted train dataset | b. Get Transferring data from train",
"Phase 3: Create an adjusted train dataset | c. Update",
"| Phase 3: Create an adjusted train dataset | a.",
"visualization for loglaplace Raw code reference (see Tester.py): Test 17",
"i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3:",
"ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary =",
"to test path = path_ProductType filename = 'test.csv' test_dataset =",
"values grouping by ID and Model path = path_ProductType +",
"index = shapeParameter_IDList) else: shapeParameter_DataFrame = [] # Set Pydicom",
"= 'Unequal case' # Set title title = str('Probability density",
"= path_ProductType + 'outcome/' # Get raw data as a",
"## metric per instance ## Metric - Part 2: min(|FVC_true",
"\"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (% of the",
"= 'prototype' # ShapeParameter_Dataframe example = False if (example ==",
"list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_' + i[7:] SDC",
"CSV file Raw code reference (see Tester.py): Test 8 \"\"\"",
"train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n]",
"- Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped -",
"Function 5: Get parameters given a must-usage of a log-laplace",
"Set sampling size (% of the train population) samplingSize =",
"datum in raw data IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k]",
"and reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train",
"submission file CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence'] = CONDataList",
"import matplotlib.pyplot as plt fig, ax = plt.subplots(4, 5, sharex=False,",
"0.5, 0.999], loglaplace.cdf(vals, c)) # Returns True if two arrays",
"train dataset | Phase 4: Create an adjusted train dataset",
"DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation']",
"train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1 else:",
"if testMode == True: ProductType = 'prototype' PydicomMode = True",
"'/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree copied:",
"= list(test_dataset.Patient) # Adjust train dataset | Phase 2: Get",
"DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list",
"round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train",
"/ TotalNumberDicomFiles * 100 Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list",
"len(IDcases_List) for i in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] #",
"instances to include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List =",
"Adjust train dataset with pydicom train dataset) | Phase 1:",
"dataset with pydicom train dataset) | Phase 1: Get pydicom",
"import create_tree from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree",
"shapeParameter_DataFrame==[], parameter c = 0.126074 is assigned by default per",
"submission files | Phase 2: Create directory try: path_output =",
"True: # Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe",
"equal within a tolerance. if(accuracy == True): accuracy = 'Equal",
"dataset if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i",
"Product Type and its corresponding path # if ProductType ==",
"file | Get directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation",
"and reportMode == True): from datetime import date reportDate =",
"in model_List: # Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r",
"additional instance) and the adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List,",
"+ metric_part2 submission_dataset[i][j] = metric # Result function specification resultFunction",
"[DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary",
"= [] for i in IDList: for j in range(0,instancesPopulation):",
"list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation =",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 =",
"if testMode == True: ProductType = 'population' filename = 'submissionRawFile_2020_09_19.csv'",
"InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3",
"in IDcases_List: # Get datum in raw data IDlabel_rawFile =",
"= str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set",
"========================================= # Function : Dataset builder 2 (Stacking solution case)",
"Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary =",
"True): from datetime import date reportDate = date.today() print(\"=========================================\") print(\"Function",
"= max(files_list) maxNumber = maxNumber[:-4] maxNumber = int(maxNumber) nextNumber =",
"submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List",
"submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace",
"if(accuracy == True): accuracy = 'Equal case' else: accuracy =",
"path of the train data; (2) the location path of",
"Phase 3: Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get",
"coding: utf-8 -*- \"\"\" Created on Mon Sep 7 11:48:59",
"True: print(\"ID tree copied: \",k) # Build a Sampling dataset",
"= 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient) ## Get",
"= path_ProductType filename = 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List =",
"= DICOMFilePercentage_list + [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary)",
"with an stacking solution but including Pydicom image-processing solution #",
"Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function 4: Success\")",
"dataset percentage to sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage",
"= pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame =",
"= 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset",
"- FVC_predicted|, 1000) ## metric per instance ## Metric -",
"train dataset if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom =",
"Raw code reference (see Tester.py): Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode):",
"the oject of concern. c value has been computed deeming",
"path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True except FileNotFoundError:",
"pydicom train dataset) | Phase 2: Include values from train_adjusted_pydicom.py",
"== 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation",
"= metric # Result function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame #",
"3: Create an adjusted train dataset | d. Add common",
"1 plt.tight_layout() plt.show() resultFunction = c return resultFunction if testMode",
"print(\"=========================================\") print(\"Shape Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\")",
"task) ## Assumption: The complete test dataset is copied. from",
"l in IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k]",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 =",
"code reference (see Tester.py): Test 17 About the Shape Parameter:",
"CSV file (Stacking solution case) Raw code reference (see Tester.py):",
"| Phase 3: Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) #",
"ID to compute for i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient",
"= 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType == 'sampling': # path_ProductType",
"+ [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary)",
"features from train data: (1) ID; (2) # of DICOM",
"scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index is ID |",
"'/' path_destination_unitary = path_destination_test + l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary)",
"min(|FVC_true - FVC_predicted|, 1000) ## SDC: Standard Deviation Clipped ##",
"for k in range(0,instancesPopulation): for l in IDList: if train_dataset.Patient[k]",
"# if ProductType == 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/'",
"c, loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type",
"Remove test instances from train dataset and reset index train_dataset_adjusted",
"ln(2^0.5 * SCD) ## metric per instance ## differential =",
"repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0]",
"print(\"Submission File saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function",
"density function for loglaplace'+'\\n'+i + '\\n' + j + '",
"Sampling dataset | Phase 3: Get train dataset (an aleatory",
"= confidence_array filename_output = str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False)",
"in IDList: for j in range(0,instancesPopulation): if i == train_dataset.Patient[j]:",
"3: Success\") print(\"=========================================\") \"\"\" ========================================= Function 4: Submission dataset builder",
"+ [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List",
"Step 1: Get index per ID to compute for i",
"an adjusted train dataset | e. Concatenate the submission dataset",
"if testMode == True: print(\"ID tree copied: \",k) # Build",
"submissionFile_DataFrame['FVC'] = FVCDataList # Get submission data as required in",
"Success\") print(\"=========================================\") return resultFunction if testMode == True: ProductType =",
"for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p]",
"for every instance in the oject of concern. c value",
"= np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array filename_output =",
"if two arrays are element-wise equal within a tolerance. if(accuracy",
"arrays are element-wise equal within a tolerance. if(accuracy == True):",
"'outcome/' # Get raw data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame",
"os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission data as required",
"submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances | Phase 4: Sort submission",
"as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False):",
"differential * 2^0.5 / SDC ) - ln(2^0.5 * SCD)",
"= submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files | Phase 1: Get",
"Sampling dataset | Phase 1: Determine: (1) the source path",
"'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/'",
"= train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent':",
"= shapeParameter_dictionary, index = IDList) # Get confidence measure |",
"Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal",
"l in MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter]",
"Assumption: The complete test dataset is copied. from distutils.dir_util import",
"working directory import os os.chdir(path_ProductType + 'outcome/') # Get result",
"resultFunction[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\")",
"= 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result",
"IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index =",
"c) accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) # Returns",
"-> Dataframe for Population\") print(\"result[1] -> Dataframe for Sample\") print(\"result[2]",
"pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template) import numpy as np",
"= False reportMode = True Commisionning mode testMode = False",
"submission_dataset_range = len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList):",
"DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted =",
"DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary =",
"= InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: #",
"IDList: for i in metric_lists: for j in list(indexPerID_DataFrame[k]): differential",
"Parameter - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped",
"instance ## Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0]",
"= pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) #",
"-> Test Mode\") print(\"result[3] -> Rerport Mode\") print(\"=========================================\") return Population_DataFrame,",
"# Freeze the distribution and display the frozen pdf: rv",
"path_destination + k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode ==",
"= path_ProductType + 'outcome/' filename = 'result.csv' y_pred = pd.read_csv(path+filename)",
"file | Confidence CONDataList = [] for k in range(0,submissionNumber_range):",
"os.chdir(path_destination) GetCreation = True except FileNotFoundError: GetCreation = False if",
"repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude =",
"= str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude,",
"and Model path = path_ProductType + 'outcome/' filename = 'result.csv'",
"of Train dataset (just information) available in file: \", filename_population)",
"mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number = len(submissionList) filename",
"dataset to be processed with an stacking solution Raw code",
"shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame = [] # Set",
"= Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample",
"/ SDC ) - ln(2^0.5 * SCD) ## metric per",
"if reportMode == True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\")",
"axe per model: |FVC_true - FVC_predicted| ## Metric - Part",
"= 5 # Build a Sampling dataset | Phase 1:",
"population) samplingSize = 5 # Build a Sampling dataset |",
"limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals =",
"path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust",
"submission instances by Weeks (ascending) and reset index submission_dataset =",
"'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index",
"# Adjust train dataset | Phase 3: Create an adjusted",
"Percent_List = [] Age_List = [] Sex_List = [] SmokingStatus_List",
"submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i in",
"j in IDcases_List: # Get datum in raw data IDlabel_rawFile",
"True): accuracy = 'Equal case' else: accuracy = 'Unequal case'",
"= 0 for i in ID_List: k = 0 for",
"ax[k,l].set_title(title) k = k + 1 l = l +",
"print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") \"\"\" ========================================= Function",
"print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of sample: Aleatory based on IDs\")",
"import math from math import log1p for k in IDList:",
"# Build a Sampling dataset | Phase 2: Build dataset",
"'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get submission files | Phase",
"import pandas as pd filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset)",
"Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal =",
"Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]]",
"from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[])",
"print(\"result[1] -> Dataframe for Sample\") print(\"result[2] -> Test Mode\") print(\"result[3]",
"submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m]",
"maxNumber = int(maxNumber) nextNumber = maxNumber+1 except ValueError: nextNumber =",
"y_pred = pd.read_csv(path+filename) ## Get IDs to test path =",
"in IDList): referenceWeek = submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range):",
"testMode == True: # Set Product type ProductType = 'prototype'",
"Created on Mon Sep 7 11:48:59 2020 @author: mazal \"\"\"",
"r = loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And compare the",
"resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files | Phase 1:",
"its corresponding path # if ProductType == 'population': # path_ProductType",
"in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek):",
"== submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy == 0):",
"Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust",
"filename_population = 'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a",
"= False Test mode 2 | Function Report testMode =",
"= result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get submission instances |",
"print(\"Test result Function 1: Success\") print(\"=========================================\") \"\"\" ========================================= Function 2:",
"Build a submission CSV file (Stacking solution case) Raw code",
"copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True: print(\"=========================================\") print(\"Building the",
"in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage",
"'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType =",
"with ML models ========================================= Purpose: Build an input dataset to",
"= train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1 else: # Additional",
"= 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data =",
"Dataset of Kaggle for competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test) for",
"instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType)",
"list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ###",
"range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList =",
"Deviation Clipped - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test",
"repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType)",
"- ln(2^0.5 * SCD) ## metric per instance ## differential",
"# Get datum in raw data IDlabel_rawFile = str(j)+str('_CON') datum",
"index per ID to compute for i in IDList: listToInclude",
"= min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get",
"metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence measure | Phase 4:",
"Get submission instances | Phase 4: Sort submission instances by",
"of concern. c value has been computed deeming the following",
"Build a Sampling dataset | Phase 4: Get test dataset",
"listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric import",
"\"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and its corresponding",
"vals = loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy = np.allclose([0.001, 0.5,",
"print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\")",
"resultFunction if testMode == True: ProductType = 'prototype' PydicomMode =",
"+ '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary]",
"IDlabel_rawFile = str(j)+str('_FVC') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) #",
"result Function 4: Success\") print(\"=========================================\") \"\"\" ========================================= Function 5: Get",
"(PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv'",
"'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset)",
"filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset",
"# path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if ProductType == 'sampling':",
"'/' path_destination_unitary = path_destination + k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary)",
"Get train dataset and test dataset import pandas as pd",
"= Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] #",
"print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \",",
"True: samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\")",
"dataset IDList = list(test_dataset.Patient) # Adjust train dataset | Phase",
"Phase 3: Get metric axe per model: |FVC_true - FVC_predicted|",
"['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ## Grouping task",
"Tester.py): Test 15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): #",
"Get Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] =",
"available in file: \", filename_population) print(\"-Sample of Train dataset (just",
"[train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List +",
"+ 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files | Phase 3:",
"int(maxNumber) nextNumber = maxNumber+1 except ValueError: nextNumber = 0 ##",
"pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric import math from math",
"print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\")",
"instancesNumber = len(submission_dataset.index) for i in metricLabels: j = 0",
"(Not sourced) ========================================= Purpose: Create support functions for the pydicom",
"outcome path_outcome = path_ProductType + 'outcome/' # Get raw data",
"= 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust",
"# Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index)",
"min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence",
"i in range(0,ID_list_range): path_ID = path_source + ID_list[i] + '/'",
"per model: |FVC_true - FVC_predicted| ## Metric - Part 1:",
"been computed deeming the following data fitting scope: (1) Data:",
"of Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction3[2])",
"trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling size (% of the train population)",
"Set Pydicom mode pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\")",
"= min(|FVC_true - FVC_predicted|, 1000) ## SDC: Standard Deviation Clipped",
"(staistical function in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0,",
"SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset |",
"metric_part2 = -1 * math.log1p(2**0.5 * SDC) metric = metric_part1",
"train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust",
"metric_part2 submission_dataset[i][j] = metric # Result function specification resultFunction =",
"pydicom train dataset if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom",
"Adjust train dataset | Phase 1: Get ID list of",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling dataset | Phase",
"columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i in columnLabels:",
"a few first moments # mean, var, skew, kurt =",
"os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list = [] DICOMFileNumber_list = []",
"= max(70,sd_LL) # j: index is ID | k: SD_Clipped_(ML",
"utf-8 -*- \"\"\" Created on Mon Sep 7 11:48:59 2020",
"= 10 else: variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary",
"print(\"=========================================\") print(\"Building the Sampling Dataset given the Train Dataset of",
"Get correlative files_list = os.listdir(path_output) try: maxNumber = max(files_list) maxNumber",
"= True reportMode = False Test mode 2 | Function",
"path_source + l + '/' path_destination_unitary = path_destination_test + l",
"Function 3: Dataset builder (Stacking solution case) to process with",
"= {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame =",
"#r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r = np.array(r) c1,",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set working directory import os os.chdir(path_ProductType) #",
"loglaplace.fit(r,floc=0,fscale=1) c = c1 # # Calculate a few first",
"(just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0",
"reference (see Tester.py): 15 # \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode):",
"file path_output = path_ProductType +'outcome/' if(PydicomMode == False): filename_output =",
"of IDs (just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal",
"len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List)",
"3: Get an aleatory grouping of IDs (just tags) import",
"True: print(\"=========================================\") print(\"Building the Test Dataset given the Test Dataset",
"sampling size (% of the train population) samplingSize = 5",
"of sample: Aleatory based on IDs\") print(\"-Train dataset percentage to",
"data IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0)",
"for k in IDList: for i in metric_lists: for j",
"are as follows:\") print(\"result[0] -> Dataframe for Population\") print(\"result[1] ->",
"repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4",
"train dataset and test dataset import pandas as pd filename_trainDataset",
"timesCopy = 0 if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m] for",
"(Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling dataset",
"InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude = pd.DataFrame(data",
"c_List3 = [3,3,3,3,3] c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1,",
"= pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv'",
"FVCDataList # Get submission data as required in submission file",
"axe per model: min(|FVC_true - FVC_predicted|, 1000) ## metric per",
"'Gradient Boosting', 'Stacking Regressor'] for j in IDList: IDList_index =",
"+ [Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame =",
"from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True:",
"DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list =",
"Phase 2: Get standard-deviation-clipped per instance ## Metric - Part",
"= 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0])",
"test import os import pandas as pd ## Set Product",
"+ '/' path_destination_unitary = path_destination_test + l + '/' create_tree(path_destination_unitary,[])",
"Set datum in submission file CONDataList = CONDataList + [datum]",
"instance) and the adjusted train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List,",
"# Set productType and splitType if ProductType == 'population': path_ProductType",
"from result dataset IDList_index = [] IDList_columns = ['Patient', 'Weeks',",
"# mean, var, skew, kurt = loglaplace.stats(c, moments='mvsk') # Display",
"import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number = len(submissionList)",
"ax[k,l].set_ylabel('f(x,c)') # Check Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999], c)",
"= False if GetCreation == False: from distutils.dir_util import mkpath",
"Test 17 About the Shape Parameter: It amounts to c",
"metric per instance ## differential = min(|FVC_true - FVC_predicted|, 1000)",
"[] SmokingStatus_List = [] for m in range (0,submission_dataset_range): timesCopy",
"adjusted train dataset | d. Add common values to submission",
"density function as follows (staistical function in scipy renowend as",
"'\\n' + j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k =",
"| Phase 1: Determine: (1) the source path of the",
"1: Get ID list of the test dataset IDList =",
"= 'result.csv' y_pred = pd.read_csv(path+filename) ## Get IDs to test",
"DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType']",
"| Phase 1: Get ID list of the test dataset",
"for i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i]",
"| Get directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation =",
"with standard-deviation-clipped values given an ID and a ML Model:",
"metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude =",
"Raw code reference (see Tester.py): Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode):",
"= IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i in range (0,IDcases_List_range):",
"create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree copied: \",k)",
"the test dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient)",
"MLModelList = IDList_columns[2:] for l in MLModelList: keyShapeParameter = 'c",
"train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset | Phase",
"Aleatory based on IDs\") print(\"-Train dataset percentage to sample (base):",
"standard-deviation-clipped per instance ## Metric - Part 1: standard_deviation_clipped =",
"as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination =",
"list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType =",
"# Get submission files | Phase 1: Get submission file",
"= pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get",
"'result.csv' y_pred = pd.read_csv(path+filename) ## Get IDs to test path",
"[] DICOMFileNumber_list = [] for i in range(0,ID_list_range): path_ID =",
"Product type ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType,",
"'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset)",
"= repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] =",
"[instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') #",
"instances by Weeks (ascending) and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient'])",
"values: Average FVC for a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient",
"= path_destination_test + l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode",
"(see Tester.py): Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os import",
"'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype':",
"a train dataset of Kaggle for competition and a sample",
"Dataset given the Train Dataset of Kaggle for competition\") print(\"=========================================\")",
"= pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population = 'populationDataset.csv' path_population = path_destination_outcome",
"filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode if",
"0.12607421874999922 for every instance in the oject of concern. c",
"l in IDList_test: path_source_unitary = path_source + l + '/'",
"submission files | Phase 1: Get submission file template filename",
"complete test dataset is copied. from distutils.dir_util import create_tree from",
"DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data =",
"= averageFVC # Adjust train dataset | Phase 4: Create",
"'Unequal case' # Set title title = str('Probability density function",
"for Sample\") print(\"result[2] -> Test Mode\") print(\"result[3] -> Rerport Mode\")",
"(Sampling)/' ## Get probabilities from predicted values grouping by ID",
"[] for i in range(0,ID_list_range): path_ID = path_source + ID_list[i]",
"shapeParameter_visualizer(ProductType,testMode): import numpy as np from scipy.stats import loglaplace import",
"path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True except FileNotFoundError: GetCreation =",
"for j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_'",
"model: min(|FVC_true - FVC_predicted|, 1000) ## metric per instance ##",
"confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] = confidence_array filename_output",
"dataset with pydicom train dataset) | Phase 2: Include values",
"## Get submission files | Phase 5: Build Files for",
"path_outcome = path_ProductType + 'outcome/' # Get raw data as",
"result dataset IDList_index = [] IDList_columns = ['Patient', 'Weeks', 'Random",
"== i].ImageType)[0] # Put instance into train_dataset_adjusted DataFrame if (0",
"print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size :\", samplingSize, \"%\") print(\"-Test",
"= train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] = train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] =",
"2: Submission Builder ========================================= Purpose: Build a submission CSV file",
"print(\"=========================================\") for k in Population_DataFrame_IDToSample: path_source_unitary = path_source + k",
"i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation",
"\", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input",
"an aleatory sample given a train dataset of Kaggle for",
"path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data",
"ML models # ========================================= # Purpose: Build an input dataset",
"DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index",
"= submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure | Phase 1:",
"shapeParameter = 0.126074 MLModelList = IDList_columns[2:] for l in MLModelList:",
"= {} ### Step 1: Get index per ID to",
"saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\")",
"filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset)",
"files per ID (including percentage). ## Improvement: (3) # of",
"loglaplace Raw code reference (see Tester.py): Test 17 \"\"\" def",
"is copied. from distutils.dir_util import create_tree from distutils.dir_util import remove_tree",
"' | Accuracy:'+accuracy) ax[k,l].set_title(title) k = k + 1 l",
"= str(InstanceToInclude_ImageType) else: # Add new instance ## Get repeatable",
"Sort submission instances by Weeks (ascending) and reset index submission_dataset",
"of IDs; tree-copy task) from distutils.dir_util import create_tree from distutils.dir_util",
"========================================= Function 4: Submission dataset builder (Stacking solution case) after",
"train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes",
"print(\"=========================================\") \"\"\" ========================================= Function 3: Dataset builder (Stacking solution case)",
"if (example == True): import pandas as pd shapeParameter_IDList =",
"reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset =",
"[] # Set Pydicom mode pydicomMode = True resultFunction4 =",
"FVC_List = [] Percent_List = [] Age_List = [] Sex_List",
"= submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset | Phase 1: Get",
"| Phase 4: Get test dataset (tree-copy task) ## Assumption:",
"if(pydicomMode == True): variableNumber = 10 else: variableNumber = 7",
"# # Calculate a few first moments # mean, var,",
"= itemToInclude # Get submission instances | Phase 2: Extract",
"SDC metric_part2 = -1 * math.log1p(2**0.5 * SDC) metric =",
") print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size",
"(and additional instance) and the adjusted train dataset additionalDictionary =",
"= shapeParameter_IDList) else: shapeParameter_DataFrame = [] # Set Pydicom mode",
"= [] Week_List = [] FVC_List = [] Percent_List =",
"as follows:\") print(\"result[0] -> Dataframe for Population\") print(\"result[1] -> Dataframe",
"Save file | Get directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination)",
"from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True:",
"in IDList: if train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index",
"metric_lists: for j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label =",
"DataFrame with standard-deviation-clipped values given an ID and a ML",
"Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File saved as:\") print(\"=========================================\") print(resultFunction2[1])",
"Builder ========================================= Purpose: Build a submission CSV file Raw code",
"pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build",
"print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size :\", samplingSize,",
"Additional instances to include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List",
"Patient_List = [] Week_List = [] FVC_List = [] Percent_List",
"(see Tester.py): Test 17 About the Shape Parameter: It amounts",
"path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from predicted values",
"## Get probabilities from predicted values grouping by ID and",
"== train_dataset.Patient[j]: indexToInclude = train_dataset.index[j] indexList = indexList + [indexToInclude]",
"file FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList #",
"print(\"=========================================\") print(\"Being the outcome expressed under the variable result, outcomes",
"Get datum in raw data IDlabel_rawFile = str(j)+str('_CON') datum =",
"(Sampling)/' # Set working directory import os os.chdir(path_ProductType) # Get",
"working directory import os os.chdir(path_ProductType) # Get train dataset and",
"print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type:",
"c return resultFunction if testMode == True: # Set Product",
"len(train_dataset.Patient) indexList = [] for i in IDList: for j",
"About the Shape Parameter: It amounts to c = 0.12607421874999922",
"pdf') # Freeze the distribution and display the frozen pdf:",
"| Phase 5: Get metric axe per model: (-1 *",
"distribution and display the frozen pdf: rv = loglaplace(c) ax[k,l].plot(x,",
"print(\"=========================================\") print(\"Test result Function 1: Success\") print(\"=========================================\") \"\"\" ========================================= Function",
"# Get datum in raw data IDlabel_rawFile = str(j)+str('_FVC') datum",
"train dataset | a. Remove test instances from train dataset",
"len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p",
"the source path of the train data; (2) the location",
"pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i])",
"# Get submission dataset (template) import numpy as np path_resources",
"specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files | Phase",
"FVC predictions; (2) Probability density function as follows (staistical function",
"frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check",
"'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList)",
"(just information) available in file: \", filename_population) print(\"-Sample of Train",
"distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True: print(\"=========================================\")",
"filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the outcome expressed under",
"# -*- coding: utf-8 -*- \"\"\" Created on Mon Sep",
"reportMode = True Commisionning mode testMode = False reportMode =",
"resultFunction3[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data type",
"standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List",
"3: Get train dataset (an aleatory grouping of IDs; tree-copy",
"train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n]",
"def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and its corresponding path",
"for j in IDcases_List: # Get datum in raw data",
"density function (pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100)",
"Dataset builder (Stacking solution case) to process with ML models",
"nan filling train_dataset_adjusted = train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes",
"print(\"=========================================\") \"\"\" ========================================= Function 2: Submission Builder ========================================= Purpose: Build",
"Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary =",
"DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent']",
"False reportMode = False \"\"\" ========================================= Function 1: Aleatory Sampling",
"= 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode if testMode",
"'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset",
"Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling",
"1: Determine: (1) the source path of the train data;",
"copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True: print(\"=========================================\") print(\"Building the",
"result Function 3: Success\") print(\"=========================================\") \"\"\" ========================================= Function 4: Submission",
"submission instances | Phase 3: Extract duplicated instances submission_dataset =",
"2: Extract submission instances from result dataset IDList_index = []",
"'Gradient Boosting', 'Stacking Regressor'] ## Grouping task k = 0",
"print(resultFunction5) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") # \"\"\"",
"[train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List + [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List +",
"Improvement: (3) # of other registers (not related to DICOM",
"= 'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset",
"* math.log1p(2**0.5 * SDC) metric = metric_part1 + metric_part2 submission_dataset[i][j]",
"'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome",
"def shapeParameter_visualizer(ProductType,testMode): import numpy as np from scipy.stats import loglaplace",
"loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Generate random",
"== train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] =",
"= np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array submissionFile['Confidence'] =",
"of pydicom (Not sourced) ========================================= Purpose: Create support functions for",
"'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes train_dataset_adjusted.astype({'FVC':",
"1 return resultFunction if testMode == True: # Set Product",
"Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles =",
"Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1,",
"create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree copied: \",l)",
"an adjusted train dataset | c. Update the submission dataset",
"for k in Population_DataFrame_IDToSample: path_source_unitary = path_source + k +",
"train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset",
"itemToInclude # Get submission instances | Phase 2: Extract submission",
"train_dataset_adjusted.replace('iNaN',np.nan) # Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes",
"resultFunction = c return resultFunction if testMode == True: #",
"i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"Weeks (ascending) and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset =",
"sourced) ========================================= Purpose: Create support functions for the pydicom project",
"= nextNumber + 1 return resultFunction if testMode == True:",
"in IDList: for i in metric_lists: for j in list(indexPerID_DataFrame[k]):",
"Add new instance ## Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List =",
"1 l = l + 1 plt.tight_layout() plt.show() resultFunction =",
"list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 =",
"create_tree(path_destination,[]) if testMode == True: print(\"=========================================\") print(\"Building the Sampling Dataset",
"to process with ML models ========================================= Purpose: Build an input",
"path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType =",
"on Mon Sep 7 11:48:59 2020 @author: mazal \"\"\" \"\"\"",
"directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True except",
"DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1 DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age']",
"as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes)",
"as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List =",
"confidence measure | Phase 5: Get metric axe per model:",
"path_source_unitary = path_source + l + '/' path_destination_unitary = path_destination_test",
"from the test dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range =",
"dataset import pandas as pd if(pydicomMode == True): filename_resultDataset =",
"repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation",
"Get index per ID to compute for i in IDList:",
"When shapeParameter_DataFrame==[], parameter c = 0.126074 is assigned by default",
"dataset to be processed with an stacking solution but including",
"IDList_index_dictionary = {} for i in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index",
"IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) #",
"reference (see Tester.py): Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set",
"Phase 2: Build dataset using the following features from train",
"DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ##",
"copied: \",k) # Build a Sampling dataset | Phase 4:",
"j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence measure | Phase",
"import os os.chdir(path_ProductType + 'outcome/') # Get result data and",
"Set working directory import os os.chdir(path_ProductType) # Get train dataset",
"print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") \"\"\" ========================================= Function",
"columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as",
"(see Tester.py): 15 # \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): #",
"print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1])",
"i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import",
"7 11:48:59 2020 @author: mazal \"\"\" \"\"\" ========================================= Support functions",
"result Function 1: Success\") print(\"=========================================\") \"\"\" ========================================= Function 2: Submission",
"dataset | Phase 1: Determine: (1) the source path of",
"IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists",
"list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient) for i in",
"compare the histogram: #ax[k,l].hist(r, density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) #",
"(Stacking solution case) to process with ML models # =========================================",
"r = y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1, scale1 =",
"| Phase 1: Get pydicom train dataset if(PydicomMode == True):",
"DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC']",
"related to DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range =",
"'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv' else:",
"pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') # Adjust train dataset | Phase",
"= DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary = len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list",
"== i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] =",
"instanceToTrasferList_index = [] for k in range(0,instancesPopulation): for l in",
"ID_list[i] + '/' DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list +",
"= round(datum,0) # Set datum in submission file FVCDataList =",
"1 | Basics testMode = True reportMode = False Test",
"path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a Sampling dataset |",
"print(\"ID tree copied: \",k) # Build a Sampling dataset |",
"model: |FVC_true - FVC_predicted| ## Metric - Part 1: |FVC_true",
"'populationDataset.csv' path_population = path_destination_outcome Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset",
"# Set datum in submission file FVCDataList = FVCDataList +",
"SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists",
"the distribution and display the frozen pdf: rv = loglaplace(c)",
"if(PydicomMode == True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType +",
"loglaplace import matplotlib.pyplot as plt fig, ax = plt.subplots(4, 5,",
"in file: \", filename_population) print(\"-Sample of Train dataset (just information)",
"CONDataList # Save file | Get directory path_destination = path_outcome+'submissions/'",
"in submission file CONDataList = CONDataList + [datum] submissionFile_DataFrame['Confidence'] =",
"= [] FVC_List = [] Percent_List = [] Age_List =",
":\", samplingSize, \"%\") print(\"-Test Mode : False\") print(\"=========================================\") print(\"(2) Outputs\")",
"# \"\"\" # ========================================= # Function : Dataset builder 2",
"print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File saved as:\")",
"submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1 return resultFunction if testMode",
"Function 1: Success\") print(\"=========================================\") \"\"\" ========================================= Function 2: Submission Builder",
"Sex_List = [] SmokingStatus_List = [] for m in range",
"print(\"=========================================\") # \"\"\" # ========================================= # Function : Dataset builder",
"trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\")",
"Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode == True: samplingSize =",
"tree copied: \",k) # Build a Sampling dataset | Phase",
"referenceWeek = submission_dataset.Weeks[m] for n in range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] ==",
"str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber +",
"sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (fitted):",
"datum in submission file FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC']",
"label='loglaplace pdf') # Freeze the distribution and display the frozen",
"numpy as np standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List",
"instances from train dataset instancesPopulation = len(train_dataset.Patient) indexList = []",
"index=False) return submissionFile_DataFrame, filename, testMode if testMode == True: ProductType",
"Create an adjusted train dataset | a. Remove test instances",
"False: from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination)",
"DICOMFile_list_unitary = os.listdir(path_ID) DICOMFile_list = DICOMFile_list + [DICOMFile_list_unitary] DICOMFileNumber_list_unitary =",
"Average FVC for a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient ==",
"[3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking Regressor':c_List4}",
"Standard Deviation Clipped ## Metric - Part 2: min(|FVC_true -",
"## differential = min(|FVC_true - FVC_predicted|, 1000) ## SDC: Standard",
"per model and ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary =",
"models model_List = ['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor']",
"ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Generate random numbers:",
"i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] =",
"+ 1 l = l + 1 plt.tight_layout() plt.show() resultFunction",
"# Set datum in submission file CONDataList = CONDataList +",
"submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC']",
"FileNotFoundError: GetCreation = False if GetCreation == False: from distutils.dir_util",
"Week_List = [] FVC_List = [] Percent_List = [] Age_List",
"## Get submission files | Phase 3: Get correlative files_list",
"Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame, Population_Percentage_DataFrame],axis=1, sort=False) filename_population =",
"Sampling dataset | Phase 2: Build dataset using the following",
"= l + 1 plt.tight_layout() plt.show() resultFunction = c return",
"print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the outcome expressed under the variable",
"index=[newIndex]) newIndex = newIndex + 1 ## Concatenate DataFrame train_dataset_adjusted",
"submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN values: Average",
"True): train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV",
"GetCreation = False if GetCreation == False: from distutils.dir_util import",
"range (0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if",
"print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result",
"i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"shapeParameter_DataFrame = [] # Set Pydicom mode pydicomMode = True",
"Success\") print(\"=========================================\") \"\"\" ========================================= Function 5: Get parameters given a",
"# Get confidence measure | Phase 4: Get metric axe",
"File saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type of the dataset\")",
"= [] SmokingStatus_List = [] for m in range (0,submission_dataset_range):",
"transferring data in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient)",
"dataset (tree-copy task) ## Assumption: The complete test dataset is",
"Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample =",
"train population) samplingSize = 5 # Build a Sampling dataset",
"Part 1: standard_deviation_clipped = max(standard_deviation, 70) ## Build a DataFrame",
"InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0]",
"Population\") print(\"result[1] -> Dataframe for Sample\") print(\"result[2] -> Test Mode\")",
"Get IDs to test import os import pandas as pd",
"i in IDList: for j in range(0,instancesPopulation): if i ==",
"(not related to DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get probabilities from predicted values grouping",
"submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames =",
"= InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude =",
"max(standard_deviation, 70) ## Build a DataFrame with standard-deviation-clipped values given",
"maxNumber = max(files_list) maxNumber = maxNumber[:-4] maxNumber = int(maxNumber) nextNumber",
"given an ID and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame =",
"dataset (just information) available in file: \", filename_population) print(\"-Sample of",
"i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 * differential",
"Population_DataFrame.to_csv(path_population+filename_population) # Build a Sampling dataset | Phase 3: Get",
"* SCD) ## metric per instance ## differential = min(|FVC_true",
"Probability density function as follows (staistical function in scipy renowend",
"print(\"Building the Test Dataset given the Test Dataset of Kaggle",
"path_source + k + '/' path_destination_unitary = path_destination + k",
"filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\")",
"tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while",
"train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train dataset with pydicom",
"numbers: r = loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And compare",
"== False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset",
"display the frozen pdf: rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-',",
"import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True: print(\"=========================================\") print(\"Building",
"first moments # mean, var, skew, kurt = loglaplace.stats(c, moments='mvsk')",
"# Get result data and test dataset import pandas as",
"path # if ProductType == 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/'",
"c1 # # Calculate a few first moments # mean,",
"testMode == True: print(\"=========================================\") print(\"Building the Sampling Dataset given the",
"InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient) for i in instancesToInclude_List:",
"dataset | b. Get Transferring data from train dataset instanceToTrasferList_index",
"for i in range(0,ID_list_range): path_ID = path_source + ID_list[i] +",
"1: Get pydicom train dataset if(PydicomMode == True): filename_pydicom =",
"i].Weeks)): # Get index indexToComplete = list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient ==",
"e. Concatenate the submission dataset (and additional instance) and the",
"samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling)",
"| Phase 2: Get submission instances from train dataset instancesPopulation",
"percentage to sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset",
"Get metric axe per model: min(|FVC_true - FVC_predicted|, 1000) ##",
"True): filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom",
"0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset",
"print(resultFunction4[2]) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\") \"\"\" =========================================",
"l + '/' path_destination_unitary = path_destination_test + l + '/'",
"(1) ID; (2) # of DICOM files per ID (including",
"\"%\") print(\"-Test Mode : False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type",
"= indexList + [indexToInclude] # Adjust train dataset | Phase",
"ValueError: nextNumber = 0 ## Get submission files | Phase",
"# Specifying dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age':",
"Get shape Parameter DataFrame by default ## When shapeParameter_DataFrame==[], parameter",
"numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode ==",
"train dataset | c. Update the submission dataset with the",
"[train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List +",
"print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location of Input File:\",",
"result Function 4: Success\") print(\"=========================================\") # \"\"\" # ========================================= #",
"instances from train dataset and reset index train_dataset_adjusted = train_dataset.drop(indexList)",
"0 for i in ID_List: k = 0 for j",
"Sampling dataset | Phase 3: Get an aleatory grouping of",
"test instances from train dataset and reset index train_dataset_adjusted =",
"IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get submission instances",
"o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p in range(0,train_dataset_instancesToTransfer_range):",
"import pandas as pd ## Set Product Type and its",
"Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode) print(\"=========================================\") print(\"Location",
"# Build a Sampling dataset | Phase 4: Get test",
"model and ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary = {}",
"+ 'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output = path_ProductType",
"dataset | Phase 4: Get test dataset (tree-copy task) ##",
"filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset)",
"files | Phase 5: Build Files for i in ModelToInclude:",
"= 0 # Get confidence measure | Phase 3: Get",
"Model) numy = numy + 1 numy = 0 #",
"metricLabels: j = 0 while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j",
"submission instances | Phase 4: Sort submission instances by Weeks",
"len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample",
"Get submission instances | Phase 1: Index IDList = list(test_dataset.Patient)",
"True: print(\"=========================================\") print(\"Building the Sampling Dataset given the Train Dataset",
"| Phase 5: Build Files for i in ModelToInclude: filename",
"train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train dataset",
"testMode = True reportMode = False Test mode 2 |",
"Mode : False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of sample:",
"path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType",
"file: \", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the outcome",
"[train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset | Phase 3: Create an",
"train data: (1) ID; (2) # of DICOM files per",
"- Part 2: min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List",
"len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: # Get instance to transfer",
"process with ML models # ========================================= # Purpose: Build an",
"remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode ==",
"resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population",
"[] Sex_List = [] SmokingStatus_List = [] for m in",
"== True: # Set Product type ProductType = 'prototype' #",
"1000) ## SDC: Standard Deviation Clipped ## Metric - Part",
"= list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame =",
"percentage to sample (base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to",
"os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output = path_ProductType + 'submission/'",
"= submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range = len(IDcases_List) for i",
"axe per model: (-1 * differential * 2^0.5 / SDC",
"[] Age_List = [] Sex_List = [] SmokingStatus_List = []",
"and test dataset import pandas as pd if(pydicomMode == True):",
"= 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j",
"SCD) ## metric per instance ## differential = min(|FVC_true -",
"| a. Remove test instances from train dataset and reset",
"========================================= Support functions of pydicom (Not sourced) ========================================= Purpose: Create",
"repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation",
"in range(0,submissionNumber_range): for j in IDcases_List: # Get datum in",
"Phase 2: Include values from train_adjusted_pydicom.py into adjusted train dataset",
"== i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = IDList) # Get",
"path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build",
"<= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if (randomNumber",
"submission file template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv')",
"filename, testMode if testMode == True: ProductType = 'population' filename",
"few first moments # mean, var, skew, kurt = loglaplace.stats(c,",
"pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission",
"dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List}",
"of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function 3:",
"in IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get",
"(0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get index indexToComplete =",
"Log Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped - Laplace Log",
"print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\")",
"if testMode == True: # Set Product type ProductType =",
"competition\") print(\"=========================================\") for k in Population_DataFrame_IDToSample: path_source_unitary = path_source +",
"Get submission file template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame =",
"Likelihood:\") print(\"=========================================\") print(resultFunction4[1]) print(\"Standard Deviation Clipped - Laplace Log Likelihood:\")",
"list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array = np.array(submission_dataset['metric_'+i]) submissionFile['FVC'] = fvc_array",
"testMode): # # Set Product Type and its corresponding path",
"a submission CSV file (Stacking solution case) Raw code reference",
"\"\"\" ========================================= Function 2: Submission Builder ========================================= Purpose: Build a",
"- FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i",
"PydicomMode, reportMode, testMode): # Set Product Type and its corresponding",
"print(\"Test result Function 3: Success\") print(\"=========================================\") return resultFunction if testMode",
"train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode",
"(samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber = random.randrange(0,randomNumberTermination,1) if",
"path_ProductType + 'outcome/' # Get raw data as a DataFrame",
"+ [indexToInclude] # Adjust train dataset | Phase 3: Create",
"metric_part1 + metric_part2 submission_dataset[i][j] = metric # Result function specification",
"[datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get submission data as required",
"plt.tight_layout() plt.show() resultFunction = c return resultFunction if testMode ==",
"2: Build dataset using the following features from train data:",
"'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom +",
"{} ### Step 1: Get index per ID to compute",
"list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index)",
"= list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5",
"1 numy = 0 # Get confidence measure | Phase",
"(Stacking solution case) to process with ML models ========================================= Purpose:",
"shape Parameter DataFrame by default ## When shapeParameter_DataFrame==[], parameter c",
"print(\"Location of Input File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File saved as:\",",
"follows:\") print(\"result[0] -> Dataframe for Population\") print(\"result[1] -> Dataframe for",
"testMode if testMode == True: ProductType = 'population' filename =",
"= {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset =",
"# Additional instances to include Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]]",
"confidence measure | Phase 1: Get shape Parameter DataFrame by",
"= [] for i in range(0,ID_list_range): path_ID = path_source +",
"reference (see Tester.py): Test 17 About the Shape Parameter: It",
"loglaplace.cdf(vals, c)) # Returns True if two arrays are element-wise",
"# path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype': #",
"+ '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree",
"IDList: itemToInclude = result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get submission",
"(-1 * differential * 2^0.5 / SDC ) - ln(2^0.5",
"DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude = pd.DataFrame(data =",
"Laplace Log Likelihood) ========================================= Purpose: Get shape parameter visualization for",
"Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r =",
"print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test result Function 1: Success\")",
"Phase 1: Index IDList = list(test_dataset.Patient) IDList_index_dictionary = {} for",
"measure | Phase 5: Get metric axe per model: (-1",
"# Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)') # Check Accuracy",
"Phase 4: Create an adjusted train dataset | e. Concatenate",
"density=True, histtype='stepfilled', alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4)",
"Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType and splitType",
"'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus':",
"File:\", resultFunction3[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction3[2]) print(\"=========================================\") print(\"Data",
"== True): variableNumber = 10 else: variableNumber = 7 MLModelList",
"files | Phase 4: Get models to include and their",
"import pandas as pd # Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/'",
"## Grouping task k = 0 l = 0 for",
"function as follows (staistical function in scipy renowend as scipy.stats.loglaplace):",
"Clipped - Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction4[2]) print(\"=========================================\") print(\"Test result",
"= 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction = train_dataset_adjusted,path_output,filename_output #",
"== 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] = train_dataset_instancesToTransfer.Percent[n] submission_dataset.Age[m] =",
"= stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\")",
"Get confidence measure | Phase 2: Get standard-deviation-clipped per instance",
"'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission dataset (template) import",
"= c1 # # Calculate a few first moments #",
"= len(ID_list) DICOMFile_list = [] DICOMFileNumber_list = [] for i",
"(see Tester.py): Test 17 \"\"\" def shapeParameter_visualizer(ProductType,testMode): import numpy as",
"1: Get shape Parameter DataFrame by default ## When shapeParameter_DataFrame==[],",
"list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index)",
"5 # Build a Sampling dataset | Phase 1: Determine:",
"into train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): #",
"loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index is",
"reportMode = False \"\"\" testMode = False reportMode = False",
"train dataset if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient =",
"= train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN values: Average FVC",
"FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i in",
"test dataset import pandas as pd if(pydicomMode == True): filename_resultDataset",
"Update the submission dataset with the transferring data in b.",
"[train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List +",
"Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in",
"# if ProductType == 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' #",
"Get directory path_destination = path_outcome+'submissions/' try: os.chdir(path_destination) GetCreation = True",
"instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances | Phase",
"Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]]",
"print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size :\",",
"4: Success\") print(\"=========================================\") \"\"\" ========================================= Function 5: Get parameters given",
"title = str('Probability density function for loglaplace'+'\\n'+i + '\\n' +",
"datum = round(datum,0) # Set datum in submission file FVCDataList",
"# Set sampling size (% of the train population) samplingSize",
"reference (see Tester.py): Test 8 \"\"\" def SubmissionBuilder(ProductType,filename,testMode): import os",
"= len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List = IDcases_List[0:5] IDcases_List_range =",
"shapeParameter_IDList) else: shapeParameter_DataFrame = [] # Set Pydicom mode pydicomMode",
"solution case) Raw code reference (see Tester.py): Test 17 About",
"= Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample}",
"Type and its corresponding path # if ProductType == 'population':",
"new instance ## Get repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"= list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary)",
"= Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber]",
"path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset |",
"in IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o]",
"type of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function",
"Phase 5: Build Files for i in ModelToInclude: filename =",
"pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template as a DataFrame os.chdir(path_ProductType)",
"Adjust train dataset | Phase 4: Create an adjusted train",
"str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex])",
"code reference (see Tester.py): 15 # \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType,",
"+ [datum] submissionFile_DataFrame['FVC'] = FVCDataList # Get submission data as",
"j in ID_List: for k in SDModel_List: itemToInclude = CParameter_List[numy]",
"and ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary = {} shapeParameter",
"list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {}",
"+ i[7:] SDC = standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 *",
"+ k + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if testMode == True:",
"d. Add common values to submission dataset given those from",
"Result resultFunction = train_dataset_adjusted,path_output,filename_output # Report Mode if reportMode ==",
"'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i])",
"return submissionFile_DataFrame, filename, testMode if testMode == True: ProductType =",
"= 'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype': # path_ProductType =",
"ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary",
"(see Tester.py): Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): # Set sampling",
"samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv'",
"confidence_array filename_output = str(nextNumber)+'.csv' path_output = path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber",
"# Get CSV file path_output = path_ProductType +'outcome/' if(PydicomMode ==",
"print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\") print(\"Being the outcome expressed under the",
"dataset percentage to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage",
"if testMode == True: samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode)",
"probability density function (pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c),",
"print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product",
"copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree copied: \",k) #",
"False \"\"\" ========================================= Function 1: Aleatory Sampling ========================================= Purpose: Build",
"+ [train_dataset_instancesToTransfer.Sex[n]] SmokingStatus_List = SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train",
"print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result",
"path = path_ProductType + 'outcome/' filename = 'result.csv' y_pred =",
"to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to sample",
"== True: print(\"ID tree copied: \",k) # Build a Sampling",
"= repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] =",
"submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv' path_output = path_ProductType +'submission/'",
"dataset using the following features from train data: (1) ID;",
"samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling",
"11:48:59 2020 @author: mazal \"\"\" \"\"\" ========================================= Support functions of",
"= 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom",
"submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure |",
"train_dataset_adjusted DataFrame if (0 in list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Weeks)): # Get",
"not in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary =",
"path_source_unitary = path_source + k + '/' path_destination_unitary = path_destination",
"Test Dataset of Kaggle for competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test)",
"print(\"-Train dataset percentage to sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of",
"| Basics testMode = True reportMode = False Test mode",
"= train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust train dataset with",
"= repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] = InstanceToInclude_indexType1_Exhalation DictionaryToInclude['indexType1_Inhalation'] =",
"= pd.concat(frames) train_dataset_adjusted = train_dataset_adjusted.reset_index() train_dataset_adjusted = train_dataset_adjusted.drop(columns='index') # Adjust",
"Set working directory import os os.chdir(path_ProductType + 'outcome/') # Get",
"# Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe example",
"3: Create an adjusted train dataset | a. Remove test",
"dataset with the transferring data in b. submission_dataset_range = len(submission_dataset.Patient)",
"shapeParameter_dictionary = {} shapeParameter = 0.126074 MLModelList = IDList_columns[2:] for",
"path_destination_unitary = path_destination_test + l + '/' create_tree(path_destination_unitary,[]) copy_tree(path_source_unitary,path_destination_unitary) if",
"MLModelList: metric_differential = abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude",
"print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function: trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1)",
"standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index is ID | k:",
"print(ProductType) print(\"=========================================\") print(\"Submission File saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test",
"metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary) # Get confidence measure | Phase",
"= len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for",
"+ 1 return resultFunction if testMode == True: # Set",
"train_dataset_instancesToTransfer.SmokingStatus[p] # Scenario to replace NaN values: Average FVC for",
"# Set Product Type and its corresponding path # if",
"= train_dataset_instancesToTransfer.Age[n] submission_dataset.Sex[m] = train_dataset_instancesToTransfer.Sex[n] submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy =",
"Set productType and splitType if ProductType == 'population': path_ProductType =",
"Step 3: Compute metric import math from math import log1p",
"Index IDList = list(test_dataset.Patient) IDList_index_dictionary = {} for i in",
"= int(maxNumber) nextNumber = maxNumber+1 except ValueError: nextNumber = 0",
"train_dataset_adjusted.indexType1_Exhalation[indexToComplete] = InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else:",
"path_ProductType filename = 'test.csv' test_dataset = pd.read_csv(path+filename) ID_List = list(test_dataset.Patient)",
"ID if (shapeParameter_DataFrame == []): shapeParameter_dictionary = {} shapeParameter =",
"list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude] = metric_differential metric_DataFrame = pd.DataFrame(data=metric_dictionary)",
"= y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1)",
"+ [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List",
"## Assumption: The complete test dataset is copied. from distutils.dir_util",
"create_tree from distutils.dir_util import remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination_test)",
"in the oject of concern. c value has been computed",
"(2) Probability density function as follows (staistical function in scipy",
"by default per model and ID if (shapeParameter_DataFrame == []):",
"CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100) standardDeviationClipped_DataFrame[k][j]",
"pd filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset = 'test.csv'",
"submission files | Phase 5: Build Files for i in",
"Success\") print(\"=========================================\") \"\"\" ========================================= Function 3: Dataset builder (Stacking solution",
"i newIndex = len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: # Get",
"# Get submission instances | Phase 2: Extract submission instances",
"filename_submissionDataset = 'submissionInputDataset_pydicom.csv' submission_dataset = pd.read_csv(path_resources+filename_submissionDataset) submission_dataset = submission_dataset.replace(np.nan,'iNaN') #",
"under the variable result, outcomes are as follows:\") print(\"result[0] ->",
"False Test mode 2 | Function Report testMode = False",
"Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for o in range(0,submission_dataset_range): if(submission_dataset.Patient[o]",
"except FileNotFoundError: import distutils.ccompiler path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output)",
"else: filename_resultDataset = 'result.csv' result_dataset = pd.read_csv(path_ProductType+'outcome/'+filename_resultDataset) filename_testDataset = 'test.csv'",
"dataset builder (Stacking solution case) after ML outcome ========================================= Purpose:",
"'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\")",
"= listToInclude indexPerID_DataFrame = pd.DataFrame(data=indexPerID_dictionary) ### Step 3: Compute metric",
"| Phase 3: Get metric axe per model: |FVC_true -",
"to replace NaN values: Average FVC for a given Patient",
"list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0",
"24)) ## Get IDs to test import os import pandas",
"pydicom (Not sourced) ========================================= Purpose: Create support functions for the",
"as a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission",
"# Purpose: Build an input dataset to be processed with",
"= standardDeviationClipped_DataFrame.replace(3,np.nan) ID_List = list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List =",
"a Sampling dataset | Phase 3: Get an aleatory grouping",
"reference (see Tester.py): Test 15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode,",
"files | Phase 2: Create directory try: path_output = path_ProductType",
"data fitting scope: (1) Data: FVC predictions; (2) Probability density",
"Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ## Grouping task k",
"percentage to sample (adjustment): \", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to",
"expressed under the variable result, outcomes are as follows:\") print(\"result[0]",
"# of other registers (not related to DICOM files) os.chdir(path_source)",
"SubmissionBuilder(ProductType,filename,testMode): import os import pandas as pd # Set ProductType",
"submission dataset (and additional instance) and the adjusted train dataset",
"train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add new instance ## Get",
"= SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType) print(\"=========================================\") print(\"Submission File",
"* differential / SDC metric_part2 = -1 * math.log1p(2**0.5 *",
"result_dataset.Patient[result_dataset.Patient==i].index IDList_index_dictionary[i] = itemToInclude # Get submission instances | Phase",
"model_List: # Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r =",
"ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode =",
"in ModelToInclude: filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) submissionFile_columns =",
"template as a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get",
"resultFunction if testMode == True: # Set Product type ProductType",
"2: Get submission instances from train dataset instancesPopulation = len(train_dataset.Patient)",
"Get metric axe per model: (-1 * differential * 2^0.5",
"Set title title = str('Probability density function for loglaplace'+'\\n'+i +",
"path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype': # path_ProductType",
"reportDate = date.today() print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\")",
"pandas as pd path_source = 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination",
"averageFVC # Adjust train dataset | Phase 4: Create an",
"= list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for i in metricLabels: j",
"Raw code reference (see Tester.py): Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode):",
"for j in IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset",
"IDList_columns[2:] for l in MLModelList: keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter]",
"= path_ProductType +'outcome/' if(PydicomMode == False): filename_output = 'train_adjusted.csv' else:",
"7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary = {} for j in",
"IDList: for j in range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude",
"with the transferring data in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range",
"data as required in submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List",
"j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence measure",
"= FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List = Percent_List + [train_dataset_instancesToTransfer.Percent[n]] Age_List",
"train dataset of Kaggle for competition and a sample size",
"| Phase 3: Create an adjusted train dataset | d.",
"Phase 1: Get shape Parameter DataFrame by default ## When",
"columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary) import numpy as np standardDeviationClipped_DataFrame =",
"measure | Phase 3: Get metric axe per model: |FVC_true",
"math from math import log1p for k in IDList: for",
"# def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set Product Type and",
"/ SDC metric_part2 = -1 * math.log1p(2**0.5 * SDC) metric",
"+'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1 return resultFunction if",
"# Get raw data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame =",
"size Raw code reference (see Tester.py): Test 5 \"\"\" def",
"k: SD_Clipped_(ML Model) numy = numy + 1 numy =",
"+ samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame = pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling =",
"sample size Raw code reference (see Tester.py): Test 5 \"\"\"",
"Extract duplicated instances submission_dataset = submission_dataset.drop_duplicates(subset=['Patient','Weeks']) # Get submission instances",
"= ['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor']",
"pandas as pd filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset",
"-1 * math.log1p(2**0.5 * SDC) metric = metric_part1 + metric_part2",
"a DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission data",
"dataset | Phase 2: Get submission instances from train dataset",
"for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item standardDeviationClipped_DataFrame = standardDeviationClipped_DataFrame.rename(columns=columnLabels_SDC_dictionary)",
"test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances | Phase 1:",
"= list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4",
"train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o] = train_dataset_instancesToTransfer.SmokingStatus[p]",
"========================================= Purpose: Create support functions for the pydicom project \"\"\"",
"dataset) | Phase 2: Include values from train_adjusted_pydicom.py into adjusted",
"i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient ==",
"for k in range(0,submissionNumber_range): for j in IDcases_List: # Get",
"print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") return resultFunction if",
"Boosting':c_List3, 'Stacking Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index =",
"| Phase 2: Get standard-deviation-clipped per instance ## Metric -",
"train dataset | e. Concatenate the submission dataset (and additional",
"= False reportMode = False \"\"\" ========================================= Function 1: Aleatory",
"'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction",
"information) available in file: \", filename_population) print(\"-Sample of Train dataset",
"= InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add new instance",
"else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction =",
"DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex = newIndex",
"support functions for the pydicom project \"\"\" \"\"\" Test mode",
"= y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r = np.array(r) c1, loc1,",
"case' # Set title title = str('Probability density function for",
"is assigned by default per model and ID if (shapeParameter_DataFrame",
"function specification resultFunction = submission_dataset,shapeParameter_DataFrame,standardDeviationClipped_DataFrame # Get submission files |",
"submission file template filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ##",
"the transferring data in b. submission_dataset_range = len(submission_dataset.Patient) train_dataset_instancesToTransfer_range =",
"Create an adjusted train dataset | b. Get Transferring data",
"os os.chdir(path_ProductType) # Get train dataset and test dataset import",
"15 # \"\"\" # def stacking_Dataset_Builder_PydicomSolution(productType, testMode): # # Set",
"the Sampling Dataset given the Train Dataset of Kaggle for",
"os import pandas as pd # Set ProductType path_ProductType =",
"70) ## Build a DataFrame with standard-deviation-clipped values given an",
"data as required in submission file | FVC FVCDataList =",
"= pd.DataFrame(data=samplingDataset_Dictionary) filename_sampling = 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) #",
"dataset | e. Concatenate the submission dataset (and additional instance)",
"DICOMFile_list = [] DICOMFileNumber_list = [] for i in range(0,ID_list_range):",
"FVC_predicted|, 1000) ## metric per instance ## Metric - Part",
"min(|FVC_true - FVC_pred|,1000) metricLabels = list(metric_DataFrame.columns) instancesNumber = len(submission_dataset.index) for",
"samplingSize_unitary = Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary =",
"numpy as np from scipy.stats import loglaplace import matplotlib.pyplot as",
"default ## When shapeParameter_DataFrame==[], parameter c = 0.126074 is assigned",
"sample: Aleatory based on IDs\") print(\"-Train dataset percentage to sample",
"(Prototype)/' # if ProductType == 'sampling': # path_ProductType = 'Y:/Kaggle_OSIC/4-Data",
"+ 'outcome/' # Get raw data as a DataFrame os.chdir(path_outcome)",
"pd.read_csv('sample_submission.csv') # Get submission data as required in submission file",
"print(\"Location of Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File saved as:\",",
"samplingSizeGoal = 0 while (samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID)",
"and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels =",
"print(\"=========================================\") \"\"\" ========================================= Function 4: Submission dataset builder (Stacking solution",
"# Check Accuracy vals = loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy",
"list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance into train_dataset_adjusted DataFrame if",
"repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0]",
"columnLabels_SDC_dictionary = {} for i in columnLabels: columnLabels_item ='SD_Clipped'+i[11:] columnLabels_SDC_dictionary[i]=columnLabels_item",
"predicted values grouping by ID and Model path = path_ProductType",
"'k-', lw=2, label='frozen pdf') # Generate random numbers: r =",
"PydicomMode) print(\"=========================================\") print(\"Location of Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File",
"Regressor':c_List4} shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList) else:",
"Function 1: Aleatory Sampling ========================================= Purpose: Build an aleatory sample",
"2: min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns)",
"case) to process with ML models # ========================================= # Purpose:",
"if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' ## Get",
"DictionaryToInclude['Percent'] = repeatableInstance2 DictionaryToInclude['Age'] = repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus']",
"= 0 for j in model_List: # Data Fit task",
"differential = min(|FVC_true - FVC_predicted|, 1000) ## SDC: Standard Deviation",
"function for loglaplace'+'\\n'+i + '\\n' + j + ' |",
"aleatory grouping of IDs (just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[]",
"IDList_test = os.listdir(path_source_test) for l in IDList_test: path_source_unitary = path_source",
"Function : Dataset builder 2 (Stacking solution case) to process",
"# Set working directory import os os.chdir(path_ProductType) # Get train",
"remove_tree(path_destination_test) create_tree(path_destination_test,[]) if testMode == True: print(\"=========================================\") print(\"Building the Test",
"files | Phase 1: Get submission file template filename =",
"testMode): # Set Product Type and its corresponding path if",
"pd.read_csv(path_ProductType+filename) ## Get submission files | Phase 2: Create directory",
"= 'Y:/Kaggle_OSIC/2-Data/train/' path_source_test = 'Y:/Kaggle_OSIC/2-Data/test/' path_destination = 'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test",
"their corresponding metrics ModelToInclude = IDList_columns[2:] ## Get submission files",
"(pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x,",
"Commisionning mode testMode = False reportMode = False \"\"\" testMode",
"as pd filename_trainDataset = 'train.csv' train_dataset = pd.read_csv(path_ProductType+filename_trainDataset) filename_testDataset =",
"* differential * 2^0.5 / SDC ) - ln(2^0.5 *",
"np from scipy.stats import loglaplace import matplotlib.pyplot as plt fig,",
"+ filename_pydicom) # Adjust train dataset with pydicom train dataset)",
"Submission Builder ========================================= Purpose: Build a submission CSV file Raw",
"pydicom project \"\"\" \"\"\" Test mode 1 | Basics testMode",
"Clipped ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) IDList",
"c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') #",
"directory import os os.chdir(path_ProductType + 'outcome/') # Get result data",
"False): filename_output = 'train_adjusted.csv' else: filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) #",
"TotalNumberDicomFiles * 100 Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list +",
"[] Percent_List = [] Age_List = [] Sex_List = []",
"[ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary",
"builder (Stacking solution case) after ML outcome ========================================= Purpose: Build",
"# Get submission instances | Phase 1: Index IDList =",
"Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index",
"= maxNumber[:-4] maxNumber = int(maxNumber) nextNumber = maxNumber+1 except ValueError:",
"and its corresponding path # if ProductType == 'population': #",
"= date.today() print(\"=========================================\") print(\"Function Report | Date:\",reportDate.year,'/',reportDate.month,'/',reportDate.day,'/' ) print(\"=========================================\") print(\"Function:",
"# Adjust train dataset | Phase 4: Create an adjusted",
"train dataset additionalDictionary = {submission_dataset.columns[0]:Patient_List, submission_dataset.columns[1]:Week_List, submission_dataset.columns[2]:FVC_List, submission_dataset.columns[3]:Percent_List, submission_dataset.columns[4]:Age_List, submission_dataset.columns[5]:Sex_List,",
"IDcases_List_range = len(IDcases_List) for i in range (0,IDcases_List_range): IDcases_List[i] =",
"+ [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary]",
"== i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance",
"train_dataset_instancesToTransfer_range = len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List = [] FVC_List",
"= CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c, loc=0, scale=100)",
"def SubmissionBuilder(ProductType,filename,testMode): import os import pandas as pd # Set",
"[randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample = Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary",
"= pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles)",
"pydicom train dataset) | Phase 1: Get pydicom train dataset",
"= list(train_dataset_adjusted[train_dataset_adjusted.Weeks == 0].Patient[train_dataset_adjusted.Patient == i].index) # Complete instance train_dataset_adjusted.indexType1_Exhalation[indexToComplete]",
"from train dataset and reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index",
"| Phase 4: Sort submission instances by Weeks (ascending) and",
"10 else: variableNumber = 7 MLModelList = list(submission_dataset.columns[variableNumber:]) metric_dictionary =",
"for i in metricLabels: j = 0 while (j<instancesNumber): metric_DataFrame[i][j]",
"train_dataset_adjusted.astype({'indexType1_Exhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file",
"j + ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k = k +",
"Patient_List = Patient_List + [train_dataset_instancesToTransfer.Patient[n]] Week_List = Week_List + [train_dataset_instancesToTransfer.Weeks[n]]",
"instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex = len(train_dataset_adjusted.Patient) for",
"{} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week DictionaryToInclude['FVC'] = repeatableInstance1",
"train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex': 'O'}).dtypes train_dataset_adjusted.astype({'SmokingStatus': 'O'}).dtypes",
"(Sampling)/outcome/' # Build a Sampling dataset | Phase 2: Build",
"the Train Dataset of Kaggle for competition\") print(\"=========================================\") for k",
"IDs; tree-copy task) from distutils.dir_util import create_tree from distutils.dir_util import",
"Files for i in ModelToInclude: filename = 'sample_submission.csv' submissionFile =",
"train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust train dataset | Phase",
"= path_ProductType + 'outcome/' train_dataset_pydicom = pd.read_csv(path_ProductType_pydicom + filename_pydicom) #",
"registers (not related to DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source)",
"train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset | Phase",
"Get instance to transfer InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient",
"= repeatableInstance3 DictionaryToInclude['Sex'] = repeatableInstance4 DictionaryToInclude['SmokingStatus'] = repeatableInstance5 DictionaryToInclude['indexType1_Exhalation'] =",
"= list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step",
"size (% of the train population) samplingSize = 5 #",
"the Test Dataset of Kaggle for competition\") print(\"=========================================\") IDList_test =",
"mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number = len(submissionList) filename =",
"data and test dataset import pandas as pd if(pydicomMode ==",
"0 while (samplingSizeGoal <= samplingSize): randomNumberTermination = len(Population_DataFrame.ID) randomNumber =",
"metric import math from math import log1p for k in",
"ShapeParameter_Dataframe resultFunction5 = shapeParameter_visualizer(ProductType, testMode = True) print(\"=========================================\") print(\"Shape Parameter",
"copy_tree(path_source_unitary,path_destination_unitary) if testMode == True: print(\"ID tree copied: \",l) if",
"- FVC_predicted|, 1000) ## SDC: Standard Deviation Clipped ## Metric",
"= pd.read_csv('submissionRawFile_2020_09_19.csv') # Get submission file template as a DataFrame",
"5: Get metric axe per model: (-1 * differential *",
"= path_source + k + '/' path_destination_unitary = path_destination +",
"Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for j in IDList:",
"standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for",
"loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf')",
"+ ' | Accuracy:'+accuracy) ax[k,l].set_title(title) k = k + 1",
"i].Percent)[0] repeatableInstance3 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Age)[0] repeatableInstance4 = list(train_dataset_adjusted[train_dataset_adjusted.Patient ==",
"referenceWeek): if (timesCopy == 0): submission_dataset.FVC[m] = train_dataset_instancesToTransfer.FVC[n] submission_dataset.Percent[m] =",
"loc=0, scale=100) standardDeviationClipped_DataFrame[k][j] = max(70,sd_LL) # j: index is ID",
"remove_tree from distutils.dir_util import copy_tree remove_tree(path_destination) create_tree(path_destination,[]) if testMode ==",
"to submission dataset given those from the test dataset (Features:",
"print(\"-Sampling Size :\", samplingSize, \"%\") print(\"-Test Mode : False\") print(\"=========================================\")",
"type of the dataset\") print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function",
"keyShapeParameter = 'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data",
"loc=0, scale=1). \"\"\" def Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode): # Set Product Type and",
"(an aleatory grouping of IDs; tree-copy task) from distutils.dir_util import",
"'Lasso', 'Gradient Boosting', 'Stacking Regressor'] for j in IDList: IDList_index",
"i].indexType1_Inhalation)[0] InstanceToInclude_ImageType = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance into",
"== False: from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList =",
"Purpose: Get shape parameter visualization for loglaplace Raw code reference",
"== i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient",
"Get metric axe per model: |FVC_true - FVC_predicted| ## Metric",
"0 ## Get submission files | Phase 4: Get models",
"metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame) #",
"5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\")",
"2**0.5 * differential / SDC metric_part2 = -1 * math.log1p(2**0.5",
"False\") print(\"=========================================\") print(\"(2) Outputs\") print(\"=========================================\") print(\"-Type of sample: Aleatory based",
"train dataset) | Phase 1: Get pydicom train dataset if(PydicomMode",
"CParameter_List = list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats import loglaplace",
"Function 3: Success\") print(\"=========================================\") \"\"\" ========================================= Function 4: Submission dataset",
"= False reportMode = False \"\"\" testMode = False reportMode",
"= standardDeviationClipped_DataFrame[SDC_Label][k] metric_part1 = -1* 2**0.5 * differential / SDC",
"Compute metric import math from math import log1p for k",
"the test dataset IDList = list(test_dataset.Patient) # Adjust train dataset",
"False reportMode = True Commisionning mode testMode = False reportMode",
"| d. Add common values to submission dataset given those",
"c_List4 = [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3,",
"# Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j]",
"j in range(0,instancesPopulation): if i == train_dataset.Patient[j]: indexToInclude = train_dataset.index[j]",
"========================================= # Purpose: Build an input dataset to be processed",
"Mode\") print(\"result[3] -> Rerport Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode,",
"Create directory try: path_output = path_ProductType + 'submission/' os.chdir(path_output) except",
"= train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index)",
"the submission dataset (and additional instance) and the adjusted train",
"+ 'outcome/' filename = 'result.csv' y_pred = pd.read_csv(path+filename) ## Get",
"= maxNumber+1 except ValueError: nextNumber = 0 ## Get submission",
"= os.listdir(path_destination) number = len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False)",
"ModelToInclude = IDList_columns[2:] ## Get submission files | Phase 5:",
"= Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample + [Percentage_unitary] samplingSize_unitary = Population_DataFrame.Percentage[randomNumber]",
"dataset instanceToTrasferList_index = [] for k in range(0,instancesPopulation): for l",
"(i.e. Laplace Log Likelihood) ========================================= Purpose: Get shape parameter visualization",
"Rerport Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode",
"following features from train data: (1) ID; (2) # of",
"Include values from train_adjusted_pydicom.py into adjusted train dataset if(PydicomMode ==",
"Dictionary DictionaryToInclude = {} DictionaryToInclude['Patient'] = InstanceToInclude_Patient DictionaryToInclude['Weeks'] = InstanceToInclude_Week",
"'float64'}).dtypes train_dataset_adjusted.astype({'indexType1_Inhalation': 'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file path_output",
"dataset percentage to sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train",
"# Get submission data as required in submission file |",
"submission data as required in submission file | Confidence CONDataList",
"function in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1).",
"FVC for a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean()",
"grouping of IDs (just tags) import random Population_DataFrame_IndexToSample=[] Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[]",
"dtype train_dataset_adjusted.astype({'Patient': 'O'}).dtypes train_dataset_adjusted.astype({'Weeks': 'float64'}).dtypes train_dataset_adjusted.astype({'Percent': 'float64'}).dtypes train_dataset_adjusted.astype({'Age': 'float64'}).dtypes train_dataset_adjusted.astype({'Sex':",
"# Display the probability density function (pdf): x = np.linspace(loglaplace.ppf(0.01,",
"code reference (see Tester.py): Test 5 \"\"\" def trainDatasetSampler(samplingSize,testMode,reportMode): #",
"Build a Sampling dataset | Phase 3: Get an aleatory",
"dataset | Phase 2: Build dataset using the following features",
"SD_Clipped_(ML Model) numy = numy + 1 numy = 0",
"in range(0,submission_dataset_range): if(submission_dataset.Patient[o] in IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o]",
"submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index() submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get",
"data as required in submission file | Confidence CONDataList =",
"if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] = train_dataset_instancesToTransfer.Age[p] submission_dataset.Sex[o] = train_dataset_instancesToTransfer.Sex[p] submission_dataset.SmokingStatus[o]",
"if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType ==",
"+ 'outcome/') # Get result data and test dataset import",
"train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset | Phase 3: Create an",
"of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function 3:",
"(Stacking solution case) after ML outcome ========================================= Purpose: Build a",
"(base): \", round(abs(samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (adjustment): \",",
"file (Stacking solution case) Raw code reference (see Tester.py): Test",
"= os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list = [] DICOMFileNumber_list =",
"= IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get submission",
"ProductType = 'prototype' PydicomMode = True reportMode = False resultFunction3",
"Boosting', 'Stacking Regressor'] ## Grouping task k = 0 l",
"= len(train_dataset_instancesToTransfer.Patient) Patient_List = [] Week_List = [] FVC_List =",
"of Kaggle for competition and a sample size Raw code",
"the probability density function (pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99,",
"@author: mazal \"\"\" \"\"\" ========================================= Support functions of pydicom (Not",
"IDList_index = [] IDList_columns = ['Patient', 'Weeks', 'Random Forest', 'Lasso',",
"= True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter - Laplace",
"dataset (and additional instance) and the adjusted train dataset additionalDictionary",
"## metric per instance ## differential = min(|FVC_true - FVC_predicted|,",
"to compute for i in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient ==",
"1: Get submission file template filename = 'sample_submission.csv' submissionFile =",
"corresponding path if ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if",
"17 About the Shape Parameter: It amounts to c =",
"those from the test dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range",
"k in Population_DataFrame_IDToSample: path_source_unitary = path_source + k + '/'",
"Test 15 \"\"\" def stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set",
"rv = loglaplace(c) ax[k,l].plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') #",
"Get train dataset (an aleatory grouping of IDs; tree-copy task)",
"print(\"result[0] -> Dataframe for Population\") print(\"result[1] -> Dataframe for Sample\")",
"stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode): # Set Product Type and its",
"Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \", ProductType)",
"Get parameters given a must-usage of a log-laplace distribution (i.e.",
"print(\"Test result Function 4: Success\") print(\"=========================================\") # \"\"\" # =========================================",
"= [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = IDList)",
"Build dataset using the following features from train data: (1)",
"+ 1 numy = 0 # Get confidence measure |",
"Phase 3: Create an adjusted train dataset | b. Get",
"= path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1 return",
"Sampling dataset | Phase 4: Get test dataset (tree-copy task)",
"outcome expressed under the variable result, outcomes are as follows:\")",
"\", round(abs(samplingSizeGoal-samplingSize),6),\"%\") print(\"-Train dataset percentage to sample (fitted): \", round(samplingSizeGoal,6),\"%\")",
"= 0 from scipy.stats import loglaplace for j in ID_List:",
"for m in range (0,submission_dataset_range): timesCopy = 0 if(submission_dataset.Patient[m] in",
"= max(standard_deviation, 70) ## Build a DataFrame with standard-deviation-clipped values",
"= list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0] repeatableInstance3",
"Phase 4: Get models to include and their corresponding metrics",
"while (j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset =",
"len(DICOMFile_list_unitary) DICOMFileNumber_list = DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame",
"c = c1 # # Calculate a few first moments",
"train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file path_output = path_ProductType +'outcome/'",
"Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if testMode ==",
"from distutils.dir_util import create_tree from distutils.dir_util import remove_tree from distutils.dir_util",
"min(|FVC_true - FVC_pred|,1000) IDList = list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List",
"2 | Function Report testMode = False reportMode = True",
"list of the test dataset IDList = list(test_dataset.Patient) # Adjust",
"ProductType == 'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType ==",
"to sample (fitted): \", round(samplingSizeGoal,6),\"%\") print(\"-Population of Train dataset (just",
"IDList): for p in range(0,train_dataset_instancesToTransfer_range): if(submission_dataset.Patient[o] == train_dataset_instancesToTransfer.Patient[p]): submission_dataset.Age[o] =",
"if(PydicomMode == True): instancesToInclude_List = list(train_dataset_pydicom.Patient) InstanceToInclude_Patient = i newIndex",
"files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list =",
"path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission files",
"testMode = False reportMode = False \"\"\" ========================================= Function 1:",
"Phase 3: Get train dataset (an aleatory grouping of IDs;",
"# Get confidence measure | Phase 5: Get metric axe",
"= 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances |",
"data from train dataset instanceToTrasferList_index = [] for k in",
"pandas as pd if(pydicomMode == True): filename_resultDataset = 'result_pydicom.csv' else:",
"ID list of the test dataset IDList = list(test_dataset.Patient) #",
"(j<instancesNumber): metric_DataFrame[i][j] = min(metric_DataFrame[i][j],1000) j = j+1 submission_dataset = submission_dataset.join(metric_DataFrame)",
"shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i in",
"every instance in the oject of concern. c value has",
"if ProductType == 'sampling': path_ProductType = 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set",
"instance ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000) metricLabels",
"case) after ML outcome ========================================= Purpose: Build a submission CSV",
"path_ProductType +'submission/' submissionFile.to_csv(path_output+filename_output,columns=submissionFile_columns,index=False) nextNumber = nextNumber + 1 return resultFunction",
"resultFunction[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type",
"predictions; (2) Probability density function as follows (staistical function in",
"# Generate random numbers: r = loglaplace.rvs(c1, loc=0, scale=1, size=1000)",
"Train dataset (just information) available in file: \", filename_population) print(\"-Sample",
"Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j]) r = y_pred[y_pred.Patient==i][j] r",
"in raw data IDlabel_rawFile = str(j)+str('_CON') datum = rawFile_DataFrame[IDlabel_rawFile][k] datum",
"dataset IDList_index = [] IDList_columns = ['Patient', 'Weeks', 'Random Forest',",
"= shapeParameter_DataFrame.copy() columnLabels = list(standardDeviationClipped_DataFrame.columns) columnLabels_SDC_dictionary = {} for i",
"pydicomMode = True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter -",
"= train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train",
"print(resultFunction3[0]) print(\"=========================================\") print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode:",
"2: Success\") print(\"=========================================\") \"\"\" ========================================= Function 3: Dataset builder (Stacking",
"Deviation Clipped ## Metric - Part 2: min(|FVC_true - FVC_pred|,1000)",
"True: print(\"ID tree copied: \",l) if (testMode == False and",
"True reportMode = False resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode)",
"DictionaryToInclude['indexType1_Inhalation'] = InstanceToInclude_indexType1_Inhalation DictionaryToInclude['ImageType'] = str(InstanceToInclude_ImageType) ## Get DataFrame DataFrameToInclude",
"dataset:\") print(\"=========================================\") print(resultFunction1[0]) print(\"=========================================\") print(\"Population dataset:\") print(\"=========================================\") print(resultFunction1[1]) print(\"=========================================\") print(\"Test",
"# Set Product Type and its corresponding path if ProductType",
"k in range(0,instancesPopulation): for l in IDList: if train_dataset.Patient[k] ==",
"submission_dataset = submission_dataset.drop(columns=['Unnamed: 0','index']) # Get confidence measure | Phase",
"2^0.5 / SDC ) - ln(2^0.5 * SCD) ## metric",
"train_dataset_adjusted.reset_index # Adjust train dataset | Phase 3: Create an",
"metric axe per model: (-1 * differential * 2^0.5 /",
"else: # Add new instance ## Get repeatable instances repeatableInstance1",
"metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber",
"= fvc_array submissionFile['Confidence'] = confidence_array filename_output = str(nextNumber)+'.csv' path_output =",
"reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust train dataset",
"InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Exhalation)[0] InstanceToInclude_indexType1_Inhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].indexType1_Inhalation)[0]",
"0','index']) # Get confidence measure | Phase 1: Get shape",
"saved as:\") print(\"=========================================\") print(resultFunction2[1]) print(\"=========================================\") print(\"Test result Function 2: Success\")",
"print(\"Test result Function 3: Success\") print(\"=========================================\") \"\"\" ========================================= Function 4:",
"other registers (not related to DICOM files) os.chdir(path_source) ID_list =",
"np.array(r) c1, loc1, scale1 = loglaplace.fit(r,floc=0,fscale=1) c = c1 #",
"grouping of IDs; tree-copy task) from distutils.dir_util import create_tree from",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/' # Set outcome path_outcome = path_ProductType +",
"= [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range): Percentage",
"for the pydicom project \"\"\" \"\"\" Test mode 1 |",
"= Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100 Percentage = round(Percentage,6) DICOMFilePercentage_list",
"## Get IDs to test path = path_ProductType filename =",
": Dataset builder 2 (Stacking solution case) to process with",
"c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace",
"Raw code reference (see Tester.py): Test 15 \"\"\" def stacking_Dataset_Builder(ProductType,",
"j in model_List: # Data Fit task #r = y_pred[y_pred.Patient==i][j]/sum(y_pred[y_pred.Patient==i][j])",
"Population_DataFrame_IDToSample + [ID_unitary] Percentage_unitary = Population_DataFrame.Percentage[randomNumber] Population_DataFrame_PercentageToSample = Population_DataFrame_PercentageToSample +",
"adjusted train dataset | e. Concatenate the submission dataset (and",
"= IDList_columns[2:] ## Get submission files | Phase 5: Build",
"= instanceToTrasferList_index + [instanceToTransfer_Index] train_dataset_instancesToTransfer = train_dataset.take(instanceToTrasferList_index) train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer =",
"========================================= Purpose: Build an aleatory sample given a train dataset",
"+ [train_dataset_instancesToTransfer.Percent[n]] Age_List = Age_List + [train_dataset_instancesToTransfer.Age[n]] Sex_List = Sex_List",
"========================================= Function 1: Aleatory Sampling ========================================= Purpose: Build an aleatory",
"True): filename_resultDataset = 'result_pydicom.csv' else: filename_resultDataset = 'result.csv' result_dataset =",
"Get submission instances from train dataset instancesPopulation = len(train_dataset.Patient) indexList",
"after ML outcome ========================================= Purpose: Build a submission CSV file",
"Get models to include and their corresponding metrics ModelToInclude =",
"the Shape Parameter: It amounts to c = 0.12607421874999922 for",
"'Y:/Kaggle_OSIC/2-Data/' # if ProductType == 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data",
"= 0 if(submission_dataset.Patient[m] in IDList): referenceWeek = submission_dataset.Weeks[m] for n",
"| Phase 1: Get submission file template filename = 'sample_submission.csv'",
"but including Pydicom image-processing solution # Raw code reference (see",
"from distutils.dir_util import mkpath mkpath(path_destination) os.chdir(path_destination) submissionList = os.listdir(path_destination) number",
"functions for the pydicom project \"\"\" \"\"\" Test mode 1",
"= [3,3,3,3,3] shapeParameter_dictionary = {'Random Forest':c_List1, 'Lasso':c_List2, 'Gradient Boosting':c_List3, 'Stacking",
"\"\"\" \"\"\" Test mode 1 | Basics testMode = True",
"rawFile_DataFrame[IDlabel_rawFile][k] datum = round(datum,0) # Set datum in submission file",
"# ========================================= # Function : Dataset builder 2 (Stacking solution",
"given those from the test dataset (Features: Age, Sex, SmokingStatus)",
"train dataset) | Phase 2: Include values from train_adjusted_pydicom.py into",
"print(\"=========================================\") print(resultFunction3[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") \"\"\"",
"list(test_dataset.Patient) SDModel_List = list(standardDeviationClipped_DataFrame.columns) SDModel_index_List = list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns)",
"## Get DataFrame DataFrameToInclude = pd.DataFrame(data = DictionaryToInclude, index=[newIndex]) newIndex",
"2 (Stacking solution case) to process with ML models #",
"for j in model_List: # Data Fit task #r =",
"alpha=0.2) ax[k,l].legend(loc='best', frameon=False) # Set limits #ax[k,l].set_xlim(0,0.1) #ax[k,l].set_ylim(0,4) ax[k,l].set_xlabel('x') ax[k,l].set_ylabel('f(x,c)')",
"for a given Patient averageFVC = train_dataset_instancesToTransfer.FVC[train_dataset_instancesToTransfer.Patient == train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o]",
"distutils.ccompiler path_output = path_ProductType + 'submission/' distutils.dir_util.mkpath(path_output) ## Get submission",
"+ 1 plt.tight_layout() plt.show() resultFunction = c return resultFunction if",
"print(\"Data type of the dataset\") print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result",
"print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type:",
"import numpy as np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode",
"remove_tree(path_destination) create_tree(path_destination,[]) if testMode == True: print(\"=========================================\") print(\"Building the Sampling",
"submission file FVCDataList = FVCDataList + [datum] submissionFile_DataFrame['FVC'] = FVCDataList",
"numy + 1 numy = 0 # Get confidence measure",
"Phase 3: Create an adjusted train dataset | a. Remove",
"adjusted train dataset | c. Update the submission dataset with",
"== True: samplingSize = 5 resultFunction1 = trainDatasetSampler(samplingSize,testMode,reportMode) print(\"=========================================\") print(\"Population",
"random numbers: r = loglaplace.rvs(c1, loc=0, scale=1, size=1000) # And",
"data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv') # Get",
"i].ImageType)[0] # Put instance into train_dataset_adjusted DataFrame if (0 in",
"c = 0.126074 is assigned by default per model and",
"and its corresponding path if ProductType == 'population': path_ProductType =",
"information) available in file: \", filename_sampling) print(\"=========================================\") print(\"(2) Outcomes:\") print(\"=========================================\")",
"# Scenario to replace NaN values: Average FVC for a",
"additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted = pd.concat(frames) train_dataset_adjusted",
"i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].Weeks)[0] InstanceToInclude_indexType1_Exhalation = list(train_dataset_pydicom[train_dataset_pydicom.Patient ==",
"SDModel_List: itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL = loglaplace.std(c,",
"4: Create an adjusted train dataset | e. Concatenate the",
"list(shapeParameter_DataFrame.columns) numy = 0 from scipy.stats import loglaplace for j",
"IDList: IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] #",
"PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0])",
"if testMode == True: print(\"=========================================\") print(\"Building the Sampling Dataset given",
"test dataset (Features: Age, Sex, SmokingStatus) submission_dataset_range = len(submission_dataset.Patient) for",
"- Laplace Log Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result Function",
"scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x, c, loc=0, scale=1). \"\"\" def",
"filename_testDataset = 'test.csv' test_dataset = pd.read_csv(path_ProductType+filename_testDataset) # Get submission instances",
"Regressor'] ## Grouping task k = 0 l = 0",
"ProductType == 'population': path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' if ProductType == 'prototype':",
"(Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset = 'submissionInputDataset.csv' else: filename_submissionDataset",
"\"\"\" testMode = False reportMode = False \"\"\" ========================================= Function",
"k + 1 l = l + 1 plt.tight_layout() plt.show()",
"an stacking solution Raw code reference (see Tester.py): Test 15",
"log-laplace distribution (i.e. Laplace Log Likelihood) ========================================= Purpose: Get shape",
"confidence measure | Phase 2: Get standard-deviation-clipped per instance ##",
"import loglaplace for j in ID_List: for k in SDModel_List:",
"-> Dataframe for Sample\") print(\"result[2] -> Test Mode\") print(\"result[3] ->",
"for i in range (0,IDcases_List_range): IDcases_List[i] = IDcases_List[i][:-4] # Get",
"[datum] submissionFile_DataFrame['Confidence'] = CONDataList # Save file | Get directory",
"c)) # Returns True if two arrays are element-wise equal",
"IDList_index = IDList_index + list(IDList_index_dictionary[j]) submission_dataset = result_dataset.loc[IDList_index] # Get",
"pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for",
"filename_pydicom = 'train_pydicom.csv' path_ProductType_pydicom = path_ProductType + 'outcome/' train_dataset_pydicom =",
"function (pdf): x = np.linspace(loglaplace.ppf(0.01, c), loglaplace.ppf(0.99, c), num=100) ax[k,l].plot(x,",
"to DICOM files) os.chdir(path_source) ID_list = os.listdir(path_source) ID_list_range = len(ID_list)",
"dataset and reset index train_dataset_adjusted = train_dataset.drop(indexList) train_dataset_adjusted.reset_index # Adjust",
"== train_dataset_instancesToTransfer.Patient[p]].mean() submission_dataset.FVC[o] = averageFVC # Adjust train dataset |",
"given a must-usage of a log-laplace distribution (i.e. Laplace Log",
"'prototype': path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' if ProductType == 'sampling': path_ProductType",
"k in range(0,submissionNumber_range): for j in IDcases_List: # Get datum",
"= len(train_dataset.Patient) indexList = [] for i in IDList: for",
"= DICOMFileNumber_list + [DICOMFileNumber_list_unitary] Population_Dictionary = {'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data",
"5: Build Files for i in ModelToInclude: filename = 'sample_submission.csv'",
"path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output =",
"os.listdir(path_source_test) for l in IDList_test: path_source_unitary = path_source + l",
"in Population_DataFrame_IndexToSample): Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber]",
"print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\") print(\"Pydicom Mode: \", PydicomMode)",
"the outcome expressed under the variable result, outcomes are as",
"i].Sex)[0] repeatableInstance5 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].SmokingStatus)[0] ## Get Dictionary DictionaryToInclude",
"Product type ProductType = 'prototype' # ShapeParameter_Dataframe example = False",
"== 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if ProductType ==",
"Dataset given the Test Dataset of Kaggle for competition\") print(\"=========================================\")",
"variable result, outcomes are as follows:\") print(\"result[0] -> Dataframe for",
"ID_list = os.listdir(path_source) ID_list_range = len(ID_list) DICOMFile_list = [] DICOMFileNumber_list",
"= Week_List + [train_dataset_instancesToTransfer.Weeks[n]] FVC_List = FVC_List + [train_dataset_instancesToTransfer.FVC[n]] Percent_List",
"instances | Phase 2: Extract submission instances from result dataset",
"import os import pandas as pd # Set ProductType path_ProductType",
"1: standard_deviation_clipped = max(standard_deviation, 70) ## Build a DataFrame with",
"(2) # of DICOM files per ID (including percentage). ##",
"\"\"\" ========================================= Function 5: Get parameters given a must-usage of",
"| FVC FVCDataList = [] for k in range(0,submissionNumber_range): for",
"ax[k,l].plot(x, loglaplace.pdf(x, c),'r-', lw=5, alpha=0.6, label='loglaplace pdf') # Freeze the",
"========================================= Function 2: Submission Builder ========================================= Purpose: Build a submission",
"shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index =",
"True): variableNumber = 10 else: variableNumber = 7 MLModelList =",
"True except FileNotFoundError: GetCreation = False if GetCreation == False:",
"| Phase 2: Build dataset using the following features from",
"instance to transfer InstanceToInclude_Patient = i InstanceToInclude_Week = list(train_dataset_pydicom[train_dataset_pydicom.Patient ==",
"filename_output = 'train_adjusted_pydicom.csv' train_dataset_adjusted.to_csv(path_output+filename_output) # Function Result resultFunction = train_dataset_adjusted,path_output,filename_output",
"\"\"\" ========================================= Function 3: Dataset builder (Stacking solution case) to",
"as follows (staistical function in scipy renowend as scipy.stats.loglaplace): loglaplace.pdf(x,",
"= 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product Type:\") print(\"=========================================\") print(ProductType)",
"submission_dataset.SmokingStatus[m] = train_dataset_instancesToTransfer.SmokingStatus[n] timesCopy = timesCopy + 1 else: #",
"Data: FVC predictions; (2) Probability density function as follows (staistical",
"Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal <= samplingSize): randomNumberTermination =",
"submission_dataset = submission_dataset.join(metric_DataFrame) # Get confidence measure | Phase 5:",
"# Save file | Get directory path_destination = path_outcome+'submissions/' try:",
"submission files | Phase 3: Get correlative files_list = os.listdir(path_output)",
"pandas as pd ## Set Product Type and its corresponding",
"Support functions of pydicom (Not sourced) ========================================= Purpose: Create support",
"file template filename = 'sample_submission.csv' submissionFile = pd.read_csv(path_ProductType+filename) ## Get",
"False if GetCreation == False: from distutils.dir_util import mkpath mkpath(path_destination)",
"Create an adjusted train dataset | e. Concatenate the submission",
"in SDModel_List: itemToInclude = CParameter_List[numy] c = shapeParameter_DataFrame[itemToInclude][j] sd_LL =",
"DataFrame by default ## When shapeParameter_DataFrame==[], parameter c = 0.126074",
"SmokingStatus_List + [train_dataset_instancesToTransfer.SmokingStatus[n]] # Adjust train dataset | Phase 3:",
"'float64'}).dtypes train_dataset_adjusted.astype({'ImageType': 'O'}).dtypes # Get CSV file path_output = path_ProductType",
"nextNumber + 1 return resultFunction if testMode == True: #",
"== True: ProductType = 'prototype' PydicomMode = True reportMode =",
"Function Report testMode = False reportMode = True Commisionning mode",
"reportMode, testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction3[0]) print(\"=========================================\")",
"outcomes are as follows:\") print(\"result[0] -> Dataframe for Population\") print(\"result[1]",
"== True: print(\"=========================================\") print(\"Function Report\") print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\")",
"submission_dataset.FVC[o] = averageFVC # Adjust train dataset | Phase 4:",
"= DictionaryToInclude, index=[newIndex]) newIndex = newIndex + 1 ## Concatenate",
"Get Transferring data from train dataset instanceToTrasferList_index = [] for",
"mode 2 | Function Report testMode = False reportMode =",
"IDcases_List[i] = IDcases_List[i][:-4] # Get submission data as required in",
"# Get confidence measure | Phase 1: Get shape Parameter",
"ID and a ML Model: standardDeviationClipped_DataFrame standardDeviationClipped_DataFrame = shapeParameter_DataFrame.copy() columnLabels",
"Population_DataFrame_IndexToSample = Population_DataFrame_IndexToSample + [randomNumber] ID_unitary = Population_DataFrame.ID[randomNumber] Population_DataFrame_IDToSample =",
"train_dataset_instancesToTransfer.index train_dataset_instancesToTransfer = train_dataset_instancesToTransfer.reset_index() train_dataset_instancesToTransfer.drop(columns='index') # Adjust train dataset |",
"Purpose: Build an input dataset to be processed with an",
"= 'samplingDataset.csv' path_sampling = path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling",
"Get submission instances | Phase 3: Extract duplicated instances submission_dataset",
"from math import log1p for k in IDList: for i",
"path_output = path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler",
"Get submission files | Phase 2: Create directory try: path_output",
"an stacking solution but including Pydicom image-processing solution # Raw",
"# Returns True if two arrays are element-wise equal within",
"Test Mode\") print(\"result[3] -> Rerport Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame,",
"# of DICOM files per ID (including percentage). ## Improvement:",
"np path_resources = 'Y:/Kaggle_OSIC/3-Data (Prototype)/resources/' if (PydicomMode == False): filename_submissionDataset",
"= 0.126074 MLModelList = IDList_columns[2:] for l in MLModelList: keyShapeParameter",
"metric axe per model: |FVC_true - FVC_predicted| ## Metric -",
"fig, ax = plt.subplots(4, 5, sharex=False, sharey=False, figsize=(32, 24)) ##",
"else: # Additional instances to include Patient_List = Patient_List +",
"Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5 =",
"math.log1p(2**0.5 * SDC) metric = metric_part1 + metric_part2 submission_dataset[i][j] =",
"len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename, testMode",
"True resultFunction4 = Stacking_Submission_Dataset_Builder(ProductType,shapeParameter_DataFrame,pydicomMode,testMode) print(\"=========================================\") print(\"Shape Parameter - Laplace Log",
"= pd.read_csv(path_ProductType+filename) submissionFile_columns = list(submissionFile.columns) fvc_array = np.array(submission_dataset[i]) confidence_array =",
"= list(standardDeviationClipped_DataFrame.index) metric_lists = list(metric_DataFrame.columns) metric_index_lists = list(metric_DataFrame.index) submission_dataset_index_List =",
"# Set ProductType path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # Set productType and",
"Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan filling train_dataset_adjusted",
"(Sampling)/' # Set outcome path_outcome = path_ProductType + 'outcome/' #",
"j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles * 100",
"= i newIndex = len(train_dataset_adjusted.Patient) for i in instancesToInclude_List: #",
"Population_DataFrame.Percentage[randomNumber] samplingSizeGoal = samplingSizeGoal + samplingSize_unitary samplingDataset_Dictionary = {'Index':Population_DataFrame_IndexToSample,'ID':Population_DataFrame_IDToSample,'Percentage':Population_DataFrame_PercentageToSample} samplingDataset_DataFrame",
"if ProductType == 'population': # path_ProductType = 'Y:/Kaggle_OSIC/2-Data/' # if",
"GetCreation = True except FileNotFoundError: GetCreation = False if GetCreation",
"print(\"Building the Sampling Dataset given the Train Dataset of Kaggle",
"pandas as pd shapeParameter_IDList = ['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2",
"Extract submission instances from result dataset IDList_index = [] IDList_columns",
"testMode = False reportMode = True Commisionning mode testMode =",
"= len(submission_dataset_index_List) indexPerID_dictionary = {} ### Step 1: Get index",
"ShapeParameter_Dataframe example = False if (example == True): import pandas",
"# Set Product type ProductType = 'prototype' # ShapeParameter_Dataframe resultFunction5",
"from datetime import date reportDate = date.today() print(\"=========================================\") print(\"Function Report",
"(0,train_dataset_instancesToTransfer_range): if(train_dataset_instancesToTransfer.Patient[n] == submission_dataset.Patient[m] and train_dataset_instancesToTransfer.Weeks[n] == referenceWeek): if (timesCopy",
"per model: min(|FVC_true - FVC_predicted|, 1000) ## metric per instance",
"solution # Raw code reference (see Tester.py): 15 # \"\"\"",
"test dataset import pandas as pd filename_trainDataset = 'train.csv' train_dataset",
"the train data; (2) the location path of the sampling",
"shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary, index = shapeParameter_IDList) else: shapeParameter_DataFrame",
"[Percentage] Population_Percentage_Dictionary = {'Percentage':DICOMFilePercentage_list} Population_Percentage_DataFrame = pd.DataFrame(data=Population_Percentage_Dictionary) Population_DataFrame = pd.concat([Population_DataFrame,",
"== True: print(\"=========================================\") print(\"Building the Sampling Dataset given the Train",
"repeatable instances repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient",
"submission_dataset.columns[5]:Sex_List, submission_dataset.columns[6]:SmokingStatus_List} additional_dataset = pd.DataFrame(data=additionalDictionary) frames = [train_dataset_adjusted,submission_dataset,additional_dataset] train_dataset_adjusted =",
"{'ID':ID_list,'NumberDicomFiles':DICOMFileNumber_list,'DicomFIles':DICOMFile_list} Population_DataFrame = pd.DataFrame(data = Population_Dictionary) DICOMFilePercentage_list = [] TotalNumberDicomFiles",
"in submission file | Confidence CONDataList = [] for k",
"= np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) # Returns True if",
"a submission CSV file Raw code reference (see Tester.py): Test",
"[] IDList_columns = ['Patient', 'Weeks', 'Random Forest', 'Lasso', 'Gradient Boosting',",
"(ascending) and reset index submission_dataset = submission_dataset.sort_values(by=['Weeks','Patient']) submission_dataset = submission_dataset.reset_index()",
"model_List = ['Random Forest', 'Lasso', 'Gradient Boosting', 'Stacking Regressor'] ##",
"ProductType == 'prototype': # path_ProductType = 'Y:/Kaggle_OSIC/3-Data (Prototype)/' # if",
"========================================= Purpose: Build an input dataset to be processed with",
"parameters given a must-usage of a log-laplace distribution (i.e. Laplace",
"* 100 Percentage = round(Percentage,6) DICOMFilePercentage_list = DICOMFilePercentage_list + [Percentage]",
"Function 4: Submission dataset builder (Stacking solution case) after ML",
"= path_ProductType + 'submission/' os.chdir(path_output) except FileNotFoundError: import distutils.ccompiler path_output",
"[]): shapeParameter_dictionary = {} shapeParameter = 0.126074 MLModelList = IDList_columns[2:]",
"print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size :\", samplingSize, \"%\") print(\"-Test Mode",
"shapeParameter_dictionary, index = IDList) # Get confidence measure | Phase",
"InstanceToInclude_indexType1_Exhalation train_dataset_adjusted.indexType1_Inhalation[indexToComplete] = InstanceToInclude_indexType1_Inhalation train_dataset_adjusted.ImageType[indexToComplete] = str(InstanceToInclude_ImageType) else: # Add",
"DICOMFilePercentage_list = [] TotalNumberDicomFiles = sum(Population_DataFrame.NumberDicomFiles) for j in range(0,ID_list_range):",
"lw=5, alpha=0.6, label='loglaplace pdf') # Freeze the distribution and display",
"train_dataset.Patient[k] == l: instanceToTransfer_Index = train_dataset.index[k] instanceToTrasferList_index = instanceToTrasferList_index +",
"'Stacking Regressor'] for j in IDList: IDList_index = IDList_index +",
"1 ## Concatenate DataFrame train_dataset_adjusted = pd.concat([train_dataset_adjusted, DataFrameToInclude]) # nan",
"test path = path_ProductType filename = 'test.csv' test_dataset = pd.read_csv(path+filename)",
"0.999], c) accuracy = np.allclose([0.001, 0.5, 0.999], loglaplace.cdf(vals, c)) #",
"= list(train_dataset_pydicom[train_dataset_pydicom.Patient == i].ImageType)[0] # Put instance into train_dataset_adjusted DataFrame",
"path_destination_outcome samplingDataset_DataFrame.to_csv(path_sampling+filename_sampling) # Build a Sampling dataset | Phase 3:",
"Get submission data as required in submission file | FVC",
"print(\"=========================================\") print(\"DataFrame\") print(\"=========================================\") print(resultFunction[0]) print(\"=========================================\") print(\"Product Type: \", ProductType) print(\"=========================================\")",
"in IDList: listToInclude = list(submission_dataset.Patient[submission_dataset.Patient == i].index) indexPerID_dictionary[i] = listToInclude",
"DataFrame os.chdir(path_ProductType) submissionFile_DataFrame = pd.read_csv('sample_submission.csv') # Get submission data as",
"print(\"=========================================\") print(resultFunction[0].dtypes) print(\"=========================================\") print(\"Test result Function 3: Success\") print(\"=========================================\") return",
"Population_DataFrame_IDToSample=[] Population_DataFrame_PercentageToSample=[] samplingSizeGoal = 0 while (samplingSizeGoal <= samplingSize): randomNumberTermination",
"= 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/' # Build a",
"= pd.read_csv(path_ProductType_pydicom + filename_pydicom) # Adjust train dataset with pydicom",
"trainDatasetSampler(samplingSize,testMode)\") print(\"=========================================\") print(\"(1) Inputs\") print(\"=========================================\") print(\"-Sampling Size :\", samplingSize, \"%\")",
"filename_population) print(\"-Sample of Train dataset (just information) available in file:",
"= {} shapeParameter = 0.126074 MLModelList = IDList_columns[2:] for l",
"'Y:/Kaggle_OSIC/4-Data (Sampling)/train/' path_destination_test = 'Y:/Kaggle_OSIC/4-Data (Sampling)/test/' path_destination_outcome = 'Y:/Kaggle_OSIC/4-Data (Sampling)/outcome/'",
"-> Rerport Mode\") print(\"=========================================\") return Population_DataFrame, samplingDataset_DataFrame, testMode, reportMode if",
"in submission file submissionNumber_range = len(rawFile_DataFrame.index) IDcases_List = submissionFile_DataFrame.Patient_Week.copy() IDcases_List",
"Phase 5: Get metric axe per model: (-1 * differential",
"Likelihood:\") print(\"=========================================\") print(resultFunction5) print(\"=========================================\") print(\"Test result Function 4: Success\") print(\"=========================================\")",
"case) Raw code reference (see Tester.py): Test 17 About the",
"abs(submission_dataset.FVC - submission_dataset[j]) metric_differential = list(metric_differential) keyToInclude = 'metric_'+j metric_dictionary[keyToInclude]",
"of Kaggle for competition\") print(\"=========================================\") IDList_test = os.listdir(path_source_test) for l",
"resultFunction3 = stacking_Dataset_Builder(ProductType, PydicomMode, reportMode, testMode) print(\"=========================================\") print(\"Function Report\") print(\"=========================================\")",
"Test mode 2 | Function Report testMode = False reportMode",
"| Accuracy:'+accuracy) ax[k,l].set_title(title) k = k + 1 l =",
"repeatableInstance1 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].FVC)[0] repeatableInstance2 = list(train_dataset_adjusted[train_dataset_adjusted.Patient == i].Percent)[0]",
"Likelihood) ========================================= Purpose: Get shape parameter visualization for loglaplace Raw",
"for j in range(0,ID_list_range): Percentage = Population_DataFrame['NumberDicomFiles'][j] / TotalNumberDicomFiles *",
"print(\"=========================================\") print(\"Input File saved as:\", resultFunction[2]) print(\"=========================================\") print(\"Data type of",
"j in list(indexPerID_DataFrame[k]): differential = submission_dataset[i][j] SDC_Label = 'SD_Clipped_' +",
"= 'population' filename = 'submissionRawFile_2020_09_19.csv' resultFunction2 = SubmissionBuilder(ProductType,filename,testMode) print(\"=========================================\") print(\"Product",
"of Input File:\", resultFunction[1]) print(\"=========================================\") print(\"Input File saved as:\", resultFunction[2])",
"= list(standardDeviationClipped_DataFrame.index) SDModel_List = list(standardDeviationClipped_DataFrame.columns) CParameter_List = list(shapeParameter_DataFrame.columns) numy =",
"3: Get metric axe per model: |FVC_true - FVC_predicted| ##",
"= len(submissionList) filename = 'submission_'+str(number+1)+'.csv' submissionFile_DataFrame.to_csv(filename, index=False) return submissionFile_DataFrame, filename,",
"['ID00419637202311204720264','ID00421637202311550012437','ID00422637202311677017371','ID00423637202312137826377','ID00426637202313170790466'] c_List1 = [3,3,3,3,3] c_List2 = [3,3,3,3,3] c_List3 = [3,3,3,3,3]",
"to c = 0.12607421874999922 for every instance in the oject",
"figsize=(32, 24)) ## Get IDs to test import os import",
"file: \", filename_population) print(\"-Sample of Train dataset (just information) available",
"\"\"\" \"\"\" ========================================= Support functions of pydicom (Not sourced) =========================================",
"skew, kurt = loglaplace.stats(c, moments='mvsk') # Display the probability density",
"# Function : Dataset builder 2 (Stacking solution case) to",
"with pydicom train dataset) | Phase 1: Get pydicom train",
"= loglaplace.ppf([0.001, 0.5, 0.999], c) accuracy = np.allclose([0.001, 0.5, 0.999],",
"i in instancesToInclude_List: # Get instance to transfer InstanceToInclude_Patient =",
"'c Parameter_'+l shapeParameter_dictionary[keyShapeParameter] = [shapeParameter,shapeParameter,shapeParameter,shapeParameter,shapeParameter] shapeParameter_DataFrame = pd.DataFrame(data = shapeParameter_dictionary,",
"Get raw data as a DataFrame os.chdir(path_outcome) rawFile_DataFrame = pd.read_csv('submissionRawFile_2020_09_19.csv')",
"= list(metric_DataFrame.index) submission_dataset_index_List = list(submission_dataset.index) instancesNumber = len(submission_dataset_index_List) indexPerID_dictionary =",
"Phase 2: Create directory try: path_output = path_ProductType + 'submission/'"
] |
[
"for kw_parent in keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return",
"p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\",",
"span_label.text: for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except Exception",
"regex_find = r'•(.*)→(.*)' regex_replace = r'\\1;\\2' # set the delimiter",
"keywords_list = cogsci(soup) elif publisher == \"springer_v1\": keywords_list = springer_v1(soup)",
"= scitepress(soup) elif publisher == \"scienceopen\": keywords_list = scienceopen(soup) elif",
"== \"dagstuhl\": keywords_list = dagstuhl(soup) elif publisher == \"aaai\": keywords_list",
"user interfaces (GUI) # Step 1: Remove annoying substrings #",
"\"scienceopen\": keywords_list = scienceopen(soup) elif publisher == \"eurographics_digital_library\": keywords_list =",
"= [\"CCS Concepts\", \"Categories and Subject Descriptors\", \"Categories and subject",
"to ACM CCS\"] keywords_str = keywords_li.find(\"a\").text for to_replace in to_replaces:",
"have '[' and ']' but they have strings such as",
"keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set = set() for keywords_li in",
"Concepts don't have '[' and ']' but they have strings",
"e: print(e) return None def springer_v1(soup): try: keywords = set()",
"keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except Exception",
"if p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled",
"return list(keywords_set) except Exception as e: print(e) return None def",
"between []. # Step 3: Split the string by ,",
"publisher == \"scienceopen\": keywords_list = scienceopen(soup) elif publisher == \"eurographics_digital_library\":",
"== \"scienceopen\": keywords_list = scienceopen(soup) elif publisher == \"eurographics_digital_library\": keywords_list",
"']' but they have strings such as \"• Human‐centered computing",
"kw_parent in keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords)",
"e.g. CASE 2 [TODO: Not taken care of yet] Categories",
"and Subject Descriptors\", \"Categories and subject descriptors\", \"Categories and Subject",
"keywords_parent_td = keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not",
"keywords_ul = keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set = set() for",
"= keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs: kw = kw_parent.text",
"class_=\"label-cell\") if label.text == \"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\") #",
"None def aaai(soup): return None def get_keywords(publisher, soup): keywords_list =",
"re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS Concepts don't",
"keywords_font.text) except Exception as e: print(e) return None def springer_v1(soup):",
"return list(keywords) except Exception as e: print(e) return None def",
"= keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in keywords_span: keywords.add(k.text) return list(keywords)",
"as e: print(e) return None def scienceopen(soup): try: keywords_set =",
"= tr.find(\"td\", class_=\"word-break\") # e.g. CASE 1: ['Categories and Subject",
"Case 2: CCS Concepts don't have '[' and ']' but",
"e: print(e) return None def scienceopen(soup): try: keywords_set = set()",
"\"Categories and Subject Descriptors\", \"Categories and subject descriptors\", \"Categories and",
"try: keywords = set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span =",
"None def cogsci(soup): return None def scitepress(soup): try: keywords_set =",
"class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li in",
"\"• Human‐centered computing → Graph drawings\" regex_find = r'•(.*)→(.*)' regex_replace",
"set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"): keywords_set.add(kw)",
"keywords_li in keywords_lis: # e.g. Case 1: \"[3.1.1] Human-Centered Computing\"",
"\"cogsci\": keywords_list = cogsci(soup) elif publisher == \"springer_v1\": keywords_list =",
"list(keywords) except Exception as e: print(e) return None def wiley_online_library(soup):",
"stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li in gp_li:",
"publisher == \"dagstuhl\": keywords_list = dagstuhl(soup) elif publisher == \"aaai\":",
"\"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif publisher == \"wiley_online_library\": keywords_list =",
"publisher == \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\":",
"keywords_list = springer_v2(soup) elif publisher == \"scitepress\": keywords_list = scitepress(soup)",
"Graph drawings\" # Step 1: Remove annoying substrings # Step",
"# e.g. CASE 1: ['Categories and Subject Descriptors (according to",
"I.4.1 [Image Processing and Computer Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]:",
"to ACM CCS): Information Interfaces And Presentation (e.g., HCI) [H.5.2]:",
"kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except Exception as",
"the string by , or ; or : to_replaces =",
"Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap and framebuffer operations']",
"keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return",
"== \"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\") # e.g. CASE 1:",
"class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs:",
"class_=\"doc-keywords-list-item\", recursive=False) for p_li in gp_li: if p_li.find('strong').text in [\"IEEE",
"for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if",
"recursive=False) for p_li in gp_li: if p_li.find('strong').text in [\"IEEE Keywords\",",
"Interfaces-Graphical user interfaces (GUI) # Step 1: Remove annoying substrings",
"e: print(e) return None def dagstuhl(soup): try: keywords_label = soup.find('b',",
"class_=\"c-article-subject-list__subject\") for k in keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip())",
"= wiley_online_library(soup) elif publisher == \"dagstuhl\": keywords_list = dagstuhl(soup) elif",
"None def ieee_explore(soup): try: keywords = set() ggp_ul = soup.find('ul',",
"> Write a REGEX to take substrings between []. #",
"descriptors\", \"Categories and Subject Descriptors (according to ACM CCS)\", \"according",
"keywords_list = springer_v1(soup) elif publisher == \"springer_v2\": keywords_list = springer_v2(soup)",
"= soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set)",
"Computing\" and so on # e.g. Case 2: CCS Concepts",
"computing → Graph drawings\" # Step 1: Remove annoying substrings",
"publisher == \"acm_digital_library\": keywords_list = acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\":",
"Presentation (e.g., HCI) [H.5.2]: User Interfaces-Graphical user interfaces (GUI) #",
"\"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\": keywords_list =",
"def springer_v1(soup): try: keywords = set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\")",
"as e: print(e) return None def cogsci(soup): return None def",
"keywords_list = graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\": keywords_list = ieee_explore(soup)",
"return None def wiley_online_library(soup): try: keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul",
"acm_digital_library(soup): try: keywords = set() keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\")",
"organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs: kw",
"return None def eurographics_digital_library(soup): try: keywords_set = set() p_tablebody =",
"set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for",
"Graph drawings\" regex_find = r'•(.*)→(.*)' regex_replace = r'\\1;\\2' # set",
"ONLY Categories, not the Subject Descriptors > Write a REGEX",
"CASE 1: ['Categories and Subject Descriptors (according to ACM CCS):",
"keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag",
"Subject Descriptors (according to ACM CCS): Information Interfaces And Presentation",
"kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except Exception as e:",
"regex_replace = r'\\1;\\2' # set the delimiter to either ,",
"None def wiley_online_library(soup): try: keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul =",
"springer_v1(soup) elif publisher == \"springer_v2\": keywords_list = springer_v2(soup) elif publisher",
"= springer_v1(soup) elif publisher == \"springer_v2\": keywords_list = springer_v2(soup) elif",
"for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except Exception as",
"re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords = set() keywords_parent_ol = soup.find('ol',",
"to ACM CCS): I.4.1 [Image Processing and Computer Vision]: Enhancement-Filtering",
"e: pass return None def aaai(soup): return None def get_keywords(publisher,",
"soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font =",
"if \"Keywords\" in span_label.text: for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return",
"to take substrings between []. # Step 3: Split the",
"for span_label in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text: for",
"# CCS Concepts don't have '[' and ']' but they",
"taken care of yet] Categories and Subject Descriptors (according to",
"User Interfaces-Graphical user interfaces (GUI) # Step 1: Remove annoying",
"= keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not None: return re.split(',', keywords_font.text)",
"wiley_online_library(soup): try: keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis",
"annoying substrings # Step 2: Choose to take ONLY Categories,",
"in p_trs: label = tr.find(\"td\", class_=\"label-cell\") if label.text == \"dc.subject\":",
"soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in",
"Descriptors > Write a REGEX to take substrings between [].",
"None def get_keywords(publisher, soup): keywords_list = None if publisher ==",
"subject descriptors\", \"Categories and Subject Descriptors (according to ACM CCS)\",",
"soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text: for keyword_a in span_label.find_next_siblings('a'):",
"either , : ; (as is used below to split)",
"elif publisher == \"ieee_explore\": keywords_list = ieee_explore(soup) elif publisher ==",
"keywords_lis: # e.g. Case 1: \"[3.1.1] Human-Centered Computing\" and so",
"CCS\"] keywords_str = keywords_li.find(\"a\").text for to_replace in to_replaces: keywords_str =",
"used below to split) keywords_str = re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;',",
"= scienceopen(soup) elif publisher == \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif",
"\"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\") # e.g. CASE 1: ['Categories",
"e: print(e) return None def eurographics_digital_library(soup): try: keywords_set = set()",
"k in keywords_span: keywords.add(k.text) return list(keywords) except Exception as e:",
"keywords_set = set() for span_label in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\"",
"the Subject Descriptors > Write a REGEX to take substrings",
"except Exception as e: print(e) return None def wiley_online_library(soup): try:",
"print(e) return None def scienceopen(soup): try: keywords_set = set() for",
"is used below to split) keywords_str = re.sub(regex_find, regex_replace, keywords_str)",
"list(keywords_set) except Exception as e: print(e) return None def scienceopen(soup):",
"2: Choose to take ONLY Categories, not the Subject Descriptors",
"\"springer_v2\": keywords_list = springer_v2(soup) elif publisher == \"scitepress\": keywords_list =",
"keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as",
"\"ieee_explore\": keywords_list = ieee_explore(soup) elif publisher == \"cogsci\": keywords_list =",
"to take ONLY Categories, not the Subject Descriptors > Write",
"[Image Processing and Computer Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image",
"return None def ieee_explore(soup): try: keywords = set() ggp_ul =",
"gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li in gp_li: if",
"to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]',",
"soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li",
"Exception as e: print(e) return None def graphics_interface_proceedings(soup): return None",
"keywords.text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted",
"dagstuhl(soup) elif publisher == \"aaai\": keywords_list = aaai(soup) return None",
"p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for tr in",
"\"scitepress\": keywords_list = scitepress(soup) elif publisher == \"scienceopen\": keywords_list =",
"keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in keywords_span: keywords.add(k.text) return",
"Categories and Subject Descriptors (according to ACM CCS): Information Interfaces",
"below to split) keywords_str = re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str))",
"Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\",",
"Remove annoying substrings # Step 2: Choose to take ONLY",
"Descriptors (according to ACM CCS): Information Interfaces And Presentation (e.g.,",
"soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in keywords_li:",
", or ; or : to_replaces = [\"CCS Concepts\", \"Categories",
"kw)).strip()) return list(keywords) except Exception as e: print(e) return None",
"keywords_set = set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr')",
"CCS): Information Interfaces And Presentation (e.g., HCI) [H.5.2]: User Interfaces-Graphical",
"\"Categories and subject descriptors\", \"Categories and Subject Descriptors (according to",
"springer_v2(soup) elif publisher == \"scitepress\": keywords_list = scitepress(soup) elif publisher",
"def graphics_interface_proceedings(soup): return None def ieee_explore(soup): try: keywords = set()",
"CASE 2 [TODO: Not taken care of yet] Categories and",
"Descriptors (according to ACM CCS)\", \"according to ACM CCS\"] keywords_str",
"\"according to ACM CCS\"] keywords_str = keywords_li.find(\"a\").text for to_replace in",
"= ieee_explore(soup) elif publisher == \"cogsci\": keywords_list = cogsci(soup) elif",
"return None def scitepress(soup): try: keywords_set = set() keywords_span =",
"== \"aaai\": keywords_list = aaai(soup) return None if len(keywords_list) ==",
"e.g. Case 2: CCS Concepts don't have '[' and ']'",
"print(e) return None def springer_v1(soup): try: keywords = set() keywords_parent_section",
"= set() keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div',",
"Not taken care of yet] Categories and Subject Descriptors (according",
"; (as is used below to split) keywords_str = re.sub(regex_find,",
"in keywords_span: keywords.add(k.text) return list(keywords) except Exception as e: print(e)",
"they have strings such as \"• Human‐centered computing → Graph",
"== \"springer_v1\": keywords_list = springer_v1(soup) elif publisher == \"springer_v2\": keywords_list",
"ACM CCS\"] keywords_str = keywords_li.find(\"a\").text for to_replace in to_replaces: keywords_str",
"keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as e:",
"keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k",
"keywords = set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\",",
"re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set)",
"[\"CCS Concepts\", \"Categories and Subject Descriptors\", \"Categories and subject descriptors\",",
"Graphics]: Picture/Image Generation-Bitmap and framebuffer operations'] # e.g. CASE 2",
"keywords = set() keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs =",
"delimiter to either , : ; (as is used below",
"set() keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True)",
"span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except Exception as e: pass return",
"graphics_interface_proceedings(soup): return None def ieee_explore(soup): try: keywords = set() ggp_ul",
"Non-Controlled Indexing\", \"MeSH Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag",
"Step 2: Choose to take ONLY Categories, not the Subject",
"soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for tr in p_trs: label",
"Picture/Image Generation-Bitmap and framebuffer operations'] # e.g. CASE 2 [TODO:",
"in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except Exception as e: print(e)",
"Human‐centered computing → Graph drawings\" regex_find = r'•(.*)→(.*)' regex_replace =",
"= set() for keywords_li in keywords_lis: # e.g. Case 1:",
"set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for",
"keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except Exception as e: print(e) return",
"CCS\"] keywords_str = keywords.text for to_replace in to_replaces: keywords_str =",
"= acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif",
"else: # CCS Concepts don't have '[' and ']' but",
"keywords_str = keywords_li.find(\"a\").text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace,",
"e: print(e) return None def wiley_online_library(soup): try: keywords_parent_section = soup.find('section',",
"keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as e: print(e)",
"return None def aaai(soup): return None def get_keywords(publisher, soup): keywords_list",
"None def scienceopen(soup): try: keywords_set = set() for span_label in",
"# e.g. Case 1: \"[3.1.1] Human-Centered Computing\" and so on",
"; or : to_replaces = [\"CCS Concepts\", \"Categories and Subject",
"CCS)\", \"according to ACM CCS\"] keywords_str = keywords_li.find(\"a\").text for to_replace",
"p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is not",
"list(keywords) except Exception as e: print(e) return None def eurographics_digital_library(soup):",
"Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap and framebuffer operations'] #",
"e.g. Case 1: \"[3.1.1] Human-Centered Computing\" and so on #",
"computing → Graph drawings\" regex_find = r'•(.*)→(.*)' regex_replace = r'\\1;\\2'",
"if a_tag is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0])))",
"publisher == \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif publisher == \"wiley_online_library\":",
"graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\": keywords_list = ieee_explore(soup) elif publisher",
"keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs: kw =",
"of yet] Categories and Subject Descriptors (according to ACM CCS):",
"as e: print(e) return None def dagstuhl(soup): try: keywords_label =",
"keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except Exception as e: print(e) return",
"\"[3.1.1] Human-Centered Computing\" and so on # e.g. Case 2:",
"except Exception as e: print(e) return None def springer_v1(soup): try:",
"keywords_list = acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup)",
"re.split(',', keywords_font.text) except Exception as e: print(e) return None def",
"keywords_ul.findChildren(\"li\") keywords_set = set() for keywords_li in keywords_lis: # e.g.",
"\"springer_v1\": keywords_list = springer_v1(soup) elif publisher == \"springer_v2\": keywords_list =",
"try: keywords_set = set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs =",
"keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not None: return re.split(',',",
"import re regex = re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords =",
"3: Split the string by , or ; or :",
"set() for span_label in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text:",
"list(keywords_set) except Exception as e: pass return None def aaai(soup):",
"in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text: for keyword_a in",
"1: \"[3.1.1] Human-Centered Computing\" and so on # e.g. Case",
"['Categories and Subject Descriptors (according to ACM CCS): I.4.1 [Image",
"in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except Exception as e: pass",
"= set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\")",
"except Exception as e: print(e) return None def dagstuhl(soup): try:",
"try: keywords_set = set() for span_label in soup.find_all('span', class_=\"so-metadata-label\"): if",
"== \"acm_digital_library\": keywords_list = acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\": keywords_list",
"return None def graphics_interface_proceedings(soup): return None def ieee_explore(soup): try: keywords",
"if label.text == \"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\") # e.g.",
"print(e) return None def wiley_online_library(soup): try: keywords_parent_section = soup.find('section', class_=\"keywords\")",
"and Computer Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap and",
"= aaai(soup) return None if len(keywords_list) == 0 else keywords_list",
"= set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for",
"= cogsci(soup) elif publisher == \"springer_v1\": keywords_list = springer_v1(soup) elif",
"\"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]: for keywords_l",
"try: keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis =",
"# set the delimiter to either , : ; (as",
"CCS)\", \"according to ACM CCS\"] keywords_str = keywords.text for to_replace",
"def scitepress(soup): try: keywords_set = set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\")",
"2: CCS Concepts don't have '[' and ']' but they",
"= tr.find(\"td\", class_=\"label-cell\") if label.text == \"dc.subject\": keywords = tr.find(\"td\",",
"\"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;',",
"not None: return re.split(',', keywords_font.text) except Exception as e: print(e)",
"publisher == \"springer_v2\": keywords_list = springer_v2(soup) elif publisher == \"scitepress\":",
"# Step 1: Remove annoying substrings # Step 2: Choose",
"as e: print(e) return None def springer_v1(soup): try: keywords =",
"\"aaai\": keywords_list = aaai(soup) return None if len(keywords_list) == 0",
"keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is",
"list(keywords_set) except Exception as e: print(e) return None def springer_v2(soup):",
"tr.find(\"td\", class_=\"label-cell\") if label.text == \"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\")",
"= None if publisher == \"acm_digital_library\": keywords_list = acm_digital_library(soup) elif",
"as e: print(e) return None def wiley_online_library(soup): try: keywords_parent_section =",
"keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS",
"→ Graph drawings\" # Step 1: Remove annoying substrings #",
"e: print(e) return None def springer_v2(soup): try: keywords = set()",
"substrings between []. # Step 3: Split the string by",
"= springer_v2(soup) elif publisher == \"scitepress\": keywords_list = scitepress(soup) elif",
"def springer_v2(soup): try: keywords = set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\")",
"(as is used below to split) keywords_str = re.sub(regex_find, regex_replace,",
"CCS Concepts don't have '[' and ']' but they have",
"= set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"):",
"to either , : ; (as is used below to",
"label.text == \"dc.subject\": keywords = tr.find(\"td\", class_=\"word-break\") # e.g. CASE",
"scienceopen(soup): try: keywords_set = set() for span_label in soup.find_all('span', class_=\"so-metadata-label\"):",
"keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except Exception as e:",
"elif publisher == \"scitepress\": keywords_list = scitepress(soup) elif publisher ==",
"(according to ACM CCS)\", \"according to ACM CCS\"] keywords_str =",
"a REGEX to take substrings between []. # Step 3:",
"None def springer_v2(soup): try: keywords = set() keywords_parent_div = soup.find('div',",
"keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS Concepts don't have '[' and",
"if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception",
"and subject descriptors\", \"Categories and Subject Descriptors (according to ACM",
"in keywords_lis: # e.g. Case 1: \"[3.1.1] Human-Centered Computing\" and",
"str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception as e: print(e) return None",
"2 [TODO: Not taken care of yet] Categories and Subject",
"to ACM CCS)\", \"according to ACM CCS\"] keywords_str = keywords.text",
"tr.find(\"td\", class_=\"word-break\") # e.g. CASE 1: ['Categories and Subject Descriptors",
"list(keywords) except Exception as e: print(e) return None def dagstuhl(soup):",
"keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not None: return re.split(',', keywords_font.text) except",
"== \"scitepress\": keywords_list = scitepress(soup) elif publisher == \"scienceopen\": keywords_list",
"keywords = set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li =",
"return None def cogsci(soup): return None def scitepress(soup): try: keywords_set",
"== \"springer_v2\": keywords_list = springer_v2(soup) elif publisher == \"scitepress\": keywords_list",
"keywords_str = re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except",
"elif publisher == \"cogsci\": keywords_list = cogsci(soup) elif publisher ==",
"= keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not None:",
"regex = re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords = set() keywords_parent_ol",
"== \"cogsci\": keywords_list = cogsci(soup) elif publisher == \"springer_v1\": keywords_list",
"print(e) return None def cogsci(soup): return None def scitepress(soup): try:",
"e.g. CASE 1: ['Categories and Subject Descriptors (according to ACM",
"print(e) return None def eurographics_digital_library(soup): try: keywords_set = set() p_tablebody",
"keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else:",
"keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception as e: print(e) return",
"None def eurographics_digital_library(soup): try: keywords_set = set() p_tablebody = soup.find('table',",
"to ACM CCS)\", \"according to ACM CCS\"] keywords_str = keywords_li.find(\"a\").text",
"and Subject Descriptors (according to ACM CCS): Information Interfaces And",
"return None def springer_v1(soup): try: keywords = set() keywords_parent_section =",
", : ; (as is used below to split) keywords_str",
"try: keywords = set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li",
"keywords_set.add(kw) return list(keywords_set) except Exception as e: print(e) return None",
"as e: pass return None def aaai(soup): return None def",
"elif publisher == \"scienceopen\": keywords_list = scienceopen(soup) elif publisher ==",
"keywords_set = set() for keywords_li in keywords_lis: # e.g. Case",
"Generation-Bitmap and framebuffer operations'] # e.g. CASE 2 [TODO: Not",
"publisher == \"aaai\": keywords_list = aaai(soup) return None if len(keywords_list)",
"\"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False):",
"= keywords_ul.findChildren(\"li\") keywords_set = set() for keywords_li in keywords_lis: #",
"keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else:",
"k in keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords)",
"except Exception as e: pass return None def aaai(soup): return",
"set the delimiter to either , : ; (as is",
"= soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for kw_parent",
"class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set = set()",
"scienceopen(soup) elif publisher == \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif publisher",
"= r'\\1;\\2' # set the delimiter to either , :",
"as \"• Human‐centered computing → Graph drawings\" # Step 1:",
"publisher == \"scitepress\": keywords_list = scitepress(soup) elif publisher == \"scienceopen\":",
"Descriptors (according to ACM CCS): I.4.1 [Image Processing and Computer",
"not the Subject Descriptors > Write a REGEX to take",
"\"dagstuhl\": keywords_list = dagstuhl(soup) elif publisher == \"aaai\": keywords_list =",
"on # e.g. Case 2: CCS Concepts don't have '['",
"except Exception as e: print(e) return None def scienceopen(soup): try:",
"def acm_digital_library(soup): try: keywords = set() keywords_parent_ol = soup.find('ol', class_=\"rlist",
"don't have '[' and ']' but they have strings such",
"in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str)",
"def aaai(soup): return None def get_keywords(publisher, soup): keywords_list = None",
"keywords_parent_ol.findChildren('div', recursive=True) for kw_parent in keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\",",
"keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k",
"keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception as",
"for k in keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return",
"Step 3: Split the string by , or ; or",
"Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]: for keywords_l in",
"= keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in keywords_li: kw = k.find(\"span\").text",
"aaai(soup): return None def get_keywords(publisher, soup): keywords_list = None if",
"keywords_list = wiley_online_library(soup) elif publisher == \"dagstuhl\": keywords_list = dagstuhl(soup)",
"soup): keywords_list = None if publisher == \"acm_digital_library\": keywords_list =",
"[H.5.2]: User Interfaces-Graphical user interfaces (GUI) # Step 1: Remove",
"is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords)",
"in span_label.text: for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set) except",
"class_=\"Keyword\") for k in keywords_span: keywords.add(k.text) return list(keywords) except Exception",
"\"• Human‐centered computing → Graph drawings\" # Step 1: Remove",
"\"MeSH Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\",",
"keywords_set.add(keyword_a.text) return list(keywords_set) except Exception as e: pass return None",
"= re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return",
"as e: print(e) return None def eurographics_digital_library(soup): try: keywords_set =",
"class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in keywords_li: kw",
"regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as e:",
"substrings # Step 2: Choose to take ONLY Categories, not",
"= soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in",
"\"according to ACM CCS\"] keywords_str = keywords.text for to_replace in",
"= soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in",
"ACM CCS): Information Interfaces And Presentation (e.g., HCI) [H.5.2]: User",
"class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text: for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text)",
"for p_li in gp_li: if p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC:",
"get_keywords(publisher, soup): keywords_list = None if publisher == \"acm_digital_library\": keywords_list",
"1: ['Categories and Subject Descriptors (according to ACM CCS): I.4.1",
"keywords_str)) return list(keywords_set) except Exception as e: print(e) return None",
"drawings\" # Step 1: Remove annoying substrings # Step 2:",
"keywords_parent_font = keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if",
"keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str))",
"= set() for span_label in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in",
"<gh_stars>1-10 import re regex = re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords",
"# Step 3: Split the string by , or ;",
"wiley_online_library(soup) elif publisher == \"dagstuhl\": keywords_list = dagstuhl(soup) elif publisher",
"as e: print(e) return None def graphics_interface_proceedings(soup): return None def",
"= keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font",
"Interfaces And Presentation (e.g., HCI) [H.5.2]: User Interfaces-Graphical user interfaces",
"Subject Descriptors (according to ACM CCS): I.4.1 [Image Processing and",
"by , or ; or : to_replaces = [\"CCS Concepts\",",
"return None def get_keywords(publisher, soup): keywords_list = None if publisher",
"re regex = re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords = set()",
"not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except",
"interfaces (GUI) # Step 1: Remove annoying substrings # Step",
"string by , or ; or : to_replaces = [\"CCS",
"def cogsci(soup): return None def scitepress(soup): try: keywords_set = set()",
"keywords_list = eurographics_digital_library(soup) elif publisher == \"wiley_online_library\": keywords_list = wiley_online_library(soup)",
"\"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: #",
"keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td = keywords_parent_font.parent",
"= soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set",
"= dagstuhl(soup) elif publisher == \"aaai\": keywords_list = aaai(soup) return",
"= k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except Exception as e:",
"a_tag is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return",
"None def springer_v1(soup): try: keywords = set() keywords_parent_section = soup.find('ul',",
"except Exception as e: print(e) return None def eurographics_digital_library(soup): try:",
"Choose to take ONLY Categories, not the Subject Descriptors >",
"care of yet] Categories and Subject Descriptors (according to ACM",
"r'•(.*)→(.*)' regex_replace = r'\\1;\\2' # set the delimiter to either",
"print(e) return None def springer_v2(soup): try: keywords = set() keywords_parent_div",
"for k in keywords_span: keywords.add(k.text) return list(keywords) except Exception as",
"class_=\"word-break\") # e.g. CASE 1: ['Categories and Subject Descriptors (according",
"Information Interfaces And Presentation (e.g., HCI) [H.5.2]: User Interfaces-Graphical user",
"keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted:",
"set() for keywords_li in keywords_lis: # e.g. Case 1: \"[3.1.1]",
"Computer Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap and framebuffer",
"Step 1: Remove annoying substrings # Step 2: Choose to",
"the delimiter to either , : ; (as is used",
"class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in keywords_span: keywords.add(k.text)",
"Subject Descriptors > Write a REGEX to take substrings between",
"CCS): I.4.1 [Image Processing and Computer Vision]: Enhancement-Filtering I.3.3 [Computer",
"to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if",
"eurographics_digital_library(soup): try: keywords_set = set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs",
": ; (as is used below to split) keywords_str =",
"such as \"• Human‐centered computing → Graph drawings\" regex_find =",
"= p_tablebody.findChildren('tr') for tr in p_trs: label = tr.find(\"td\", class_=\"label-cell\")",
"return None def dagstuhl(soup): try: keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font",
"keywords_list = dagstuhl(soup) elif publisher == \"aaai\": keywords_list = aaai(soup)",
"or ; or : to_replaces = [\"CCS Concepts\", \"Categories and",
"elif publisher == \"dagstuhl\": keywords_list = dagstuhl(soup) elif publisher ==",
"recursive=True) for kw_parent in keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0]))",
"try: keywords = set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li =",
"Concepts\", \"Categories and Subject Descriptors\", \"Categories and subject descriptors\", \"Categories",
"= keywords_str.replace(to_replace, \"\") keywords_extracted = re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted)",
"publisher == \"ieee_explore\": keywords_list = ieee_explore(soup) elif publisher == \"cogsci\":",
"but they have strings such as \"• Human‐centered computing →",
"acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif publisher",
"Exception as e: print(e) return None def springer_v2(soup): try: keywords",
"id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except Exception",
"None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception",
"keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except Exception",
"= ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li in gp_li: if p_li.find('strong').text",
"text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\")",
"framebuffer operations'] # e.g. CASE 2 [TODO: Not taken care",
"keywords_str = keywords.text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace,",
"ACM CCS)\", \"according to ACM CCS\"] keywords_str = keywords.text for",
"= re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception",
"elif publisher == \"wiley_online_library\": keywords_list = wiley_online_library(soup) elif publisher ==",
"else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as e: print(e)",
"== \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\": keywords_list",
"kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except Exception as e: print(e)",
"keywords_li.find(\"a\").text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted",
"keywords_list = ieee_explore(soup) elif publisher == \"cogsci\": keywords_list = cogsci(soup)",
"class_=\"stats-keywords-list-item\") if a_tag is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\",",
"def scienceopen(soup): try: keywords_set = set() for span_label in soup.find_all('span',",
"keywords_list = scienceopen(soup) elif publisher == \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup)",
"keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except",
"try: keywords_set = set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw",
"set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for tr",
"else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception as e: print(e)",
"in [\"IEEE Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH",
"Processing and Computer Vision]: Enhancement-Filtering I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap",
"such as \"• Human‐centered computing → Graph drawings\" # Step",
"and Subject Descriptors (according to ACM CCS): I.4.1 [Image Processing",
"take substrings between []. # Step 3: Split the string",
"elif publisher == \"springer_v2\": keywords_list = springer_v2(soup) elif publisher ==",
"Exception as e: print(e) return None def cogsci(soup): return None",
"a_tag.text.split(\",\")[0]))) else: keywords.add(str(regex.sub(\"\", str(keywords_l.text).split(\",\")[0]))) return list(keywords) except Exception as e:",
"keywords_list = scitepress(soup) elif publisher == \"scienceopen\": keywords_list = scienceopen(soup)",
"def eurographics_digital_library(soup): try: keywords_set = set() p_tablebody = soup.find('table', class_=\"detailtable\").find(\"tbody\")",
"for tr in p_trs: label = tr.find(\"td\", class_=\"label-cell\") if label.text",
"scitepress(soup) elif publisher == \"scienceopen\": keywords_list = scienceopen(soup) elif publisher",
"if publisher == \"acm_digital_library\": keywords_list = acm_digital_library(soup) elif publisher ==",
"Indexing\", \"MeSH Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag =",
"split) keywords_str = re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set)",
"Exception as e: print(e) return None def eurographics_digital_library(soup): try: keywords_set",
": to_replaces = [\"CCS Concepts\", \"Categories and Subject Descriptors\", \"Categories",
"yet] Categories and Subject Descriptors (according to ACM CCS): Information",
"elif publisher == \"aaai\": keywords_list = aaai(soup) return None if",
"# e.g. CASE 2 [TODO: Not taken care of yet]",
"re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as",
"[Computer Graphics]: Picture/Image Generation-Bitmap and framebuffer operations'] # e.g. CASE",
"for keywords_li in keywords_lis: # e.g. Case 1: \"[3.1.1] Human-Centered",
"to ACM CCS\"] keywords_str = keywords.text for to_replace in to_replaces:",
"Write a REGEX to take substrings between []. # Step",
"(according to ACM CCS): Information Interfaces And Presentation (e.g., HCI)",
"= set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\",",
"None: return re.split(',', keywords_font.text) except Exception as e: print(e) return",
"keywords_font is not None: return re.split(',', keywords_font.text) except Exception as",
"for kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except Exception as",
"Split the string by , or ; or : to_replaces",
"keywords = tr.find(\"td\", class_=\"word-break\") # e.g. CASE 1: ['Categories and",
"strings such as \"• Human‐centered computing → Graph drawings\" #",
"eurographics_digital_library(soup) elif publisher == \"wiley_online_library\": keywords_list = wiley_online_library(soup) elif publisher",
"= eurographics_digital_library(soup) elif publisher == \"wiley_online_library\": keywords_list = wiley_online_library(soup) elif",
"[TODO: Not taken care of yet] Categories and Subject Descriptors",
"Exception as e: print(e) return None def dagstuhl(soup): try: keywords_label",
"I.3.3 [Computer Graphics]: Picture/Image Generation-Bitmap and framebuffer operations'] # e.g.",
"Subject Descriptors\", \"Categories and subject descriptors\", \"Categories and Subject Descriptors",
"= set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\")",
"try: keywords = set() keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs",
"keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in keywords_span: keywords.add(k.text) return list(keywords) except",
"in keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except",
"= keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is not None: keywords.add(str(regex.sub(\"\", a_tag.text.split(\",\")[0])))",
"def dagstuhl(soup): try: keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent",
"keywords_list = aaai(soup) return None if len(keywords_list) == 0 else",
"= keywords.text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\")",
"except Exception as e: print(e) return None def graphics_interface_proceedings(soup): return",
"and ']' but they have strings such as \"• Human‐centered",
"\"Categories and Subject Descriptors (according to ACM CCS)\", \"according to",
"ieee_explore(soup) elif publisher == \"cogsci\": keywords_list = cogsci(soup) elif publisher",
"== \"wiley_online_library\": keywords_list = wiley_online_library(soup) elif publisher == \"dagstuhl\": keywords_list",
"ieee_explore(soup): try: keywords = set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\")",
"cogsci(soup) elif publisher == \"springer_v1\": keywords_list = springer_v1(soup) elif publisher",
"keywords_li = keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in keywords_li: kw =",
"= re.findall(r'\\[(.*?)\\]', keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS Concepts",
"and framebuffer operations'] # e.g. CASE 2 [TODO: Not taken",
"e: print(e) return None def cogsci(soup): return None def scitepress(soup):",
"def get_keywords(publisher, soup): keywords_list = None if publisher == \"acm_digital_library\":",
"Exception as e: pass return None def aaai(soup): return None",
"label = tr.find(\"td\", class_=\"label-cell\") if label.text == \"dc.subject\": keywords =",
"= re.compile(r'[\\n\\r\\t]') def acm_digital_library(soup): try: keywords = set() keywords_parent_ol =",
"strings such as \"• Human‐centered computing → Graph drawings\" regex_find",
"if keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS Concepts don't have '['",
"keywords_set.update(keywords_extracted) else: # CCS Concepts don't have '[' and ']'",
"kw.split(\",\")[0])) return list(keywords) except Exception as e: print(e) return None",
"springer_v1(soup): try: keywords = set() keywords_parent_section = soup.find('ul', class_=\"c-article-subject-list\") keywords_li",
"return None def scienceopen(soup): try: keywords_set = set() for span_label",
"if keywords_font is not None: return re.split(',', keywords_font.text) except Exception",
"and so on # e.g. Case 2: CCS Concepts don't",
"1: Remove annoying substrings # Step 2: Choose to take",
"keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\")",
"ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for p_li in gp_li: if p_li.find('strong').text in",
"keywords_set = set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in",
"publisher == \"springer_v1\": keywords_list = springer_v1(soup) elif publisher == \"springer_v2\":",
"scitepress(soup): try: keywords_set = set() keywords_span = soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for",
"keywords_span: keywords.add(k.text) return list(keywords) except Exception as e: print(e) return",
"And Presentation (e.g., HCI) [H.5.2]: User Interfaces-Graphical user interfaces (GUI)",
"in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is",
"operations'] # e.g. CASE 2 [TODO: Not taken care of",
"(e.g., HCI) [H.5.2]: User Interfaces-Graphical user interfaces (GUI) # Step",
"or : to_replaces = [\"CCS Concepts\", \"Categories and Subject Descriptors\",",
"'[' and ']' but they have strings such as \"•",
"list(keywords) except Exception as e: print(e) return None def graphics_interface_proceedings(soup):",
"soup.find('span', id=\"ContentPlaceHolder1_LinkPaperPage_LinkPaperContent_LabelPublicationDetailKeywords\") for kw in keywords_span.text.split(\",\"): keywords_set.add(kw) return list(keywords_set) except",
"to_replaces = [\"CCS Concepts\", \"Categories and Subject Descriptors\", \"Categories and",
"e: print(e) return None def graphics_interface_proceedings(soup): return None def ieee_explore(soup):",
"ACM CCS\"] keywords_str = keywords.text for to_replace in to_replaces: keywords_str",
"Exception as e: print(e) return None def wiley_online_library(soup): try: keywords_parent_section",
"p_tablebody.findChildren('tr') for tr in p_trs: label = tr.find(\"td\", class_=\"label-cell\") if",
"as e: print(e) return None def springer_v2(soup): try: keywords =",
"keywords_str) if keywords_extracted: keywords_set.update(keywords_extracted) else: # CCS Concepts don't have",
"\"acm_digital_library\": keywords_list = acm_digital_library(soup) elif publisher == \"graphics_interface_proceedings\": keywords_list =",
"publisher == \"cogsci\": keywords_list = cogsci(soup) elif publisher == \"springer_v1\":",
"dagstuhl(soup): try: keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td",
"kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except Exception as",
"keywords_set.update(re.split(',|:|;', keywords_str)) return list(keywords_set) except Exception as e: print(e) return",
"keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except Exception as e: print(e) return",
"= soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False) for",
"so on # e.g. Case 2: CCS Concepts don't have",
"and Subject Descriptors (according to ACM CCS)\", \"according to ACM",
"try: keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td =",
"tr in p_trs: label = tr.find(\"td\", class_=\"label-cell\") if label.text ==",
"Descriptors\", \"Categories and subject descriptors\", \"Categories and Subject Descriptors (according",
"keywords.add(k.text) return list(keywords) except Exception as e: print(e) return None",
"= keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set = set() for keywords_li",
"print(e) return None def graphics_interface_proceedings(soup): return None def ieee_explore(soup): try:",
"in gp_li: if p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC: Controlled Indexing\",",
"\"Keywords\" in span_label.text: for keyword_a in span_label.find_next_siblings('a'): keywords_set.add(keyword_a.text) return list(keywords_set)",
"= graphics_interface_proceedings(soup) elif publisher == \"ieee_explore\": keywords_list = ieee_explore(soup) elif",
"ACM CCS): I.4.1 [Image Processing and Computer Vision]: Enhancement-Filtering I.3.3",
"None def dagstuhl(soup): try: keywords_label = soup.find('b', text=\"Keywords:\") keywords_parent_font =",
"publisher == \"wiley_online_library\": keywords_list = wiley_online_library(soup) elif publisher == \"dagstuhl\":",
"Categories, not the Subject Descriptors > Write a REGEX to",
"return re.split(',', keywords_font.text) except Exception as e: print(e) return None",
"ACM CCS)\", \"according to ACM CCS\"] keywords_str = keywords_li.find(\"a\").text for",
"recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is not None:",
"= keywords_li.find(\"a\").text for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\")",
"p_trs: label = tr.find(\"td\", class_=\"label-cell\") if label.text == \"dc.subject\": keywords",
"for to_replace in to_replaces: keywords_str = keywords_str.replace(to_replace, \"\") keywords_extracted =",
"except Exception as e: print(e) return None def cogsci(soup): return",
"keywords_parent_section.findChildren(\"li\", class_=\"c-article-subject-list__subject\") for k in keywords_li: kw = k.find(\"span\").text keywords.add(str(regex.sub(\"\",",
"Human‐centered computing → Graph drawings\" # Step 1: Remove annoying",
"pass return None def aaai(soup): return None def get_keywords(publisher, soup):",
"None def scitepress(soup): try: keywords_set = set() keywords_span = soup.find('span',",
"keywords = set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\",",
"p_li in gp_li: if p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC: Controlled",
"class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for tr in p_trs: label =",
"elif publisher == \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif publisher ==",
"print(e) return None def dagstuhl(soup): try: keywords_label = soup.find('b', text=\"Keywords:\")",
"keywords_parent_ol = soup.find('ol', class_=\"rlist organizational-chart\") keywords_divs = keywords_parent_ol.findChildren('div', recursive=True) for",
"= kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except Exception as e:",
"= soup.find('table', class_=\"detailtable\").find(\"tbody\") p_trs = p_tablebody.findChildren('tr') for tr in p_trs:",
"soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul') keywords_lis = keywords_ul.findChildren(\"li\") keywords_set =",
"\"wiley_online_library\": keywords_list = wiley_online_library(soup) elif publisher == \"dagstuhl\": keywords_list =",
"Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]: for",
"def wiley_online_library(soup): try: keywords_parent_section = soup.find('section', class_=\"keywords\") keywords_ul = keywords_parent_section.find('ul')",
"REGEX to take substrings between []. # Step 3: Split",
"Human-Centered Computing\" and so on # e.g. Case 2: CCS",
"set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\",",
"HCI) [H.5.2]: User Interfaces-Graphical user interfaces (GUI) # Step 1:",
"to split) keywords_str = re.sub(regex_find, regex_replace, keywords_str) keywords_set.update(re.split(',|:|;', keywords_str)) return",
"→ Graph drawings\" regex_find = r'•(.*)→(.*)' regex_replace = r'\\1;\\2' #",
"None def graphics_interface_proceedings(soup): return None def ieee_explore(soup): try: keywords =",
"except Exception as e: print(e) return None def springer_v2(soup): try:",
"# Step 2: Choose to take ONLY Categories, not the",
"k.find(\"span\").text keywords.add(str(regex.sub(\"\", kw)).strip()) return list(keywords) except Exception as e: print(e)",
"== \"ieee_explore\": keywords_list = ieee_explore(soup) elif publisher == \"cogsci\": keywords_list",
"keywords_lis = keywords_ul.findChildren(\"li\") keywords_set = set() for keywords_li in keywords_lis:",
"keywords_list = None if publisher == \"acm_digital_library\": keywords_list = acm_digital_library(soup)",
"= soup.find('b', text=\"Keywords:\") keywords_parent_font = keywords_label.parent keywords_parent_td = keywords_parent_font.parent keywords_font",
"have strings such as \"• Human‐centered computing → Graph drawings\"",
"soup.find('div', class_=\"KeywordGroup\") keywords_span = keywords_parent_div.findChildren(\"span\", class_=\"Keyword\") for k in keywords_span:",
"as \"• Human‐centered computing → Graph drawings\" regex_find = r'•(.*)→(.*)'",
"[\"IEEE Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC: Non-Controlled Indexing\", \"MeSH Terms\"]:",
"Terms\"]: for keywords_l in p_li.find('ul').findChildren(\"li\", recursive=False): a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\")",
"is not None: return re.split(',', keywords_font.text) except Exception as e:",
"Subject Descriptors (according to ACM CCS)\", \"according to ACM CCS\"]",
"r'\\1;\\2' # set the delimiter to either , : ;",
"= r'•(.*)→(.*)' regex_replace = r'\\1;\\2' # set the delimiter to",
"span_label in soup.find_all('span', class_=\"so-metadata-label\"): if \"Keywords\" in span_label.text: for keyword_a",
"Case 1: \"[3.1.1] Human-Centered Computing\" and so on # e.g.",
"cogsci(soup): return None def scitepress(soup): try: keywords_set = set() keywords_span",
"Exception as e: print(e) return None def scienceopen(soup): try: keywords_set",
"elif publisher == \"springer_v1\": keywords_list = springer_v1(soup) elif publisher ==",
"None if publisher == \"acm_digital_library\": keywords_list = acm_digital_library(soup) elif publisher",
"drawings\" regex_find = r'•(.*)→(.*)' regex_replace = r'\\1;\\2' # set the",
"keywords_parent_font.parent keywords_font = keywords_parent_td.find_next('td').find_next('td').find(\"font\") if keywords_font is not None: return",
"list(keywords_set) except Exception as e: print(e) return None def cogsci(soup):",
"take ONLY Categories, not the Subject Descriptors > Write a",
"== \"eurographics_digital_library\": keywords_list = eurographics_digital_library(soup) elif publisher == \"wiley_online_library\": keywords_list",
"[]. # Step 3: Split the string by , or",
"elif publisher == \"graphics_interface_proceedings\": keywords_list = graphics_interface_proceedings(soup) elif publisher ==",
"a_tag = keywords_l.find(\"a\", class_=\"stats-keywords-list-item\") if a_tag is not None: keywords.add(str(regex.sub(\"\",",
"springer_v2(soup): try: keywords = set() keywords_parent_div = soup.find('div', class_=\"KeywordGroup\") keywords_span",
"ggp_ul = soup.find('ul', class_=\"doc-keywords-list stats-keywords-list\") gp_li = ggp_ul.findChildren(\"li\", class_=\"doc-keywords-list-item\", recursive=False)",
"p_trs = p_tablebody.findChildren('tr') for tr in p_trs: label = tr.find(\"td\",",
"Exception as e: print(e) return None def springer_v1(soup): try: keywords",
"def ieee_explore(soup): try: keywords = set() ggp_ul = soup.find('ul', class_=\"doc-keywords-list",
"return None def springer_v2(soup): try: keywords = set() keywords_parent_div =",
"return list(keywords_set) except Exception as e: pass return None def",
"gp_li: if p_li.find('strong').text in [\"IEEE Keywords\", \"INSPEC: Controlled Indexing\", \"INSPEC:",
"(according to ACM CCS): I.4.1 [Image Processing and Computer Vision]:",
"(GUI) # Step 1: Remove annoying substrings # Step 2:",
"in keywords_divs: kw = kw_parent.text keywords.add(regex.sub(\"\", kw.split(\",\")[0])) return list(keywords) except",
"# e.g. Case 2: CCS Concepts don't have '[' and"
] |
[
"from django.urls import reverse from django.utils import timezone from django.utils.safestring",
"return reverse('publication:go', args=[self.short_url]) def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self,",
"like a relative path to a directory. If storage is",
"prefix should correspond to a real directory. \"\"\" return \"publications/{}/\".format(self.short_url)",
"[(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url =",
"= \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for t in",
"+= ' <a href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors, year=self.datetime.year, version=self.version,",
"= models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications')",
"self.get_full_url(request)) # Name of Database add('DB', 'contact.engineering') # Notes add('N1',",
"End of record, must be empty and last tag add('ER',",
"@misc{{ {shortname}, title = {{{title}}}, author = {{{author}}}, year =",
"self.surface.tags.all()) s = \"\"\" @misc{{ {shortname}, title = {{{title}}}, author",
"f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name",
"3 dashes version = models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license =",
"add(key, value): nonlocal s s += f\"{key} - {value}\\n\" #",
"record, must be empty and last tag add('ER', '') return",
"shortname=shortname, ) return s.strip() def _get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace('",
"dashes version = models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12,",
"keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for t",
"citation format flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name'])",
"ones and tags for kw in DEFAULT_KEYWORDS: add('KW', kw) for",
"16 digits including 3 dashes version = models.PositiveIntegerField(default=1) datetime =",
"', ' and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, )",
"getattr(self, method_name)(request) def _get_citation_as_html(self, request): s = '{authors}. ({year}). contact.engineering.",
"s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s) def",
"null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='')",
"def __init__(self, flavor): self._flavor = flavor def __str__(self): return f\"Unknown",
"add('DB', 'contact.engineering') # Notes add('N1', self.surface.description) # add keywords, defaults",
"https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def",
"in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return getattr(self, method_name)(request)",
"models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id =",
"from django.utils import timezone from django.utils.safestring import mark_safe from django.conf",
"def __str__(self): return f\"Unknown citation format flavor '{self._flavor}'.\" class Publication(models.Model):",
"If storage is on filesystem, the prefix should correspond to",
"for kw in DEFAULT_KEYWORDS: add('KW', kw) for t in self.surface.tags.all():",
"= {{{title}}}, version = {{{version}}}, author = {{{author}}}, year =",
"# Notes add('N1', self.surface.description) # add keywords, defaults ones and",
"models.CharField(max_length=10, unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface =",
"s = s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return",
"get_citation(self, flavor, request): if flavor not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor)",
"(Version {version})</em>.' s += ' <a href=\"{publication_url}\">{publication_url}</a>' s = s.format(",
"format flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for",
"request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request): if flavor not in CITATION_FORMAT_FLAVORS:",
"t in self.surface.tags.all(): add('KW', t.name) # End of record, must",
"= {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ', ' and '), year=self.datetime.year,",
"t in self.surface.tags.all()) s = \"\"\" @misc{{ {shortname}, title =",
"{{{month}}}, date = {{{date}}}, note = {{{note}}}, keywords = {{{keywords}}},",
"LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']]",
"real directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return relative",
"url = {{{url}}}, urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(',",
"def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request): if",
"method_name = '_get_citation_as_'+flavor return getattr(self, method_name)(request) def _get_citation_as_html(self, request): s",
"{{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ', ' and '), year=self.datetime.year, note=self.surface.description,",
"DEFAULT_KEYWORDS: add('KW', kw) for t in self.surface.tags.all(): add('KW', t.name) #",
"if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all()) s",
"'_get_citation_as_'+flavor return getattr(self, method_name)(request) def _get_citation_as_html(self, request): s = '{authors}.",
"flavor): self._flavor = flavor def __str__(self): return f\"Unknown citation format",
"{{{version}}}, author = {{{author}}}, year = {{{year}}}, month = {{{month}}},",
"choices=LICENSE_CHOICES, blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='')",
"# Publication Year add('PY', format(self.datetime, '%Y/%m/%d/')) # URL add('UR', self.get_full_url(request))",
"\"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return s.strip() @property def storage_prefix(self): \"\"\"Return",
"def storage_prefix(self): \"\"\"Return prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like",
"of Database add('DB', 'contact.engineering') # Notes add('N1', self.surface.description) # add",
"<a href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request),",
"https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative path to a directory. If",
"'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class UnknownCitationFormat(Exception): def __init__(self, flavor):",
"= 512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS =",
"publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return s.strip() def _get_citation_as_biblatex(self, request): shortname",
"= \"\"\" @misc{{ {shortname}, title = {{{title}}}, author = {{{author}}},",
"Year add('PY', format(self.datetime, '%Y/%m/%d/')) # URL add('UR', self.get_full_url(request)) # Name",
"{{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', ' and '), year=self.datetime.year,",
"__init__(self, flavor): self._flavor = flavor def __str__(self): return f\"Unknown citation",
"tag add('ER', '') return s.strip() def _get_citation_as_bibtex(self, request): title =",
"= {{{note}}}, keywords = {{{keywords}}}, howpublished = {{{publication_url}}}, }} \"\"\".format(title=title,",
"method_name)(request) def _get_citation_as_html(self, request): s = '{authors}. ({year}). contact.engineering. <em>{surface.name}",
"self.surface.tags.all()) s = \"\"\" @online{{ {shortname}, title = {{{title}}}, version",
"= ['surface', 'topography'] class UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor =",
"= models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id",
"models.CharField(max_length=19, default='') # 16 digits including 3 dashes version =",
"= '_get_citation_as_'+flavor return getattr(self, method_name)(request) def _get_citation_as_html(self, request): s =",
"relative path to a directory. If storage is on filesystem,",
"\"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return relative path of container in",
"Notes add('N1', self.surface.description) # add keywords, defaults ones and tags",
"keywords = {{{keywords}}}, howpublished = {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ',",
"f\"{self.surface.name} (Version {self.version})\") # Authors for author in self.authors.split(','): add('AU',",
"for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative path to a",
"return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return relative path of container",
"\"\"\"Return prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative",
"keywords, defaults ones and tags for kw in DEFAULT_KEYWORDS: add('KW',",
"see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip",
"s = '{authors}. ({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.' s +=",
"import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex',",
"author=self.authors.replace(', ', ' and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description,",
"s.strip() def _get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords =",
"_get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) # or",
"['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True, null=True) surface =",
"related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='') #",
"not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return getattr(self,",
"{{{note}}}, keywords = {{{keywords}}}, url = {{{url}}}, urldate = {{{urldate}}}",
"# Authors for author in self.authors.split(','): add('AU', author.strip()) # Publication",
"authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s) def _get_citation_as_ris(self,",
"{{{date}}}, note = {{{note}}}, keywords = {{{keywords}}}, url = {{{url}}},",
"return s.strip() @property def storage_prefix(self): \"\"\"Return prefix used for storage.",
"MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS",
"s.strip() @property def storage_prefix(self): \"\"\"Return prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to",
"= models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container =",
"'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\",",
"+= \",\"+\",\".join(t.name for t in self.surface.tags.all()) s = \"\"\" @misc{{",
"howpublished = {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ', ' and '),",
"storage is on filesystem, the prefix should correspond to a",
"# End of record, must be empty and last tag",
"version=self.version, author=self.authors.replace(', ', ' and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"),",
"in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True, null=True) surface",
"and last tag add('ER', '') return s.strip() def _get_citation_as_bibtex(self, request):",
"version = models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES,",
"or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\"",
"original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT)",
"format(self.datetime, '%Y/%m/%d/')) # URL add('UR', self.get_full_url(request)) # Name of Database",
"= {{{title}}}, author = {{{author}}}, year = {{{year}}}, note =",
"blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='') def",
"surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True,",
"in self.surface.tags.all(): add('KW', t.name) # End of record, must be",
"models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher",
"{version})</em>.' s += ' <a href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors,",
"datetime = models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors",
"get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request): if flavor",
"UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor = flavor def __str__(self): return",
"Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0', 'ccby-4.0',",
"k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True, null=True)",
"'{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in",
"= f\"{self.surface.name} (Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords =",
"= {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', ' and '),",
"should correspond to a real directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property",
"of record, must be empty and last tag add('ER', '')",
"'ELEC') # Title add('TI', f\"{self.surface.name} (Version {self.version})\") # Authors for",
"title = {{{title}}}, version = {{{version}}}, author = {{{author}}}, year",
"get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def",
"models from django.urls import reverse from django.utils import timezone from",
"# Electronic citation / Website add('TY', 'ELEC') # Title add('TI',",
"request): s = '{authors}. ({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.' s",
"(Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if",
"or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def add(key, value):",
"https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def add(key, value): nonlocal",
"# https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def add(key, value): nonlocal s",
"{{{url}}}, urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', '",
"Title add('TI', f\"{self.surface.name} (Version {self.version})\") # Authors for author in",
"@online{{ {shortname}, title = {{{title}}}, version = {{{version}}}, author =",
"/ Website add('TY', 'ELEC') # Title add('TI', f\"{self.surface.name} (Version {self.version})\")",
"month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, )",
"CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return getattr(self, method_name)(request) def",
"add('ER', '') return s.strip() def _get_citation_as_bibtex(self, request): title = f\"{self.surface.name}",
"def container_storage_path(self): \"\"\"Return relative path of container in storage.\"\"\" return",
"'') return s.strip() def _get_citation_as_bibtex(self, request): title = f\"{self.surface.name} (Version",
"\"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return s.strip()",
"and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return s.strip()",
"_get_citation_as_html(self, request): s = '{authors}. ({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.'",
"year = {{{year}}}, note = {{{note}}}, keywords = {{{keywords}}}, howpublished",
"url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return s.strip() @property def",
"for author in self.authors.split(','): add('AU', author.strip()) # Publication Year add('PY',",
"# Name of Database add('DB', 'contact.engineering') # Notes add('N1', self.surface.description)",
"= {{{version}}}, author = {{{author}}}, year = {{{year}}}, month =",
"date = {{{date}}}, note = {{{note}}}, keywords = {{{keywords}}}, url",
"= models.FileField(max_length=50, default='') def get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def get_full_url(self,",
"shortname=shortname, ) return s.strip() @property def storage_prefix(self): \"\"\"Return prefix used",
"\"\" def add(key, value): nonlocal s s += f\"{key} -",
"- {value}\\n\" # Electronic citation / Website add('TY', 'ELEC') #",
"<em>{surface.name} (Version {version})</em>.' s += ' <a href=\"{publication_url}\">{publication_url}</a>' s =",
"add('KW', t.name) # End of record, must be empty and",
"import reverse from django.utils import timezone from django.utils.safestring import mark_safe",
"href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), )",
"{{{title}}}, version = {{{version}}}, author = {{{author}}}, year = {{{year}}},",
"add('KW', kw) for t in self.surface.tags.all(): add('KW', t.name) # End",
"to a real directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self):",
"if flavor not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor",
"_get_citation_as_bibtex(self, request): title = f\"{self.surface.name} (Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace('",
"add('N1', self.surface.description) # add keywords, defaults ones and tags for",
"models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='') # 16 digits including",
"mark_safe(s) def _get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format)",
"{{{title}}}, author = {{{author}}}, year = {{{year}}}, note = {{{note}}},",
"reverse('publication:go', args=[self.short_url]) def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor,",
"'{authors}. ({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.' s += ' <a",
"+= f\"{key} - {value}\\n\" # Electronic citation / Website add('TY',",
"and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"),",
"def get_citation(self, flavor, request): if flavor not in CITATION_FORMAT_FLAVORS: raise",
"directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return relative path",
"CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography']",
"{{{author}}}, year = {{{year}}}, note = {{{note}}}, keywords = {{{keywords}}},",
"{self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0:",
"the prefix should correspond to a real directory. \"\"\" return",
"def _get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS)",
"'contact.engineering') # Notes add('N1', self.surface.description) # add keywords, defaults ones",
"self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all()) s =",
"reverse from django.utils import timezone from django.utils.safestring import mark_safe from",
"note = {{{note}}}, keywords = {{{keywords}}}, url = {{{url}}}, urldate",
"license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container",
"= {{{keywords}}}, url = {{{url}}}, urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name,",
"= \"\" def add(key, value): nonlocal s s += f\"{key}",
"storage_prefix(self): \"\"\"Return prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a",
"{self.version})\") # Authors for author in self.authors.split(','): add('AU', author.strip()) #",
"flavor def __str__(self): return f\"Unknown citation format flavor '{self._flavor}'.\" class",
"on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19,",
"for t in self.surface.tags.all()) s = \"\"\" @misc{{ {shortname}, title",
"'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class UnknownCitationFormat(Exception): def __init__(self,",
"version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s) def _get_citation_as_ris(self, request): #",
"import mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS",
"note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return s.strip() def _get_citation_as_biblatex(self, request):",
"' and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(),",
"__str__(self): return f\"Unknown citation format flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES",
"request): if flavor not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name =",
"flavor, request): if flavor not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name",
"settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex']",
"add('AU', author.strip()) # Publication Year add('PY', format(self.datetime, '%Y/%m/%d/')) # URL",
"= models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors =",
"note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return s.strip() @property",
"title = {{{title}}}, author = {{{author}}}, year = {{{year}}}, note",
"import timezone from django.utils.safestring import mark_safe from django.conf import settings",
"to a directory. If storage is on filesystem, the prefix",
"author = {{{author}}}, year = {{{year}}}, note = {{{note}}}, keywords",
"keywords = {{{keywords}}}, url = {{{url}}}, urldate = {{{urldate}}} }}",
"empty and last tag add('ER', '') return s.strip() def _get_citation_as_bibtex(self,",
"['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class UnknownCitationFormat(Exception):",
"self._flavor = flavor def __str__(self): return f\"Unknown citation format flavor",
"def _get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) #",
"used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative path to",
"author in self.authors.split(','): add('AU', author.strip()) # Publication Year add('PY', format(self.datetime,",
"'), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords,",
"on filesystem, the prefix should correspond to a real directory.",
"Electronic citation / Website add('TY', 'ELEC') # Title add('TI', f\"{self.surface.name}",
"_get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if",
"models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD)",
"', ' and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request),",
"class UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor = flavor def __str__(self):",
"args=[self.short_url]) def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request):",
"a real directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return",
"# URL add('UR', self.get_full_url(request)) # Name of Database add('DB', 'contact.engineering')",
"({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.' s += ' <a href=\"{publication_url}\">{publication_url}</a>'",
"}} \"\"\".format(title=title, author=self.authors.replace(', ', ' and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request),",
"for t in self.surface.tags.all()) s = \"\"\" @online{{ {shortname}, title",
"= f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords +=",
"title = f\"{self.surface.name} (Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords",
"including 3 dashes version = models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license",
"tags for kw in DEFAULT_KEYWORDS: add('KW', kw) for t in",
"\",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all())",
"s = \"\" def add(key, value): nonlocal s s +=",
"= \"\"\" @online{{ {shortname}, title = {{{title}}}, version = {{{version}}},",
"= models.CharField(max_length=10, unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface",
"= {{{month}}}, date = {{{date}}}, note = {{{note}}}, keywords =",
"f\"Unknown citation format flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES = [(k,",
"version = {{{version}}}, author = {{{author}}}, year = {{{year}}}, month",
"import models from django.urls import reverse from django.utils import timezone",
"= {{{keywords}}}, howpublished = {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ', '",
"urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return s.strip() @property def storage_prefix(self):",
"django.utils.safestring import mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD = 512",
"in DEFAULT_KEYWORDS: add('KW', kw) for t in self.surface.tags.all(): add('KW', t.name)",
"+= \",\"+\",\".join(t.name for t in self.surface.tags.all()) s = \"\"\" @online{{",
"s += f\"{key} - {value}\\n\" # Electronic citation / Website",
"unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\",",
"author.strip()) # Publication Year add('PY', format(self.datetime, '%Y/%m/%d/')) # URL add('UR',",
"publication_url=self.get_full_url(request), ) return mark_safe(s) def _get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html",
"URL add('UR', self.get_full_url(request)) # Name of Database add('DB', 'contact.engineering') #",
"kw in DEFAULT_KEYWORDS: add('KW', kw) for t in self.surface.tags.all(): add('KW',",
"timezone from django.utils.safestring import mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD",
"flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k",
"= s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s)",
"t in self.surface.tags.all()) s = \"\"\" @online{{ {shortname}, title =",
"@property def container_storage_path(self): \"\"\"Return relative path of container in storage.\"\"\"",
"request): return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request): if flavor not",
"in self.surface.tags.all()) s = \"\"\" @misc{{ {shortname}, title = {{{title}}},",
"'%Y/%m/%d/')) # URL add('UR', self.get_full_url(request)) # Name of Database add('DB',",
"\"\"\" return \"publications/{}/\".format(self.short_url) @property def container_storage_path(self): \"\"\"Return relative path of",
"models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50,",
"# Title add('TI', f\"{self.surface.name} (Version {self.version})\") # Authors for author",
"storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative path to a directory.",
"null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL,",
"{shortname}, title = {{{title}}}, version = {{{version}}}, author = {{{author}}},",
"# or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def add(key,",
"https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s = \"\" def add(key, value): nonlocal s s",
"add keywords, defaults ones and tags for kw in DEFAULT_KEYWORDS:",
"filesystem, the prefix should correspond to a real directory. \"\"\"",
"\"\"\" @online{{ {shortname}, title = {{{title}}}, version = {{{version}}}, author",
"keywords=keywords, shortname=shortname, ) return s.strip() @property def storage_prefix(self): \"\"\"Return prefix",
"path to a directory. If storage is on filesystem, the",
") return s.strip() @property def storage_prefix(self): \"\"\"Return prefix used for",
"= ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class",
"directory. If storage is on filesystem, the prefix should correspond",
"must be empty and last tag add('ER', '') return s.strip()",
"}} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', ' and '), year=self.datetime.year, month=self.datetime.month,",
"for t in self.surface.tags.all(): add('KW', t.name) # End of record,",
"for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True,",
"# or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s =",
"Looks like a relative path to a directory. If storage",
"return s.strip() def _get_citation_as_bibtex(self, request): title = f\"{self.surface.name} (Version {self.version})\"",
"value): nonlocal s s += f\"{key} - {value}\\n\" # Electronic",
"s s += f\"{key} - {value}\\n\" # Electronic citation /",
"# see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp #",
"note = {{{note}}}, keywords = {{{keywords}}}, howpublished = {{{publication_url}}}, }}",
"{value}\\n\" # Electronic citation / Website add('TY', 'ELEC') # Title",
"{shortname}, title = {{{title}}}, author = {{{author}}}, year = {{{year}}},",
"from django.conf import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html',",
"s = \"\"\" @online{{ {shortname}, title = {{{title}}}, version =",
"year=self.datetime.year, month=self.datetime.month, date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname,",
"= models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='') # 16 digits",
"= models.CharField(max_length=19, default='') # 16 digits including 3 dashes version",
"s.strip() def _get_citation_as_bibtex(self, request): title = f\"{self.surface.name} (Version {self.version})\" shortname",
"\"\"\" @misc{{ {shortname}, title = {{{title}}}, author = {{{author}}}, year",
"add('PY', format(self.datetime, '%Y/%m/%d/')) # URL add('UR', self.get_full_url(request)) # Name of",
"mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS =",
"add('TI', f\"{self.surface.name} (Version {self.version})\") # Authors for author in self.authors.split(','):",
"date=format(self.datetime, \"%Y-%m-%d\"), note=self.surface.description, url=self.get_full_url(request), urldate=format(timezone.now(), \"%Y-%m-%d\"), keywords=keywords, shortname=shortname, ) return",
"is on filesystem, the prefix should correspond to a real",
"return s.strip() def _get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords",
"from django.db import models from django.urls import reverse from django.utils",
"{{{year}}}, month = {{{month}}}, date = {{{date}}}, note = {{{note}}},",
"self.surface.description) # add keywords, defaults ones and tags for kw",
"on_delete=models.PROTECT, related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher =",
"nonlocal s s += f\"{key} - {value}\\n\" # Electronic citation",
"# add keywords, defaults ones and tags for kw in",
"class Publication(models.Model): LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0',",
"default='') def get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def get_full_url(self, request): return",
"return mark_safe(s) def _get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or",
"UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return getattr(self, method_name)(request) def _get_citation_as_html(self, request):",
"\"\"\".format(title=title, author=self.authors.replace(', ', ' and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords,",
"= flavor def __str__(self): return f\"Unknown citation format flavor '{self._flavor}'.\"",
"related_name='publication') original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL, null=True, related_name='derived_publications') publisher = models.ForeignKey(\"users.User\",",
"= {{{author}}}, year = {{{year}}}, month = {{{month}}}, date =",
"author=self.authors.replace(', ', ' and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname,",
"publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='') # 16",
"keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all()) s = \"\"\"",
"kw) for t in self.surface.tags.all(): add('KW', t.name) # End of",
"request): title = f\"{self.surface.name} (Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_')",
"'topography'] class UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor = flavor def",
"on_delete=models.PROTECT) publisher_orcid_id = models.CharField(max_length=19, default='') # 16 digits including 3",
"{{{year}}}, note = {{{note}}}, keywords = {{{keywords}}}, howpublished = {{{publication_url}}},",
"= {{{year}}}, note = {{{note}}}, keywords = {{{keywords}}}, howpublished =",
"settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url = models.CharField(max_length=10,",
"def _get_citation_as_bibtex(self, request): title = f\"{self.surface.name} (Version {self.version})\" shortname =",
"def _get_citation_as_html(self, request): s = '{authors}. ({year}). contact.engineering. <em>{surface.name} (Version",
"last tag add('ER', '') return s.strip() def _get_citation_as_bibtex(self, request): title",
"year=self.datetime.year, version=self.version, surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s) def _get_citation_as_ris(self, request):",
"http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp # https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip s",
"Database add('DB', 'contact.engineering') # Notes add('N1', self.surface.description) # add keywords,",
"request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html # or https://en.wikipedia.org/wiki/RIS_(file_format) # or https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp",
"f\"{self.surface.name} (Version {self.version})\" shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS)",
"= {{{date}}}, note = {{{note}}}, keywords = {{{keywords}}}, url =",
"django.utils import timezone from django.utils.safestring import mark_safe from django.conf import",
") return mark_safe(s) def _get_citation_as_ris(self, request): # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html #",
"prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks like a relative path",
"year = {{{year}}}, month = {{{month}}}, date = {{{date}}}, note",
"container_storage_path(self): \"\"\"Return relative path of container in storage.\"\"\" return f\"{self.storage_prefix}container.zip\"",
"models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='') def get_absolute_url(self): return reverse('publication:go', args=[self.short_url])",
"'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface', 'topography'] class UnknownCitationFormat(Exception): def",
"{{{note}}}, keywords = {{{keywords}}}, howpublished = {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(',",
"django.conf import settings MAX_LEN_AUTHORS_FIELD = 512 CITATION_FORMAT_FLAVORS = ['html', 'ris',",
"= models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False,",
"default='') # 16 digits including 3 dashes version = models.PositiveIntegerField(default=1)",
"{{{author}}}, year = {{{year}}}, month = {{{month}}}, date = {{{date}}},",
"request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0:",
"','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords += \",\"+\",\".join(t.name for",
"= '{authors}. ({year}). contact.engineering. <em>{surface.name} (Version {version})</em>.' s += '",
"keywords=keywords, shortname=shortname, ) return s.strip() def _get_citation_as_biblatex(self, request): shortname =",
"defaults ones and tags for kw in DEFAULT_KEYWORDS: add('KW', kw)",
"add('UR', self.get_full_url(request)) # Name of Database add('DB', 'contact.engineering') # Notes",
"Publication Year add('PY', format(self.datetime, '%Y/%m/%d/')) # URL add('UR', self.get_full_url(request)) #",
"512 CITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex'] DEFAULT_KEYWORDS = ['surface',",
"['surface', 'topography'] class UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor = flavor",
"container = models.FileField(max_length=50, default='') def get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def",
"(Version {self.version})\") # Authors for author in self.authors.split(','): add('AU', author.strip())",
") return s.strip() def _get_citation_as_biblatex(self, request): shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_')",
"s += ' <a href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors, year=self.datetime.year,",
"surface=self.surface, publication_url=self.get_full_url(request), ) return mark_safe(s) def _get_citation_as_ris(self, request): # see",
"from django.utils.safestring import mark_safe from django.conf import settings MAX_LEN_AUTHORS_FIELD =",
"@property def storage_prefix(self): \"\"\"Return prefix used for storage. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to Looks",
"= [(k, settings.CC_LICENSE_INFOS[k]['option_name']) for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']] short_url",
"year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return s.strip() def _get_citation_as_biblatex(self,",
"citation / Website add('TY', 'ELEC') # Title add('TI', f\"{self.surface.name} (Version",
"def add(key, value): nonlocal s s += f\"{key} - {value}\\n\"",
"s = \"\"\" @misc{{ {shortname}, title = {{{title}}}, author =",
"# 16 digits including 3 dashes version = models.PositiveIntegerField(default=1) datetime",
"t.name) # End of record, must be empty and last",
"a directory. If storage is on filesystem, the prefix should",
"month = {{{month}}}, date = {{{date}}}, note = {{{note}}}, keywords",
"raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return getattr(self, method_name)(request) def _get_citation_as_html(self,",
"DEFAULT_KEYWORDS = ['surface', 'topography'] class UnknownCitationFormat(Exception): def __init__(self, flavor): self._flavor",
"'ccbysa-4.0']] short_url = models.CharField(max_length=10, unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT,",
"in self.authors.split(','): add('AU', author.strip()) # Publication Year add('PY', format(self.datetime, '%Y/%m/%d/'))",
"in self.surface.tags.all()) s = \"\"\" @online{{ {shortname}, title = {{{title}}},",
"correspond to a real directory. \"\"\" return \"publications/{}/\".format(self.short_url) @property def",
"= {{{year}}}, month = {{{month}}}, date = {{{date}}}, note =",
"publisher_orcid_id = models.CharField(max_length=19, default='') # 16 digits including 3 dashes",
"\"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', ' and '), year=self.datetime.year, month=self.datetime.month, date=format(self.datetime,",
"return f\"Unknown citation format flavor '{self._flavor}'.\" class Publication(models.Model): LICENSE_CHOICES =",
"def get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def get_full_url(self, request): return request.build_absolute_uri(self.get_absolute_url())",
"flavor not in CITATION_FORMAT_FLAVORS: raise UnknownCitationFormat(flavor) method_name = '_get_citation_as_'+flavor return",
"shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_') keywords = \",\".join(DEFAULT_KEYWORDS) if self.surface.tags.count()>0: keywords",
"urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ', ' and",
"= {{{url}}}, urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version, author=self.authors.replace(', ',",
"be empty and last tag add('ER', '') return s.strip() def",
"self.authors.split(','): add('AU', author.strip()) # Publication Year add('PY', format(self.datetime, '%Y/%m/%d/')) #",
"authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='') def get_absolute_url(self): return",
"\",\"+\",\".join(t.name for t in self.surface.tags.all()) s = \"\"\" @misc{{ {shortname},",
"' and '), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return",
"{{{keywords}}}, howpublished = {{{publication_url}}}, }} \"\"\".format(title=title, author=self.authors.replace(', ', ' and",
"a relative path to a directory. If storage is on",
"return request.build_absolute_uri(self.get_absolute_url()) def get_citation(self, flavor, request): if flavor not in",
"' <a href=\"{publication_url}\">{publication_url}</a>' s = s.format( authors=self.authors, year=self.datetime.year, version=self.version, surface=self.surface,",
"\",\"+\",\".join(t.name for t in self.surface.tags.all()) s = \"\"\" @online{{ {shortname},",
"Name of Database add('DB', 'contact.engineering') # Notes add('N1', self.surface.description) #",
"{{{keywords}}}, url = {{{url}}}, urldate = {{{urldate}}} }} \"\"\".format(title=self.surface.name, version=self.version,",
"models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True) license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='')",
"self.surface.tags.all(): add('KW', t.name) # End of record, must be empty",
"default='') authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='') def get_absolute_url(self):",
"contact.engineering. <em>{surface.name} (Version {version})</em>.' s += ' <a href=\"{publication_url}\">{publication_url}</a>' s",
"= {{{note}}}, keywords = {{{keywords}}}, url = {{{url}}}, urldate =",
"Website add('TY', 'ELEC') # Title add('TI', f\"{self.surface.name} (Version {self.version})\") #",
"'), year=self.datetime.year, note=self.surface.description, publication_url=self.get_full_url(request), keywords=keywords, shortname=shortname, ) return s.strip() def",
"= models.CharField(max_length=MAX_LEN_AUTHORS_FIELD) container = models.FileField(max_length=50, default='') def get_absolute_url(self): return reverse('publication:go',",
"= {{{author}}}, year = {{{year}}}, note = {{{note}}}, keywords =",
"Authors for author in self.authors.split(','): add('AU', author.strip()) # Publication Year",
"digits including 3 dashes version = models.PositiveIntegerField(default=1) datetime = models.DateTimeField(auto_now_add=True)",
"and tags for kw in DEFAULT_KEYWORDS: add('KW', kw) for t",
"add('TY', 'ELEC') # Title add('TI', f\"{self.surface.name} (Version {self.version})\") # Authors",
"short_url = models.CharField(max_length=10, unique=True, null=True) surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication')",
"author = {{{author}}}, year = {{{year}}}, month = {{{month}}}, date",
"models.FileField(max_length=50, default='') def get_absolute_url(self): return reverse('publication:go', args=[self.short_url]) def get_full_url(self, request):",
"f\"{key} - {value}\\n\" # Electronic citation / Website add('TY', 'ELEC')",
"return getattr(self, method_name)(request) def _get_citation_as_html(self, request): s = '{authors}. ({year}).",
"django.db import models from django.urls import reverse from django.utils import",
"django.urls import reverse from django.utils import timezone from django.utils.safestring import"
] |
[
"on 2017-07-24 19:36 from __future__ import unicode_literals from django.db import",
"('vendor', '0002_store_image'), ] operations = [ migrations.AddField( model_name='store', name='password', field=models.CharField(default=1,",
"-*- coding: utf-8 -*- # Generated by Django 1.10.5 on",
"-*- # Generated by Django 1.10.5 on 2017-07-24 19:36 from",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'), ]",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'),",
"19:36 from __future__ import unicode_literals from django.db import migrations, models",
"operations = [ migrations.AddField( model_name='store', name='password', field=models.CharField(default=1, max_length=30), preserve_default=False, ),",
"2017-07-24 19:36 from __future__ import unicode_literals from django.db import migrations,",
"= [ ('vendor', '0002_store_image'), ] operations = [ migrations.AddField( model_name='store',",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"] operations = [ migrations.AddField( model_name='store', name='password', field=models.CharField(default=1, max_length=30), preserve_default=False,",
"[ ('vendor', '0002_store_image'), ] operations = [ migrations.AddField( model_name='store', name='password',",
"utf-8 -*- # Generated by Django 1.10.5 on 2017-07-24 19:36",
"Django 1.10.5 on 2017-07-24 19:36 from __future__ import unicode_literals from",
"1.10.5 on 2017-07-24 19:36 from __future__ import unicode_literals from django.db",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-24",
"class Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'), ] operations =",
"Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'), ] operations = [",
"# -*- coding: utf-8 -*- # Generated by Django 1.10.5",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vendor',",
"models class Migration(migrations.Migration): dependencies = [ ('vendor', '0002_store_image'), ] operations",
"Generated by Django 1.10.5 on 2017-07-24 19:36 from __future__ import",
"'0002_store_image'), ] operations = [ migrations.AddField( model_name='store', name='password', field=models.CharField(default=1, max_length=30),",
"dependencies = [ ('vendor', '0002_store_image'), ] operations = [ migrations.AddField(",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"= [ migrations.AddField( model_name='store', name='password', field=models.CharField(default=1, max_length=30), preserve_default=False, ), ]",
"by Django 1.10.5 on 2017-07-24 19:36 from __future__ import unicode_literals",
"# Generated by Django 1.10.5 on 2017-07-24 19:36 from __future__",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"from __future__ import unicode_literals from django.db import migrations, models class"
] |
[
"World\".lower()) #print(\"hello\" + \"world\" + \".\") #print(2**3) #my_str = \"hello",
"Your module description \"\"\" \"\"\" this is my second py",
"commment # this is my second line comment #print(type(\"123.\")) #print",
"+ \".\") #print(2**3) #my_str = \"hello world\" #print(my_str) #my_str =",
"\".\") #print(2**3) #my_str = \"hello world\" #print(my_str) #my_str = \"Tom\"",
"this is a single line commment # this is my",
"world\" #print(my_str) #my_str = \"Tom\" #print(my_str) my_int = 2 my_float",
"code for my second lecture \"\"\" #print ('hello world') #",
"\"\"\" Your module description \"\"\" \"\"\" this is my second",
"#print ('hello world') # this is a single line commment",
"comment #print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" + \"world\"",
"(\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" + \"world\" + \".\") #print(2**3)",
"#print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" + \"world\" +",
"\"\"\" \"\"\" this is my second py code for my",
"py code for my second lecture \"\"\" #print ('hello world')",
"#my_str = \"hello world\" #print(my_str) #my_str = \"Tom\" #print(my_str) my_int",
"#print(\"Hello World\".lower()) #print(\"hello\" + \"world\" + \".\") #print(2**3) #my_str =",
"second line comment #print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\"",
"second py code for my second lecture \"\"\" #print ('hello",
"#my_str = \"Tom\" #print(my_str) my_int = 2 my_float = 3.0",
"#print(my_str) my_int = 2 my_float = 3.0 print(my_int + my_float)",
"\"\"\" this is my second py code for my second",
"is my second py code for my second lecture \"\"\"",
"this is my second line comment #print(type(\"123.\")) #print (\"Hello World\".upper())",
"for my second lecture \"\"\" #print ('hello world') # this",
"is my second line comment #print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello",
"my second line comment #print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello World\".lower())",
"World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" + \"world\" + \".\") #print(2**3) #my_str",
"world') # this is a single line commment # this",
"this is my second py code for my second lecture",
"#print (\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" + \"world\" + \".\")",
"second lecture \"\"\" #print ('hello world') # this is a",
"my second py code for my second lecture \"\"\" #print",
"line commment # this is my second line comment #print(type(\"123.\"))",
"+ \"world\" + \".\") #print(2**3) #my_str = \"hello world\" #print(my_str)",
"= \"hello world\" #print(my_str) #my_str = \"Tom\" #print(my_str) my_int =",
"#print(my_str) #my_str = \"Tom\" #print(my_str) my_int = 2 my_float =",
"#print(\"hello\" + \"world\" + \".\") #print(2**3) #my_str = \"hello world\"",
"\"\"\" #print ('hello world') # this is a single line",
"# this is a single line commment # this is",
"module description \"\"\" \"\"\" this is my second py code",
"a single line commment # this is my second line",
"('hello world') # this is a single line commment #",
"description \"\"\" \"\"\" this is my second py code for",
"is a single line commment # this is my second",
"# this is my second line comment #print(type(\"123.\")) #print (\"Hello",
"\"world\" + \".\") #print(2**3) #my_str = \"hello world\" #print(my_str) #my_str",
"single line commment # this is my second line comment",
"lecture \"\"\" #print ('hello world') # this is a single",
"line comment #print(type(\"123.\")) #print (\"Hello World\".upper()) #print(\"Hello World\".lower()) #print(\"hello\" +",
"= \"Tom\" #print(my_str) my_int = 2 my_float = 3.0 print(my_int",
"#print(2**3) #my_str = \"hello world\" #print(my_str) #my_str = \"Tom\" #print(my_str)",
"<gh_stars>0 \"\"\" Your module description \"\"\" \"\"\" this is my",
"\"Tom\" #print(my_str) my_int = 2 my_float = 3.0 print(my_int +",
"\"hello world\" #print(my_str) #my_str = \"Tom\" #print(my_str) my_int = 2",
"my second lecture \"\"\" #print ('hello world') # this is"
] |
[
"file: data = file.read() return play_combat(data) if __name__ == \"__main__\":",
"c = [] for p in s.splitlines()[1:]: c.append(int(p)) return c",
"s def convert_cards(s: str) -> list: c = [] for",
"p2.append(c1) return winner def play_combat(s: str): p1, p2 = s.strip().split(\"\\n\\n\")",
"len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2]) else: winner = c1 >",
"i return s def convert_cards(s: str) -> list: c =",
"= file.read() return play_combat(data) if __name__ == \"__main__\": run_tests() import",
"with open(\"inputs/input_22.txt\") as file: data = file.read() return play_combat(data) if",
"8 4 7 10\"\"\" test_output = 291 assert play_combat(test_input) ==",
"29 14\"\"\" assert play_combat(test_input) def run() -> int: with open(\"inputs/input_22.txt\")",
"time.perf_counter() print(run()) time_end = time.perf_counter() - time_start print(f\"Time: {time_end:0.4f} sec\")",
"winner def play_combat(s: str): p1, p2 = s.strip().split(\"\\n\\n\") p1, p2",
"winner: p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1) return winner def play_combat(s:",
"0 for i, c in enumerate(reversed(w), 1): s += c",
"p1 if winner else p2 s = 0 for i,",
"if r in rounds: return True else: rounds.add(r) c1 =",
"= \"\"\"Player 1: 43 19 Player 2: 2 29 14\"\"\"",
"r = tuple(p1 + [-1] + p2) if r in",
"= p1 if winner else p2 s = 0 for",
"19 Player 2: 2 29 14\"\"\" assert play_combat(test_input) def run()",
"return True else: rounds.add(r) c1 = p1.pop(0) c2 = p2.pop(0)",
"s.splitlines()[1:]: c.append(int(p)) return c def run_tests(): test_input = \"\"\"Player 1:",
"c def run_tests(): test_input = \"\"\"Player 1: 9 2 6",
"winner = None while len(p1) > 0 and len(p2) >",
"in enumerate(reversed(w), 1): s += c * i return s",
"def convert_cards(s: str) -> list: c = [] for p",
"= p1.pop(0) c2 = p2.pop(0) if c1 <= len(p1) and",
"9 2 6 3 1 Player 2: 5 8 4",
"play_combat(data) if __name__ == \"__main__\": run_tests() import time time_start =",
"= c1 > c2 if winner: p1.append(c1) p1.append(c2) else: p2.append(c2)",
"data = file.read() return play_combat(data) if __name__ == \"__main__\": run_tests()",
"rounds.add(r) c1 = p1.pop(0) c2 = p2.pop(0) if c1 <=",
"2 6 3 1 Player 2: 5 8 4 7",
"4 7 10\"\"\" test_output = 291 assert play_combat(test_input) == test_output",
"for p in s.splitlines()[1:]: c.append(int(p)) return c def run_tests(): test_input",
"[-1] + p2) if r in rounds: return True else:",
"p1.pop(0) c2 = p2.pop(0) if c1 <= len(p1) and c2",
"* i return s def convert_cards(s: str) -> list: c",
"if winner else p2 s = 0 for i, c",
"= play_recursively_combat(p1[:c1], p2[:c2]) else: winner = c1 > c2 if",
"len(p2) > 0: r = tuple(p1 + [-1] + p2)",
"p2 = convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1, p2) w =",
"> c2 if winner: p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1) return",
"def run() -> int: with open(\"inputs/input_22.txt\") as file: data =",
"43 19 Player 2: 2 29 14\"\"\" assert play_combat(test_input) def",
"c1 <= len(p1) and c2 <= len(p2): winner = play_recursively_combat(p1[:c1],",
"test_input = \"\"\"Player 1: 9 2 6 3 1 Player",
"1: 9 2 6 3 1 Player 2: 5 8",
"0: r = tuple(p1 + [-1] + p2) if r",
"len(p1) > 0 and len(p2) > 0: r = tuple(p1",
"return winner def play_combat(s: str): p1, p2 = s.strip().split(\"\\n\\n\") p1,",
"i, c in enumerate(reversed(w), 1): s += c * i",
"convert_cards(s: str) -> list: c = [] for p in",
"play_combat(s: str): p1, p2 = s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1),",
"= [] for p in s.splitlines()[1:]: c.append(int(p)) return c def",
"list, p2: list) -> bool: rounds = set() winner =",
"assert play_combat(test_input) def run() -> int: with open(\"inputs/input_22.txt\") as file:",
"\"__main__\": run_tests() import time time_start = time.perf_counter() print(run()) time_end =",
"c * i return s def convert_cards(s: str) -> list:",
"rounds = set() winner = None while len(p1) > 0",
"while len(p1) > 0 and len(p2) > 0: r =",
"return play_combat(data) if __name__ == \"__main__\": run_tests() import time time_start",
"1 Player 2: 5 8 4 7 10\"\"\" test_output =",
"<= len(p1) and c2 <= len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2])",
"c1 > c2 if winner: p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1)",
"test_output = 291 assert play_combat(test_input) == test_output test_input = \"\"\"Player",
"file.read() return play_combat(data) if __name__ == \"__main__\": run_tests() import time",
"if __name__ == \"__main__\": run_tests() import time time_start = time.perf_counter()",
"set() winner = None while len(p1) > 0 and len(p2)",
"play_recursively_combat(p1[:c1], p2[:c2]) else: winner = c1 > c2 if winner:",
"2: 5 8 4 7 10\"\"\" test_output = 291 assert",
"run() -> int: with open(\"inputs/input_22.txt\") as file: data = file.read()",
"s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1, p2)",
"def run_tests(): test_input = \"\"\"Player 1: 9 2 6 3",
"c2 if winner: p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1) return winner",
"+ p2) if r in rounds: return True else: rounds.add(r)",
"= tuple(p1 + [-1] + p2) if r in rounds:",
"p2.pop(0) if c1 <= len(p1) and c2 <= len(p2): winner",
"bool: rounds = set() winner = None while len(p1) >",
"convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1, p2) w = p1 if",
"in s.splitlines()[1:]: c.append(int(p)) return c def run_tests(): test_input = \"\"\"Player",
"assert play_combat(test_input) == test_output test_input = \"\"\"Player 1: 43 19",
"10\"\"\" test_output = 291 assert play_combat(test_input) == test_output test_input =",
"<reponame>Gyaha/AOC2020<filename>day_22_b.py def play_recursively_combat(p1: list, p2: list) -> bool: rounds =",
"test_input = \"\"\"Player 1: 43 19 Player 2: 2 29",
"return c def run_tests(): test_input = \"\"\"Player 1: 9 2",
"p1, p2 = s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1), convert_cards(p2) winner",
"s += c * i return s def convert_cards(s: str)",
"run_tests() import time time_start = time.perf_counter() print(run()) time_end = time.perf_counter()",
"6 3 1 Player 2: 5 8 4 7 10\"\"\"",
"[] for p in s.splitlines()[1:]: c.append(int(p)) return c def run_tests():",
"len(p1) and c2 <= len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2]) else:",
"p2 s = 0 for i, c in enumerate(reversed(w), 1):",
"0 and len(p2) > 0: r = tuple(p1 + [-1]",
"= convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1, p2) w = p1",
"\"\"\"Player 1: 43 19 Player 2: 2 29 14\"\"\" assert",
"str): p1, p2 = s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1), convert_cards(p2)",
"time time_start = time.perf_counter() print(run()) time_end = time.perf_counter() - time_start",
"c2 <= len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2]) else: winner =",
"if c1 <= len(p1) and c2 <= len(p2): winner =",
"> 0: r = tuple(p1 + [-1] + p2) if",
"p2: list) -> bool: rounds = set() winner = None",
"+= c * i return s def convert_cards(s: str) ->",
"5 8 4 7 10\"\"\" test_output = 291 assert play_combat(test_input)",
"winner else p2 s = 0 for i, c in",
"= None while len(p1) > 0 and len(p2) > 0:",
"list) -> bool: rounds = set() winner = None while",
"c in enumerate(reversed(w), 1): s += c * i return",
"winner = play_recursively_combat(p1[:c1], p2[:c2]) else: winner = c1 > c2",
"test_output test_input = \"\"\"Player 1: 43 19 Player 2: 2",
"winner = c1 > c2 if winner: p1.append(c1) p1.append(c2) else:",
"-> int: with open(\"inputs/input_22.txt\") as file: data = file.read() return",
"<= len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2]) else: winner = c1",
"Player 2: 5 8 4 7 10\"\"\" test_output = 291",
"= set() winner = None while len(p1) > 0 and",
"r in rounds: return True else: rounds.add(r) c1 = p1.pop(0)",
"c1 = p1.pop(0) c2 = p2.pop(0) if c1 <= len(p1)",
"__name__ == \"__main__\": run_tests() import time time_start = time.perf_counter() print(run())",
"p2.append(c2) p2.append(c1) return winner def play_combat(s: str): p1, p2 =",
"else: winner = c1 > c2 if winner: p1.append(c1) p1.append(c2)",
"tuple(p1 + [-1] + p2) if r in rounds: return",
"in rounds: return True else: rounds.add(r) c1 = p1.pop(0) c2",
"2 29 14\"\"\" assert play_combat(test_input) def run() -> int: with",
"= p2.pop(0) if c1 <= len(p1) and c2 <= len(p2):",
"p2) if r in rounds: return True else: rounds.add(r) c1",
"True else: rounds.add(r) c1 = p1.pop(0) c2 = p2.pop(0) if",
"Player 2: 2 29 14\"\"\" assert play_combat(test_input) def run() ->",
"def play_combat(s: str): p1, p2 = s.strip().split(\"\\n\\n\") p1, p2 =",
"def play_recursively_combat(p1: list, p2: list) -> bool: rounds = set()",
"open(\"inputs/input_22.txt\") as file: data = file.read() return play_combat(data) if __name__",
"play_recursively_combat(p1, p2) w = p1 if winner else p2 s",
"1): s += c * i return s def convert_cards(s:",
"14\"\"\" assert play_combat(test_input) def run() -> int: with open(\"inputs/input_22.txt\") as",
"p2 = s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1), convert_cards(p2) winner =",
"== \"__main__\": run_tests() import time time_start = time.perf_counter() print(run()) time_end",
"= 0 for i, c in enumerate(reversed(w), 1): s +=",
"3 1 Player 2: 5 8 4 7 10\"\"\" test_output",
"for i, c in enumerate(reversed(w), 1): s += c *",
"play_combat(test_input) == test_output test_input = \"\"\"Player 1: 43 19 Player",
"else: p2.append(c2) p2.append(c1) return winner def play_combat(s: str): p1, p2",
"= \"\"\"Player 1: 9 2 6 3 1 Player 2:",
"time_start = time.perf_counter() print(run()) time_end = time.perf_counter() - time_start print(f\"Time:",
"return s def convert_cards(s: str) -> list: c = []",
"run_tests(): test_input = \"\"\"Player 1: 9 2 6 3 1",
"p2) w = p1 if winner else p2 s =",
"= 291 assert play_combat(test_input) == test_output test_input = \"\"\"Player 1:",
"p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1) return winner def play_combat(s: str):",
"p1.append(c2) else: p2.append(c2) p2.append(c1) return winner def play_combat(s: str): p1,",
"else p2 s = 0 for i, c in enumerate(reversed(w),",
"c.append(int(p)) return c def run_tests(): test_input = \"\"\"Player 1: 9",
"7 10\"\"\" test_output = 291 assert play_combat(test_input) == test_output test_input",
"import time time_start = time.perf_counter() print(run()) time_end = time.perf_counter() -",
"1: 43 19 Player 2: 2 29 14\"\"\" assert play_combat(test_input)",
"enumerate(reversed(w), 1): s += c * i return s def",
"s = 0 for i, c in enumerate(reversed(w), 1): s",
"else: rounds.add(r) c1 = p1.pop(0) c2 = p2.pop(0) if c1",
"p in s.splitlines()[1:]: c.append(int(p)) return c def run_tests(): test_input =",
"== test_output test_input = \"\"\"Player 1: 43 19 Player 2:",
"if winner: p1.append(c1) p1.append(c2) else: p2.append(c2) p2.append(c1) return winner def",
"c2 = p2.pop(0) if c1 <= len(p1) and c2 <=",
"winner = play_recursively_combat(p1, p2) w = p1 if winner else",
"play_recursively_combat(p1: list, p2: list) -> bool: rounds = set() winner",
"play_combat(test_input) def run() -> int: with open(\"inputs/input_22.txt\") as file: data",
"rounds: return True else: rounds.add(r) c1 = p1.pop(0) c2 =",
"int: with open(\"inputs/input_22.txt\") as file: data = file.read() return play_combat(data)",
"-> list: c = [] for p in s.splitlines()[1:]: c.append(int(p))",
"w = p1 if winner else p2 s = 0",
"= time.perf_counter() print(run()) time_end = time.perf_counter() - time_start print(f\"Time: {time_end:0.4f}",
"convert_cards(p2) winner = play_recursively_combat(p1, p2) w = p1 if winner",
"None while len(p1) > 0 and len(p2) > 0: r",
"and c2 <= len(p2): winner = play_recursively_combat(p1[:c1], p2[:c2]) else: winner",
"\"\"\"Player 1: 9 2 6 3 1 Player 2: 5",
"str) -> list: c = [] for p in s.splitlines()[1:]:",
"+ [-1] + p2) if r in rounds: return True",
"> 0 and len(p2) > 0: r = tuple(p1 +",
"= s.strip().split(\"\\n\\n\") p1, p2 = convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1,",
"= play_recursively_combat(p1, p2) w = p1 if winner else p2",
"-> bool: rounds = set() winner = None while len(p1)",
"291 assert play_combat(test_input) == test_output test_input = \"\"\"Player 1: 43",
"and len(p2) > 0: r = tuple(p1 + [-1] +",
"p2[:c2]) else: winner = c1 > c2 if winner: p1.append(c1)",
"list: c = [] for p in s.splitlines()[1:]: c.append(int(p)) return",
"p1, p2 = convert_cards(p1), convert_cards(p2) winner = play_recursively_combat(p1, p2) w",
"as file: data = file.read() return play_combat(data) if __name__ ==",
"2: 2 29 14\"\"\" assert play_combat(test_input) def run() -> int:"
] |
[
"= 0x02 # currently do not in use RECON_PROOF =",
"currently do not in use REALMLIST = 0x10 class LoginResult(Enum):",
"process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01 RECON_CHALL =",
"use RECON_PROOF = 0x03 # currently do not in use",
"not in use RECON_PROOF = 0x03 # currently do not",
"during login process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01",
"from enum import Enum class LoginOpCode(Enum): ''' Opcodes during login",
"in use REALMLIST = 0x10 class LoginResult(Enum): ''' Error codes",
"''' Opcodes during login process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF",
"LoginOpCode(Enum): ''' Opcodes during login process ''' LOGIN_CHALL = 0x00",
"use REALMLIST = 0x10 class LoginResult(Enum): ''' Error codes '''",
"0x10 class LoginResult(Enum): ''' Error codes ''' SUCCESS = 0x00",
"import Enum class LoginOpCode(Enum): ''' Opcodes during login process '''",
"= 0x00 LOGIN_PROOF = 0x01 RECON_CHALL = 0x02 # currently",
"LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01 RECON_CHALL = 0x02 #",
"LOGIN_PROOF = 0x01 RECON_CHALL = 0x02 # currently do not",
"''' LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01 RECON_CHALL = 0x02",
"currently do not in use RECON_PROOF = 0x03 # currently",
"# currently do not in use RECON_PROOF = 0x03 #",
"= 0x01 RECON_CHALL = 0x02 # currently do not in",
"in use RECON_PROOF = 0x03 # currently do not in",
"0x00 LOGIN_PROOF = 0x01 RECON_CHALL = 0x02 # currently do",
"RECON_PROOF = 0x03 # currently do not in use REALMLIST",
"REALMLIST = 0x10 class LoginResult(Enum): ''' Error codes ''' SUCCESS",
"not in use REALMLIST = 0x10 class LoginResult(Enum): ''' Error",
"do not in use REALMLIST = 0x10 class LoginResult(Enum): '''",
"enum import Enum class LoginOpCode(Enum): ''' Opcodes during login process",
"<reponame>sundayz/idewave-core from enum import Enum class LoginOpCode(Enum): ''' Opcodes during",
"login process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF = 0x01 RECON_CHALL",
"RECON_CHALL = 0x02 # currently do not in use RECON_PROOF",
"class LoginOpCode(Enum): ''' Opcodes during login process ''' LOGIN_CHALL =",
"do not in use RECON_PROOF = 0x03 # currently do",
"0x02 # currently do not in use RECON_PROOF = 0x03",
"0x03 # currently do not in use REALMLIST = 0x10",
"Enum class LoginOpCode(Enum): ''' Opcodes during login process ''' LOGIN_CHALL",
"# currently do not in use REALMLIST = 0x10 class",
"0x01 RECON_CHALL = 0x02 # currently do not in use",
"= 0x10 class LoginResult(Enum): ''' Error codes ''' SUCCESS =",
"= 0x03 # currently do not in use REALMLIST =",
"Opcodes during login process ''' LOGIN_CHALL = 0x00 LOGIN_PROOF ="
] |
[
"-*- coding: utf-8 -*- from .LineApi import LINE from .lib.Gen.ttypes",
"utf-8 -*- from .LineApi import LINE from .lib.Gen.ttypes import *",
"# -*- coding: utf-8 -*- from .LineApi import LINE from",
"coding: utf-8 -*- from .LineApi import LINE from .lib.Gen.ttypes import",
"<reponame>pratannaimjoi/tokenIpad # -*- coding: utf-8 -*- from .LineApi import LINE"
] |
[
"17, 2021 @author: Sean ''' import PDF2CSV_GUI def main(): j",
"@author: Sean ''' import PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI()",
"''' import PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI() if __name__",
"<filename>main.py ''' Created on Jun 17, 2021 @author: Sean '''",
"Jun 17, 2021 @author: Sean ''' import PDF2CSV_GUI def main():",
"on Jun 17, 2021 @author: Sean ''' import PDF2CSV_GUI def",
"PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI() if __name__ == \"__main__\":",
"Created on Jun 17, 2021 @author: Sean ''' import PDF2CSV_GUI",
"''' Created on Jun 17, 2021 @author: Sean ''' import",
"def main(): j = PDF2CSV_GUI.Convert_GUI() if __name__ == \"__main__\": main()",
"2021 @author: Sean ''' import PDF2CSV_GUI def main(): j =",
"Sean ''' import PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI() if",
"import PDF2CSV_GUI def main(): j = PDF2CSV_GUI.Convert_GUI() if __name__ =="
] |
[
"= reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text:",
"submission in subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text: \", submission.selftext) print(\"Score:",
"reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text: \",",
"for submission in subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text: \", submission.selftext)",
"praw reddit = praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for submission in",
"praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5): print(\"Title: \",",
"= praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5): print(\"Title:",
"#!/usr/bin/python import praw reddit = praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for",
"subreddit = reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5): print(\"Title: \", submission.title)",
"import praw reddit = praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for submission",
"reddit = praw.Reddit('mob-secondbot') subreddit = reddit.subreddit(\"learnpython\") for submission in subreddit.hot(limit=5):",
"in subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text: \", submission.selftext) print(\"Score: \",",
"subreddit.hot(limit=5): print(\"Title: \", submission.title) print(\"Text: \", submission.selftext) print(\"Score: \", submission.score)",
"print(\"Title: \", submission.title) print(\"Text: \", submission.selftext) print(\"Score: \", submission.score) print(\"---------------------------------\\n\")"
] |
[
"\"もっと大きいよ。\" << endl; } else { cout << \"もっと小さいよ。\" <<",
"{ cout << \"不正な入力です。\" << endl; continue; } count++; bool",
"{ cout << \"正解です。おめでとう。 (\" << count << \" 回目)\"",
"{ random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1,",
"(1) { int i; cout << \"数を当ててみて \"; cin >>",
"100); int count = 0; int num = randint(mt); while",
"\"; cin >> i; if (i < 1 || i",
"<random> using namespace std; int main() { random_device rd; mt19937",
"|| i > 100) { cout << \"不正な入力です。\" << endl;",
"if (i < 1 || i > 100) { cout",
"0; } \"\"\"; proc = Popen([\"g++\", \"-o\", name, \"-x\", \"c++\",",
"int i; cout << \"数を当ててみて \"; cin >> i; if",
"count = 0; int num = randint(mt); while (1) {",
"<< \"もっと小さいよ。\" << endl; } } return 0; } \"\"\";",
"cout << \"もっと小さいよ。\" << endl; } } return 0; }",
"\"kazuate_liar.o\" src = \"\"\" #include <iostream> #include <random> using namespace",
"else { cout << \"もっと小さいよ。\" << endl; } } return",
"using namespace std; int main() { random_device rd; mt19937 mt(rd());",
"(\" << count << \" 回目)\" << endl; break; }",
"num) { cout << \"もっと大きいよ。\" << endl; } else {",
"return 0; } \"\"\"; proc = Popen([\"g++\", \"-o\", name, \"-x\",",
"1 || i > 100) { cout << \"不正な入力です。\" <<",
"< 1 || i > 100) { cout << \"不正な入力です。\"",
"Popen([\"g++\", \"-o\", name, \"-x\", \"c++\", \"-\"], stdin = PIPE); proc.communicate(src.encode());",
"num = randint(mt); while (1) { int i; cout <<",
"num) { cout << \"正解です。おめでとう。 (\" << count << \"",
"mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int count =",
"randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int count = 0; int",
"import Popen, PIPE, call name = \"kazuate_liar.o\" src = \"\"\"",
"else if ((liar && i > num) || i <",
"randfive(mt) == 0; if (i == num) { cout <<",
"== 0; if (i == num) { cout << \"正解です。おめでとう。",
"cout << \"正解です。おめでとう。 (\" << count << \" 回目)\" <<",
"<< endl; } else { cout << \"もっと小さいよ。\" << endl;",
"= \"\"\" #include <iostream> #include <random> using namespace std; int",
"\"正解です。おめでとう。 (\" << count << \" 回目)\" << endl; break;",
"#include <iostream> #include <random> using namespace std; int main() {",
"} else { cout << \"もっと小さいよ。\" << endl; } }",
"= 0; int num = randint(mt); while (1) { int",
"bool liar = randfive(mt) == 0; if (i == num)",
"name, \"-x\", \"c++\", \"-\"], stdin = PIPE); proc.communicate(src.encode()); call([\"./\" +",
"uniform_int_distribution<int> randint(1, 100); int count = 0; int num =",
"break; } else if ((liar && i > num) ||",
"= randint(mt); while (1) { int i; cout << \"数を当ててみて",
"continue; } count++; bool liar = randfive(mt) == 0; if",
"i; if (i < 1 || i > 100) {",
"from subprocess import Popen, PIPE, call name = \"kazuate_liar.o\" src",
"回目)\" << endl; break; } else if ((liar && i",
"== num) { cout << \"正解です。おめでとう。 (\" << count <<",
"cout << \"もっと大きいよ。\" << endl; } else { cout <<",
"<< \"正解です。おめでとう。 (\" << count << \" 回目)\" << endl;",
"subprocess import Popen, PIPE, call name = \"kazuate_liar.o\" src =",
"4); uniform_int_distribution<int> randint(1, 100); int count = 0; int num",
"int count = 0; int num = randint(mt); while (1)",
"count++; bool liar = randfive(mt) == 0; if (i ==",
"random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100);",
"((liar && i > num) || i < num) {",
"num) || i < num) { cout << \"もっと大きいよ。\" <<",
"(i < 1 || i > 100) { cout <<",
"cout << \"数を当ててみて \"; cin >> i; if (i <",
"proc = Popen([\"g++\", \"-o\", name, \"-x\", \"c++\", \"-\"], stdin =",
"randint(1, 100); int count = 0; int num = randint(mt);",
"i > 100) { cout << \"不正な入力です。\" << endl; continue;",
"|| i < num) { cout << \"もっと大きいよ。\" << endl;",
"} count++; bool liar = randfive(mt) == 0; if (i",
"\"不正な入力です。\" << endl; continue; } count++; bool liar = randfive(mt)",
"i < num) { cout << \"もっと大きいよ。\" << endl; }",
"i > num) || i < num) { cout <<",
"Popen, PIPE, call name = \"kazuate_liar.o\" src = \"\"\" #include",
"\"\"\"; proc = Popen([\"g++\", \"-o\", name, \"-x\", \"c++\", \"-\"], stdin",
"<< count << \" 回目)\" << endl; break; } else",
"call name = \"kazuate_liar.o\" src = \"\"\" #include <iostream> #include",
"endl; } else { cout << \"もっと小さいよ。\" << endl; }",
"int main() { random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4);",
"<filename>17/kazuate_liar.cpp.py from subprocess import Popen, PIPE, call name = \"kazuate_liar.o\"",
"<< endl; } } return 0; } \"\"\"; proc =",
"<< endl; break; } else if ((liar && i >",
"\"数を当ててみて \"; cin >> i; if (i < 1 ||",
"if ((liar && i > num) || i < num)",
"&& i > num) || i < num) { cout",
"randint(mt); while (1) { int i; cout << \"数を当ててみて \";",
"\"\"\" #include <iostream> #include <random> using namespace std; int main()",
"< num) { cout << \"もっと大きいよ。\" << endl; } else",
"name = \"kazuate_liar.o\" src = \"\"\" #include <iostream> #include <random>",
"<< \"もっと大きいよ。\" << endl; } else { cout << \"もっと小さいよ。\"",
"<< \"数を当ててみて \"; cin >> i; if (i < 1",
"endl; break; } else if ((liar && i > num)",
"i; cout << \"数を当ててみて \"; cin >> i; if (i",
"0; int num = randint(mt); while (1) { int i;",
"#include <random> using namespace std; int main() { random_device rd;",
"mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int count",
"\"もっと小さいよ。\" << endl; } } return 0; } \"\"\"; proc",
"main() { random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int>",
"int num = randint(mt); while (1) { int i; cout",
"liar = randfive(mt) == 0; if (i == num) {",
"} else if ((liar && i > num) || i",
"namespace std; int main() { random_device rd; mt19937 mt(rd()); uniform_int_distribution<int>",
"<iostream> #include <random> using namespace std; int main() { random_device",
"100) { cout << \"不正な入力です。\" << endl; continue; } count++;",
"endl; continue; } count++; bool liar = randfive(mt) == 0;",
"{ cout << \"もっと小さいよ。\" << endl; } } return 0;",
">> i; if (i < 1 || i > 100)",
"while (1) { int i; cout << \"数を当ててみて \"; cin",
"\"-x\", \"c++\", \"-\"], stdin = PIPE); proc.communicate(src.encode()); call([\"./\" + name]);",
"<< \"不正な入力です。\" << endl; continue; } count++; bool liar =",
"uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int count = 0;",
"> 100) { cout << \"不正な入力です。\" << endl; continue; }",
"{ cout << \"もっと大きいよ。\" << endl; } else { cout",
"endl; } } return 0; } \"\"\"; proc = Popen([\"g++\",",
"= Popen([\"g++\", \"-o\", name, \"-x\", \"c++\", \"-\"], stdin = PIPE);",
"rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0, 4); uniform_int_distribution<int> randint(1, 100); int",
"cin >> i; if (i < 1 || i >",
"= randfive(mt) == 0; if (i == num) { cout",
"src = \"\"\" #include <iostream> #include <random> using namespace std;",
"if (i == num) { cout << \"正解です。おめでとう。 (\" <<",
"count << \" 回目)\" << endl; break; } else if",
"(i == num) { cout << \"正解です。おめでとう。 (\" << count",
"> num) || i < num) { cout << \"もっと大きいよ。\"",
"PIPE, call name = \"kazuate_liar.o\" src = \"\"\" #include <iostream>",
"cout << \"不正な入力です。\" << endl; continue; } count++; bool liar",
"\" 回目)\" << endl; break; } else if ((liar &&",
"<< endl; continue; } count++; bool liar = randfive(mt) ==",
"= \"kazuate_liar.o\" src = \"\"\" #include <iostream> #include <random> using",
"std; int main() { random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> randfive(0,",
"} return 0; } \"\"\"; proc = Popen([\"g++\", \"-o\", name,",
"} \"\"\"; proc = Popen([\"g++\", \"-o\", name, \"-x\", \"c++\", \"-\"],",
"0; if (i == num) { cout << \"正解です。おめでとう。 (\"",
"{ int i; cout << \"数を当ててみて \"; cin >> i;",
"} } return 0; } \"\"\"; proc = Popen([\"g++\", \"-o\",",
"<< \" 回目)\" << endl; break; } else if ((liar",
"\"-o\", name, \"-x\", \"c++\", \"-\"], stdin = PIPE); proc.communicate(src.encode()); call([\"./\""
] |
[
"click from .providers.aws import Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output import",
"of a terraform template\") @click.version_option() @click.pass_context def cli(ctx, commands=False): ctx.obj",
"cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ == \"__main__\": # pylint: disable=unexpected-keyword-arg,no-value-for-parameter cli(obj={})",
"for specific resources \"\"\" import click from .providers.aws import Aws",
"resources \"\"\" import click from .providers.aws import Aws @click.group() @click.option('--commands',",
"commands instead of a terraform template\") @click.version_option() @click.pass_context def cli(ctx,",
"Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output import commands instead of a",
"import Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output import commands instead of",
"<gh_stars>1-10 \"\"\" Terrafort Generate terraform templates for specific resources \"\"\"",
"Terrafort Generate terraform templates for specific resources \"\"\" import click",
"terraform template\") @click.version_option() @click.pass_context def cli(ctx, commands=False): ctx.obj = {'commands':",
"terraform templates for specific resources \"\"\" import click from .providers.aws",
"commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ == \"__main__\": #",
"instead of a terraform template\") @click.version_option() @click.pass_context def cli(ctx, commands=False):",
"cli(ctx, commands=False): ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group)",
"= {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ ==",
"help=\"Output import commands instead of a terraform template\") @click.version_option() @click.pass_context",
"@click.group() @click.option('--commands', is_flag=True, help=\"Output import commands instead of a terraform",
"cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ == \"__main__\": # pylint: disable=unexpected-keyword-arg,no-value-for-parameter",
"\"\"\" import click from .providers.aws import Aws @click.group() @click.option('--commands', is_flag=True,",
"@click.option('--commands', is_flag=True, help=\"Output import commands instead of a terraform template\")",
"@click.version_option() @click.pass_context def cli(ctx, commands=False): ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance)",
"commands=False): ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if",
"@click.pass_context def cli(ctx, commands=False): ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile)",
"specific resources \"\"\" import click from .providers.aws import Aws @click.group()",
"cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ == \"__main__\": # pylint:",
"a terraform template\") @click.version_option() @click.pass_context def cli(ctx, commands=False): ctx.obj =",
"import click from .providers.aws import Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output",
"from .providers.aws import Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output import commands",
"{'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__ == \"__main__\":",
"is_flag=True, help=\"Output import commands instead of a terraform template\") @click.version_option()",
"\"\"\" Terrafort Generate terraform templates for specific resources \"\"\" import",
".providers.aws import Aws @click.group() @click.option('--commands', is_flag=True, help=\"Output import commands instead",
"templates for specific resources \"\"\" import click from .providers.aws import",
"import commands instead of a terraform template\") @click.version_option() @click.pass_context def",
"def cli(ctx, commands=False): ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance)",
"Generate terraform templates for specific resources \"\"\" import click from",
"template\") @click.version_option() @click.pass_context def cli(ctx, commands=False): ctx.obj = {'commands': commands}",
"ctx.obj = {'commands': commands} cli.add_command(Aws.aws_db_instance) cli.add_command(Aws.aws_iam_instance_profile) cli.add_command(Aws.aws_instance) cli.add_command(Aws.aws_security_group) if __name__"
] |
[
"= bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping of client'",
"def __init__(self, bot: app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping',",
"app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping",
"import app_util class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot =",
"class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot = bot @app_util.Cog.command(",
"discord import app_util class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot",
"guild_id=877399405056102431 ) async def command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency *",
"bot: app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg",
"<gh_stars>0 import discord import app_util class Ping(app_util.Cog): def __init__(self, bot:",
"client' ), guild_id=877399405056102431 ) async def command(self, ctx: app_util.Context): await",
"ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency * 1000:.2f}ms')) def setup(bot: app_util.Bot): bot.add_application_cog(Ping(bot))",
"), guild_id=877399405056102431 ) async def command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency",
"of client' ), guild_id=877399405056102431 ) async def command(self, ctx: app_util.Context):",
"import discord import app_util class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot):",
"app_util class Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot = bot",
"def command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency * 1000:.2f}ms')) def setup(bot:",
"description='shows avg ping of client' ), guild_id=877399405056102431 ) async def",
"avg ping of client' ), guild_id=877399405056102431 ) async def command(self,",
"command=app_util.SlashCommand( name='ping', description='shows avg ping of client' ), guild_id=877399405056102431 )",
"async def command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency * 1000:.2f}ms')) def",
"command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency * 1000:.2f}ms')) def setup(bot: app_util.Bot):",
"ping of client' ), guild_id=877399405056102431 ) async def command(self, ctx:",
"self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping of",
") async def command(self, ctx: app_util.Context): await ctx.send_response(embed=discord.Embed(title=f'{self.bot.latency * 1000:.2f}ms'))",
"@app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping of client' ), guild_id=877399405056102431",
"Ping(app_util.Cog): def __init__(self, bot: app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand(",
"__init__(self, bot: app_util.Bot): self.bot = bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows",
"bot @app_util.Cog.command( command=app_util.SlashCommand( name='ping', description='shows avg ping of client' ),",
"name='ping', description='shows avg ping of client' ), guild_id=877399405056102431 ) async"
] |
[
"white. tiles = {} for line in open(sys.argv[1]).read().splitlines(): pos =",
"in tiles: tiles[t] = not tiles[t] else: tiles[t] = True",
"(x, y): True/False in tiles. True = black, False =",
"'sw': (-1, 2), 'w': (-2, 0), 'nw': (-1, -2), 'ne':",
"from PIL import Image moves = { 'e': (2, 0),",
"do outer edge (to avoid special cases) for y in",
"sys import re import numpy as np from PIL import",
"'e': (2, 0), 'se': (1, 2), 'sw': (-1, 2), 'w':",
"in moves.values(): num += b[(y + m[1], x + m[0])]",
"value def black_neighbours(y, x, b): num = 0 for m",
"special cases) for y in range(2, h - 2): for",
"if tile: # black if n == 0 or n",
"np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d]",
"# black if n == 0 or n > 2:",
"(-2, 0), 'nw': (-1, -2), 'ne': (1, -2) } #",
"np from PIL import Image moves = { 'e': (2,",
"True for val in tiles.values())) # -- Part 2 --",
"0, 0), (255, 255, 255)] im = Image.new('RGB', (width, heigth))",
"for m in moves.values(): num += b[(y + m[1], x",
"tiles, move to center for key, value in tiles.items(): x,",
"> 2: board[(y, x)] = False else: # white if",
"white if n == 2: board[(y, x)] = True def",
"%d: %d' % (day, len(np.where(board == True)[0]))) ys, xs =",
"# Don't do outer edge (to avoid special cases) for",
"num = 0 for m in moves.values(): num += b[(y",
"num def game(): board_copy = np.copy(board) w, h = board.shape",
"} # Save (x, y): True/False in tiles. True =",
"re import numpy as np from PIL import Image moves",
"black_neighbours(y, x, b): num = 0 for m in moves.values():",
"import re import numpy as np from PIL import Image",
"= [(0, 0, 0), (255, 255, 255)] im = Image.new('RGB',",
"value in tiles.items(): x, y = key x += width",
"+= heigth // 2 board[y][x] = value def black_neighbours(y, x,",
"return num def game(): board_copy = np.copy(board) w, h =",
"num += b[(y + m[1], x + m[0])] return num",
"else: tiles[t] = True # Part 1 print('black:', sum(val ==",
"if n == 0 or n > 2: board[(y, x)]",
"// 2 y += heigth // 2 board[y][x] = value",
"board = np.zeros(width * heigth, dtype=np.int8) board = board.reshape(heigth, width)",
"heigth, dtype=np.int8) board = board.reshape(heigth, width) # Fill in tiles,",
"in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t = tuple(pos) if",
"- 2): tile = board_copy[(y, x)] n = black_neighbours(y, x,",
"% (day)) save_image(0) for day in range(1, 101): game() save_image(day)",
"board[(y, x)] = True def save_image(day): colours = [(0, 0,",
"for val in tiles.values())) # -- Part 2 -- #",
"h = board.shape # Don't do outer edge (to avoid",
"tile: # black if n == 0 or n >",
"to center for key, value in tiles.items(): x, y =",
"True def save_image(day): colours = [(0, 0, 0), (255, 255,",
"game() save_image(day) print('Day %d: %d' % (day, len(np.where(board == True)[0])))",
"import Image moves = { 'e': (2, 0), 'se': (1,",
"def black_neighbours(y, x, b): num = 0 for m in",
"to be width = 300 heigth = 300 board =",
"t = tuple(pos) if t in tiles: tiles[t] = not",
"#!/usr/bin/env python3 import sys import re import numpy as np",
"key, value in tiles.items(): x, y = key x +=",
"take a chance on how wide it needs to be",
"board = board.reshape(heigth, width) # Fill in tiles, move to",
"[(0, 0, 0), (255, 255, 255)] im = Image.new('RGB', (width,",
"move to center for key, value in tiles.items(): x, y",
"if n == 2: board[(y, x)] = True def save_image(day):",
"in range(1, 101): game() save_image(day) print('Day %d: %d' % (day,",
"== True)[0]))) ys, xs = np.where(board) print(min(ys), max(ys), min(xs), max(xs))",
"heigth = 300 board = np.zeros(width * heigth, dtype=np.int8) board",
"print('Day %d: %d' % (day, len(np.where(board == True)[0]))) ys, xs",
"300 board = np.zeros(width * heigth, dtype=np.int8) board = board.reshape(heigth,",
"in tiles.values())) # -- Part 2 -- # take a",
"= board.shape # Don't do outer edge (to avoid special",
"range(1, 101): game() save_image(day) print('Day %d: %d' % (day, len(np.where(board",
"w, h = board.shape # Don't do outer edge (to",
"Image moves = { 'e': (2, 0), 'se': (1, 2),",
"* heigth, dtype=np.int8) board = board.reshape(heigth, width) # Fill in",
"(-1, -2), 'ne': (1, -2) } # Save (x, y):",
"= white. tiles = {} for line in open(sys.argv[1]).read().splitlines(): pos",
"2), 'sw': (-1, 2), 'w': (-2, 0), 'nw': (-1, -2),",
"x + m[0])] return num def game(): board_copy = np.copy(board)",
"x)] n = black_neighbours(y, x, board_copy) if tile: # black",
"= True def save_image(day): colours = [(0, 0, 0), (255,",
"print('black:', sum(val == True for val in tiles.values())) # --",
"Fill in tiles, move to center for key, value in",
"n > 2: board[(y, x)] = False else: # white",
"width) # Fill in tiles, move to center for key,",
"{ 'e': (2, 0), 'se': (1, 2), 'sw': (-1, 2),",
"0), 'nw': (-1, -2), 'ne': (1, -2) } # Save",
"True/False in tiles. True = black, False = white. tiles",
"moves.values(): num += b[(y + m[1], x + m[0])] return",
"range(2, w - 2): tile = board_copy[(y, x)] n =",
"x, board_copy) if tile: # black if n == 0",
"re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t = tuple(pos) if t",
"key x += width // 2 y += heigth //",
"in range(width): c = colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' %",
"board_copy) if tile: # black if n == 0 or",
"d in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t = tuple(pos)",
"python3 import sys import re import numpy as np from",
"a chance on how wide it needs to be width",
"tiles[t] else: tiles[t] = True # Part 1 print('black:', sum(val",
"w - 2): tile = board_copy[(y, x)] n = black_neighbours(y,",
"+= b[(y + m[1], x + m[0])] return num def",
"x)] = True def save_image(day): colours = [(0, 0, 0),",
"0), (255, 255, 255)] im = Image.new('RGB', (width, heigth)) for",
"in range(heigth): for x in range(width): c = colours[board[y][x]] im.putpixel((x,",
"y = key x += width // 2 y +=",
"heigth // 2 board[y][x] = value def black_neighbours(y, x, b):",
"b): num = 0 for m in moves.values(): num +=",
"avoid special cases) for y in range(2, h - 2):",
"for y in range(heigth): for x in range(width): c =",
"black if n == 0 or n > 2: board[(y,",
"0)) for d in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t",
"(day, len(np.where(board == True)[0]))) ys, xs = np.where(board) print(min(ys), max(ys),",
"Save (x, y): True/False in tiles. True = black, False",
"0), 'se': (1, 2), 'sw': (-1, 2), 'w': (-2, 0),",
"center for key, value in tiles.items(): x, y = key",
"x, b): num = 0 for m in moves.values(): num",
"x += width // 2 y += heigth // 2",
"2: board[(y, x)] = True def save_image(day): colours = [(0,",
"edge (to avoid special cases) for y in range(2, h",
"+ m[0])] return num def game(): board_copy = np.copy(board) w,",
"on how wide it needs to be width = 300",
"as np from PIL import Image moves = { 'e':",
"2), 'w': (-2, 0), 'nw': (-1, -2), 'ne': (1, -2)",
"in tiles. True = black, False = white. tiles =",
"save_image(0) for day in range(1, 101): game() save_image(day) print('Day %d:",
"Part 2 -- # take a chance on how wide",
"= 300 heigth = 300 board = np.zeros(width * heigth,",
"y += heigth // 2 board[y][x] = value def black_neighbours(y,",
"board[(y, x)] = False else: # white if n ==",
"tiles[t] = not tiles[t] else: tiles[t] = True # Part",
"for day in range(1, 101): game() save_image(day) print('Day %d: %d'",
"needs to be width = 300 heigth = 300 board",
"== 2: board[(y, x)] = True def save_image(day): colours =",
"black, False = white. tiles = {} for line in",
"wide it needs to be width = 300 heigth =",
"for d in re.findall(r'e|se|sw|w|nw|ne', line): pos += moves[d] t =",
"n == 2: board[(y, x)] = True def save_image(day): colours",
"in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne',",
"2: board[(y, x)] = False else: # white if n",
"for x in range(width): c = colours[board[y][x]] im.putpixel((x, y), c)",
"% (day, len(np.where(board == True)[0]))) ys, xs = np.where(board) print(min(ys),",
"c) im.save('img%03d.png' % (day)) save_image(0) for day in range(1, 101):",
"False = white. tiles = {} for line in open(sys.argv[1]).read().splitlines():",
"width = 300 heigth = 300 board = np.zeros(width *",
"cases) for y in range(2, h - 2): for x",
"tiles.values())) # -- Part 2 -- # take a chance",
"b[(y + m[1], x + m[0])] return num def game():",
"255, 255)] im = Image.new('RGB', (width, heigth)) for y in",
"moves = { 'e': (2, 0), 'se': (1, 2), 'sw':",
"pos = np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne', line): pos",
"2 y += heigth // 2 board[y][x] = value def",
"in tiles.items(): x, y = key x += width //",
"(255, 255, 255)] im = Image.new('RGB', (width, heigth)) for y",
"(2, 0), 'se': (1, 2), 'sw': (-1, 2), 'w': (-2,",
"for x in range(2, w - 2): tile = board_copy[(y,",
"if t in tiles: tiles[t] = not tiles[t] else: tiles[t]",
"x in range(2, w - 2): tile = board_copy[(y, x)]",
"colours = [(0, 0, 0), (255, 255, 255)] im =",
"Image.new('RGB', (width, heigth)) for y in range(heigth): for x in",
"m[0])] return num def game(): board_copy = np.copy(board) w, h",
"def game(): board_copy = np.copy(board) w, h = board.shape #",
"= board_copy[(y, x)] n = black_neighbours(y, x, board_copy) if tile:",
"0 or n > 2: board[(y, x)] = False else:",
"= np.copy(board) w, h = board.shape # Don't do outer",
"x in range(width): c = colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png'",
"# Save (x, y): True/False in tiles. True = black,",
"1 print('black:', sum(val == True for val in tiles.values())) #",
"or n > 2: board[(y, x)] = False else: #",
"# take a chance on how wide it needs to",
"range(width): c = colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' % (day))",
"'w': (-2, 0), 'nw': (-1, -2), 'ne': (1, -2) }",
"save_image(day): colours = [(0, 0, 0), (255, 255, 255)] im",
"0 for m in moves.values(): num += b[(y + m[1],",
"n = black_neighbours(y, x, board_copy) if tile: # black if",
"(day)) save_image(0) for day in range(1, 101): game() save_image(day) print('Day",
"sum(val == True for val in tiles.values())) # -- Part",
"import sys import re import numpy as np from PIL",
"= Image.new('RGB', (width, heigth)) for y in range(heigth): for x",
"line in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for d in",
"board.reshape(heigth, width) # Fill in tiles, move to center for",
"val in tiles.values())) # -- Part 2 -- # take",
"'ne': (1, -2) } # Save (x, y): True/False in",
"tiles[t] = True # Part 1 print('black:', sum(val == True",
"-2) } # Save (x, y): True/False in tiles. True",
"# Part 1 print('black:', sum(val == True for val in",
"2 board[y][x] = value def black_neighbours(y, x, b): num =",
"+= moves[d] t = tuple(pos) if t in tiles: tiles[t]",
"= np.zeros(width * heigth, dtype=np.int8) board = board.reshape(heigth, width) #",
"in tiles, move to center for key, value in tiles.items():",
"save_image(day) print('Day %d: %d' % (day, len(np.where(board == True)[0]))) ys,",
"True # Part 1 print('black:', sum(val == True for val",
"Don't do outer edge (to avoid special cases) for y",
"== 0 or n > 2: board[(y, x)] = False",
"y in range(2, h - 2): for x in range(2,",
"PIL import Image moves = { 'e': (2, 0), 'se':",
"- 2): for x in range(2, w - 2): tile",
"True = black, False = white. tiles = {} for",
"np.zeros(width * heigth, dtype=np.int8) board = board.reshape(heigth, width) # Fill",
"outer edge (to avoid special cases) for y in range(2,",
"im.putpixel((x, y), c) im.save('img%03d.png' % (day)) save_image(0) for day in",
"else: # white if n == 2: board[(y, x)] =",
"-- Part 2 -- # take a chance on how",
"# white if n == 2: board[(y, x)] = True",
"(1, 2), 'sw': (-1, 2), 'w': (-2, 0), 'nw': (-1,",
"not tiles[t] else: tiles[t] = True # Part 1 print('black:',",
"== True for val in tiles.values())) # -- Part 2",
"game(): board_copy = np.copy(board) w, h = board.shape # Don't",
"= np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne', line): pos +=",
"-2), 'ne': (1, -2) } # Save (x, y): True/False",
"moves[d] t = tuple(pos) if t in tiles: tiles[t] =",
"Part 1 print('black:', sum(val == True for val in tiles.values()))",
"in range(2, h - 2): for x in range(2, w",
"= False else: # white if n == 2: board[(y,",
"for line in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for d",
"pos += moves[d] t = tuple(pos) if t in tiles:",
"2 -- # take a chance on how wide it",
"open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for d in re.findall(r'e|se|sw|w|nw|ne', line):",
"range(2, h - 2): for x in range(2, w -",
"# -- Part 2 -- # take a chance on",
"%d' % (day, len(np.where(board == True)[0]))) ys, xs = np.where(board)",
"{} for line in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0)) for",
"(width, heigth)) for y in range(heigth): for x in range(width):",
"y), c) im.save('img%03d.png' % (day)) save_image(0) for day in range(1,",
"= black, False = white. tiles = {} for line",
"= {} for line in open(sys.argv[1]).read().splitlines(): pos = np.array((0, 0))",
"= board.reshape(heigth, width) # Fill in tiles, move to center",
"# Fill in tiles, move to center for key, value",
"t in tiles: tiles[t] = not tiles[t] else: tiles[t] =",
"h - 2): for x in range(2, w - 2):",
"tile = board_copy[(y, x)] n = black_neighbours(y, x, board_copy) if",
"x)] = False else: # white if n == 2:",
"it needs to be width = 300 heigth = 300",
"255)] im = Image.new('RGB', (width, heigth)) for y in range(heigth):",
"c = colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' % (day)) save_image(0)",
"line): pos += moves[d] t = tuple(pos) if t in",
"m in moves.values(): num += b[(y + m[1], x +",
"tiles. True = black, False = white. tiles = {}",
"(to avoid special cases) for y in range(2, h -",
"tiles: tiles[t] = not tiles[t] else: tiles[t] = True #",
"chance on how wide it needs to be width =",
"False else: # white if n == 2: board[(y, x)]",
"colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' % (day)) save_image(0) for day",
"= value def black_neighbours(y, x, b): num = 0 for",
"board_copy[(y, x)] n = black_neighbours(y, x, board_copy) if tile: #",
"y): True/False in tiles. True = black, False = white.",
"im = Image.new('RGB', (width, heigth)) for y in range(heigth): for",
"tiles = {} for line in open(sys.argv[1]).read().splitlines(): pos = np.array((0,",
"+= width // 2 y += heigth // 2 board[y][x]",
"board[y][x] = value def black_neighbours(y, x, b): num = 0",
"len(np.where(board == True)[0]))) ys, xs = np.where(board) print(min(ys), max(ys), min(xs),",
"= key x += width // 2 y += heigth",
"// 2 board[y][x] = value def black_neighbours(y, x, b): num",
"(-1, 2), 'w': (-2, 0), 'nw': (-1, -2), 'ne': (1,",
"for key, value in tiles.items(): x, y = key x",
"2): tile = board_copy[(y, x)] n = black_neighbours(y, x, board_copy)",
"= 0 for m in moves.values(): num += b[(y +",
"= tuple(pos) if t in tiles: tiles[t] = not tiles[t]",
"def save_image(day): colours = [(0, 0, 0), (255, 255, 255)]",
"how wide it needs to be width = 300 heigth",
"heigth)) for y in range(heigth): for x in range(width): c",
"range(heigth): for x in range(width): c = colours[board[y][x]] im.putpixel((x, y),",
"im.save('img%03d.png' % (day)) save_image(0) for day in range(1, 101): game()",
"day in range(1, 101): game() save_image(day) print('Day %d: %d' %",
"2): for x in range(2, w - 2): tile =",
"numpy as np from PIL import Image moves = {",
"300 heigth = 300 board = np.zeros(width * heigth, dtype=np.int8)",
"black_neighbours(y, x, board_copy) if tile: # black if n ==",
"be width = 300 heigth = 300 board = np.zeros(width",
"n == 0 or n > 2: board[(y, x)] =",
"dtype=np.int8) board = board.reshape(heigth, width) # Fill in tiles, move",
"= 300 board = np.zeros(width * heigth, dtype=np.int8) board =",
"(1, -2) } # Save (x, y): True/False in tiles.",
"tiles.items(): x, y = key x += width // 2",
"board.shape # Don't do outer edge (to avoid special cases)",
"= True # Part 1 print('black:', sum(val == True for",
"width // 2 y += heigth // 2 board[y][x] =",
"import numpy as np from PIL import Image moves =",
"= { 'e': (2, 0), 'se': (1, 2), 'sw': (-1,",
"+ m[1], x + m[0])] return num def game(): board_copy",
"m[1], x + m[0])] return num def game(): board_copy =",
"'nw': (-1, -2), 'ne': (1, -2) } # Save (x,",
"= not tiles[t] else: tiles[t] = True # Part 1",
"np.copy(board) w, h = board.shape # Don't do outer edge",
"for y in range(2, h - 2): for x in",
"board_copy = np.copy(board) w, h = board.shape # Don't do",
"in range(2, w - 2): tile = board_copy[(y, x)] n",
"= black_neighbours(y, x, board_copy) if tile: # black if n",
"101): game() save_image(day) print('Day %d: %d' % (day, len(np.where(board ==",
"'se': (1, 2), 'sw': (-1, 2), 'w': (-2, 0), 'nw':",
"y in range(heigth): for x in range(width): c = colours[board[y][x]]",
"x, y = key x += width // 2 y",
"= colours[board[y][x]] im.putpixel((x, y), c) im.save('img%03d.png' % (day)) save_image(0) for",
"tuple(pos) if t in tiles: tiles[t] = not tiles[t] else:",
"-- # take a chance on how wide it needs"
] |
[
"and process.stackframes and process.types): del processes[pid] return processes def ResolveMemoryDumpFields(entries,",
"+ 'b') return open(file_path, mode + 't') def FindMemoryDumps(filename): processes",
"root['size'] = 0 root['children'] = {} root['count_by_type'] = {} for",
"return (name,) + tail def ResolveType(type_id, types): return types[type_id] for",
"0 root['size'] = 0 root['children'] = {} root['count_by_type'] = {}",
"start_entries = GetEntries(heap, start_process) end_entries = GetEntries(heap, end_process) graph =",
"in end_process.allocators: start_entries = GetEntries(heap, start_process) end_entries = GetEntries(heap, end_process)",
"import argparse import gzip import json import os import shutil",
"process.name = event['args']['name'] if event['name'] == 'process_labels' and 'labels' in",
"'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def __init__(self): self.pid",
"> size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' % root['size']) output.write(' \\\"count\\\": \\\"%s\\\",'",
"'parent' in node: node_v1['parent'] = node['parent'] process.stackframes[node['id']] = node_v1 for",
"graph.pid = pid graph.name = name graph.labels = labels graph.heap",
"filter_by_name, filter_by_labels, match_by_labels): # Retrieve the processes and the associated",
"end_process.pid name = end_process.name if end_process.name else '' labels =",
"-1 (18446744073709551615L) when not stackframe are # available. if entry.stackframe",
"new_stackframe['name'] = s['name'] if 'parent' in s: new_stackframe['parent'] = int(s['parent'])",
"'GPU'] or start_process.labels == end_process.labels)): matching_start_process = start_process if matching_start_process:",
"os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR,",
"fields by looking into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries",
"graph.name, 'labels': graph.labels, 'objects': graph.root, 'potential leaks': graph.leak_stackframes, 'objects leaked':",
"six.iteritems(start_processes): if (start_process.name == end_process.name and (start_process.name in ['Browser', 'GPU']",
"if end_process.labels else '' print('Process[%d] %s: %s' % (pid, name,",
"not start_processes: # Only keep end-processes. for _, end_process in",
"= 'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename) with",
"the LICENSE file. from __future__ import absolute_import from __future__ import",
"= processes[pid] # Retrieve process informations. if event['ph'] == 'M':",
"process.stackframes = {} for stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe =",
"& set(start_processes.keys()) for pid in relevant_pids: start_process = start_processes[pid] end_process",
"relevant processes to be processed. processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name,",
"size if typename not in root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename]",
"class Entry(object): def __init__(self): self.count = None self.size = None",
"start_process = start_processes[pid] end_process = end_processes[pid] processes.append((start_process, end_process)) return processes",
"end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root",
"if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size, entry.type, root) for",
"event['args']: process.name = event['args']['name'] if event['name'] == 'process_labels' and 'labels'",
"start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size, entry.type, root)",
"a potential memory leak') parser.add_argument( '--filter-by-name', type=str, help='Only keep processes",
"end_process.labels)): matching_start_process = start_process if matching_start_process: processes.append((matching_start_process, end_process)) else: #",
"total_count_for_type = 0 for child in six.itervalues(root['children']): if typename in",
"count, size, typename, root): if not stack: root['count'] += count",
"root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename] += count else: top =",
"= event['args']['dumps']['heaps'] # Check for a memory dump V2. #",
"graph_dumps: # Dump the remaining allocated objects tree. filename =",
"are paired based on their PID. relevant_pids = set(end_processes.keys()) &",
"type=int, default=0, help='Objects threshold for being a potential memory leak')",
"leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects, } for graph in graph_dumps],",
"found.' % (heap, len(leaks))) graph.leaks = leaks graph.leak_stackframes = len(leaks)",
"'type' not in raw_entry or not raw_entry['bt']: continue entry =",
"allocations') parser.add_argument( '--threshold', type=int, default=0, help='Objects threshold for being a",
"Get the first memory dump. if not process.allocators: dump =",
"return remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels): # Retrieve",
"# https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in raw_entry or not raw_entry['bt']:",
"total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for child in six.itervalues(root['children']):",
"= list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type, raw_stackframe)",
"pid = end_process.pid name = end_process.name if end_process.name else ''",
"memory dump V1. if u'heaps' in event['args']['dumps']: # Get the",
"leaks, threshold, size_threshold): for frame in root['children']: FindLeaks(root['children'][frame], [frame] +",
"__future__ import print_function import argparse import gzip import json import",
"\"\"\" Returns all entries in a heap, after filtering out",
"paired based on name/labels. for _, end_process in six.iteritems(end_processes): matching_start_process",
"default=0, help='Size threshold for being a potential memory leak') parser.add_argument(",
"# Find relevant processes to be processed. processes = FindRelevantProcesses(start_trace,",
"pid graph.name = name graph.labels = labels graph.heap = heap",
"(start_process.name in ['Browser', 'GPU'] or start_process.labels == end_process.labels)): matching_start_process =",
"return gzip.open(file_path, mode + 'b') return open(file_path, mode + 't')",
"GetEntries(heap, start_process) end_entries = GetEntries(heap, end_process) graph = GraphDump() graph.pid",
"'w') as output: DumpTree(graph.root, '.', output, threshold, size_threshold) graph.root =",
"None else: start_trace = options.trace[0] end_trace = options.trace[1] if not",
"if typename in child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type",
"child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for child in",
"in graph_dumps], output) def WriteHTML(): # Copy the HTML page.",
"= pid graph.name = name graph.labels = labels graph.heap =",
"= 0 new_node['children'] = {} new_node['count_by_type'] = {} root['children'][top] =",
"not in stackframes: entry.stackframe = [] else: entry.stackframe = ResolveStackTrace(entry.stackframe,",
"def ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id]",
"stack, leaks, threshold, size_threshold): for frame in root['children']: FindLeaks(root['children'][frame], [frame]",
"root['count_by_type'][typename] += count else: top = stack[-1] tail = stack[:-1]",
"= int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif process.version == 2:",
"(name,) + tail def ResolveType(type_id, types): return types[type_id] for entry",
"ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type, types) def IncrementHeapEntry(stack, count, size,",
"in raw_entry or not raw_entry['bt']: continue entry = Entry() entry.count",
"'index.html') shutil.copyfile(source, destination) # Copy the D3 library file. source",
"int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif process.version == 2: raw_entries",
"tail = ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n', '') return",
"root['children']: new_node = {} new_node['count'] = 0 new_node['size'] = 0",
"CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks, threshold, size_threshold): for frame in",
"as f: data = json.loads(f.read().decode('utf-8')) for event in data['traceEvents']: pid",
"processes def BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build graph for a",
"event['args']['dumps']['level_of_detail'] == 'detailed'): continue # Check for a memory dump",
"typename not in root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename] += count",
"graph_dumps = [] for (start_process, end_process) in processes: pid =",
"is dumping information incrementally. Update # the cumulated indexes. maps",
"def BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build graph for a sequence",
"the relevant fields. \"\"\" if not process: return [] entries",
"Memory dump format V2 is dumping information incrementally. Update #",
"None class GraphDump(object): def __init__(self): self.pid = None self.name =",
"processes.items(): if not (process.allocators and process.stackframes and process.types): del processes[pid]",
"entry = Entry() entry.count = raw_count entry.size = raw_size entry.type",
"def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return gzip.open(file_path, mode + 'b')",
"Find relevant processes to be processed. processes = FindRelevantProcesses(start_trace, end_trace,",
"root['count_by_type'][typename] = 0 root['count_by_type'][typename] += count else: top = stack[-1]",
"processes = [] if not start_processes: # Only keep end-processes.",
"= end_process.labels if end_process.labels else '' print('Process[%d] %s: %s' %",
"with OpenTraceFile(filename, 'r') as f: data = json.loads(f.read().decode('utf-8')) for event",
"WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML() if __name__ == '__main__': Main()",
"threshold, size_threshold): for frame in root['children']: FindLeaks(root['children'][frame], [frame] + stack,",
"= raw_type entry.stackframe = raw_stackframe entries.append(entry) # Resolve fields by",
"end_process)) else: # Processes are paired based on their PID.",
"process.allocators = event['args']['dumps']['heaps'] # Check for a memory dump V2.",
"entries.append(entry) elif process.version == 2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'],",
"as output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph",
"root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack}) def DumpTree(root, frame,",
"for pid, process in processes.items(): if not (process.allocators and process.stackframes",
"in processes: pid = end_process.pid name = end_process.name if end_process.name",
"event. if not ((event['name'] == 'periodic_interval' or event['name'] == 'explicitly_triggered')",
"to extract the relevant fields. \"\"\" if not process: return",
"are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in raw_entry",
"= 0 self.leak_objects = 0 def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'):",
"#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights",
"types[type_id] for entry in entries: # Stackframe may be -1",
"for child in six.itervalues(root['children']): if typename in child['count_by_type']: total_count_for_type +=",
"parser.add_argument( '--size-threshold', type=int, default=0, help='Size threshold for being a potential",
"'name': graph.name, 'labels': graph.labels, 'objects': graph.root, 'potential leaks': graph.leak_stackframes, 'objects",
"in processes.items(): if not (process.allocators and process.stackframes and process.types): del",
"= {} with OpenTraceFile(filename, 'r') as f: data = json.loads(f.read().decode('utf-8'))",
"options.threshold == 0 and options.size_threshold == 0: options.threshold = 1000",
"process.labels)): continue remaining_processes[pid] = process return remaining_processes def FindRelevantProcesses(start_trace, end_trace,",
"% root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' % root['count']) output.write(' \\\"children\\\": [')",
"= stackframes[stack_id] tail = () if 'parent' in stackframe: tail",
"but not in start_process. \"\"\" graph_dumps = [] for (start_process,",
"if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML() if",
"python # Copyright 2017 The Chromium Authors. All rights reserved.",
"based on stackframe allocations') parser.add_argument( '--threshold', type=int, default=0, help='Objects threshold",
"processes[pid].pid = pid process = processes[pid] # Retrieve process informations.",
"root['size'] += size if typename not in root['count_by_type']: root['count_by_type'][typename] =",
"import absolute_import from __future__ import print_function import argparse import gzip",
"'d3.min.js') shutil.copyfile(source, destination) def Main(): parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph',",
"six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks, threshold, size_threshold): for frame",
"Only keep end-processes. for _, end_process in six.iteritems(end_processes): processes.append((None, end_process))",
"output.write('}') def GetEntries(heap, process): \"\"\" Returns all entries in a",
"heap in end_process.allocators: start_entries = GetEntries(heap, start_process) end_entries = GetEntries(heap,",
"PID. relevant_pids = set(end_processes.keys()) & set(start_processes.keys()) for pid in relevant_pids:",
"event['name'] == 'typeNames': process.types = {} for type_id, t in",
"> size_threshold: leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack})",
"GetEntries(heap, end_process) graph = GraphDump() graph.pid = pid graph.name =",
"if typename not in root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename] +=",
"IncrementHeapEntry(tail, count, size, typename, root['children'][top]) def CanonicalHeapEntries(root): total_count = 0",
"Entry() entry.count = int(raw_entry['count'], 16) entry.size = int(raw_entry['size'], 16) entry.type",
"child_frame, child in root['children'].items(): if is_first: is_first = False else:",
"file. from __future__ import absolute_import from __future__ import print_function import",
"process in six.iteritems(processes): if filter_by_name and process.name != filter_by_name: continue",
"= int(raw_entry['count'], 16) entry.size = int(raw_entry['size'], 16) entry.type = int(raw_entry['type'])",
"not in raw_entry or not raw_entry['bt']: continue entry = Entry()",
"# Resolve fields by looking into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types)",
"keep end-processes. for _, end_process in six.iteritems(end_processes): processes.append((None, end_process)) elif",
"'labels' in event['args']: process.labels = event['args']['labels'] if event['name'] == 'typeNames':",
"if start_trace: start_processes = FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels)",
"open(output_filename, 'w') as output: DumpTree(graph.root, '.', output, threshold, size_threshold) graph.root",
"= GetEntries(heap, start_process) end_entries = GetEntries(heap, end_process) graph = GraphDump()",
"True for child_frame, child in root['children'].items(): if is_first: is_first =",
"== 0 and options.size_threshold == 0: options.threshold = 1000 if",
"this source code is governed by a BSD-style license that",
"processes[pid] = Process() processes[pid].pid = pid process = processes[pid] #",
"size_threshold) if root['count'] > threshold and root['size'] > size_threshold: leaks.append({'count':",
"root # Find leaks leaks = [] FindLeaks(root, [], leaks,",
"None if start_trace: start_processes = FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name,",
"tail = stack[:-1] if top not in root['children']: new_node =",
"= node['parent'] process.stackframes[node['id']] = node_v1 for t in maps['types']: process.types[t['id']]",
"\\\"children\\\": [') is_first = True for child_frame, child in root['children'].items():",
"if entry.stackframe not in stackframes: entry.stackframe = [] else: entry.stackframe",
"mode + 't') def FindMemoryDumps(filename): processes = {} with OpenTraceFile(filename,",
"self.leaks = '' self.leak_stackframes = 0 self.leak_objects = 0 def",
"def FindMemoryDumps(filename): processes = {} with OpenTraceFile(filename, 'r') as f:",
"filename) if graph.root: with open(output_filename, 'w') as output: DumpTree(graph.root, '.',",
"Processes are paired based on name/labels. for _, end_process in",
"leaks.sort(reverse=True, key=lambda k: k['size']) if leaks: print(' %s: %d potential",
"self.leak_stackframes = 0 self.leak_objects = 0 def OpenTraceFile(file_path, mode): if",
"WriteHTML(): # Copy the HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html')",
"{'pid': graph.pid, 'heap': graph.heap, 'name': graph.name, 'labels': graph.labels, 'objects': graph.root,",
"pid process = processes[pid] # Retrieve process informations. if event['ph']",
"0 for child in six.itervalues(root['children']): if typename in child['count_by_type']: total_count_for_type",
"'' labels = end_process.labels if end_process.labels else '' print('Process[%d] %s:",
"entry.type, root) CanonicalHeapEntries(root) graph.root = root # Find leaks leaks",
"Retrieve the processes and the associated memory dump. end_processes =",
"-= total_count root['size'] -= total_size for typename in root['count_by_type']: total_count_for_type",
"graph.root = filename def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with",
"cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']: process.strings[string['id']]",
"to be processed') options = parser.parse_args() if options.threshold == 0",
"the HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR,",
"'--filter-by-labels', type=str, help='Only keep processes with matching labels') parser.add_argument( '--match-by-labels',",
"= FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold,",
"for t in maps['types']: process.types[t['id']] = process.strings[t['name_sid']] # Get the",
"leak in leaks: graph.leak_objects += leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps):",
"entry.count = int(raw_entry['count'], 16) entry.size = int(raw_entry['size'], 16) entry.type =",
"for string in maps['strings']: process.strings[string['id']] = string['string'] for node in",
"threshold, size_threshold) graph.root = filename def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR,",
"+= size if typename not in root['count_by_type']: root['count_by_type'][typename] = 0",
"graph.root, 'potential leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects, } for graph",
"entry.count, - entry.size, entry.type, root) for entry in end_entries: if",
"end_trace. Otherwise, counts objects present in end_trace, but not in",
"on stackframe allocations') parser.add_argument( '--threshold', type=int, default=0, help='Objects threshold for",
"process.version == 2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for",
"for entry in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, -",
"+= count root['size'] += size if typename not in root['count_by_type']:",
"of this source code is governed by a BSD-style license",
"for raw_entry in process.allocators[heap]['entries']: # Cumulative sizes and types are",
"root['children'][top]) def CanonicalHeapEntries(root): total_count = 0 total_size = 0 for",
"end_process in six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels: # Processes are",
"= [] else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type,",
"= os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js') destination",
"graph based on stackframe allocations') parser.add_argument( '--threshold', type=int, default=0, help='Objects",
"reserved. # Use of this source code is governed by",
"None self.labels = None self.heap = None self.root = ''",
"WritePotentialLeaks(graph_dumps) if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold)",
"raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type,",
"0 new_node['children'] = {} new_node['count_by_type'] = {} root['children'][top] = new_node",
"'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack}) def DumpTree(root, frame, output,",
"options.threshold = 1000 if len(options.trace) == 1: end_trace = options.trace[0]",
"if u'heaps' in event['args']['dumps']: # Get the first memory dump.",
"= json.loads(f.read().decode('utf-8')) for event in data['traceEvents']: pid = event['pid'] if",
"in entries: # Stackframe may be -1 (18446744073709551615L) when not",
"options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML()",
"(pid, name, labels)) for heap in end_process.allocators: start_entries = GetEntries(heap,",
"root['children'] = {} root['count_by_type'] = {} for entry in start_entries:",
"in event['args']: process.labels = event['args']['labels'] if event['name'] == 'typeNames': process.types",
"with open(output_filename, 'w') as output: json.dump([ {'pid': graph.pid, 'heap': graph.heap,",
"Check for a memory dump V2. # See format: [chromium]",
"extract the relevant fields. \"\"\" if not process: return []",
"parser.parse_args() if options.threshold == 0 and options.size_threshold == 0: options.threshold",
"os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) # Copy the D3 library file.",
"= None self.labels = None self.types = {} self.strings =",
"matching labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match processes between runs by",
"== 1: end_trace = options.trace[0] start_trace = None else: start_trace",
"frame) if root['count'] > threshold and root['count'] > size_threshold: output.write('",
"for (start_process, end_process) in processes: pid = end_process.pid name =",
"{} for entry in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count,",
"= event['args']['name'] if event['name'] == 'process_labels' and 'labels' in event['args']:",
"= start_processes[pid] end_process = end_processes[pid] processes.append((start_process, end_process)) return processes def",
"in event['args']['dumps']: # Get the first memory dump. if not",
"if 'parent' in node: node_v1['parent'] = node['parent'] process.stackframes[node['id']] = node_v1",
"0: options.threshold = 1000 if len(options.trace) == 1: end_trace =",
"filter_by_labels) # Build a sequence of pair of processes to",
"stack: root['count'] += count root['size'] += size if typename not",
"self.root = '' self.leaks = '' self.leak_stackframes = 0 self.leak_objects",
"= {} new_node['count_by_type'] = {} root['children'][top] = new_node IncrementHeapEntry(tail, count,",
"%d potential leaks found.' % (heap, len(leaks))) graph.leaks = leaks",
"class GraphDump(object): def __init__(self): self.pid = None self.name = None",
"= process return remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels):",
"name = end_process.name if end_process.name else '' labels = end_process.labels",
"size_threshold): \"\"\" Build graph for a sequence of pair of",
"child['size'] root['count'] -= total_count root['size'] -= total_size for typename in",
"# Only keep end-processes. for _, end_process in six.iteritems(end_processes): processes.append((None,",
"pair of processes. If start_process is None, counts objects in",
"new_node['count'] = 0 new_node['size'] = 0 new_node['children'] = {} new_node['count_by_type']",
"= end_process.pid name = end_process.name if end_process.name else '' labels",
"event['args']['dumps']: # Memory dump format V2 is dumping information incrementally.",
"help='Trace files to be processed') options = parser.parse_args() if options.threshold",
"filter_by_name, filter_by_labels) start_processes = None if start_trace: start_processes = FindMemoryDumps(start_trace)",
"None self.stackframe = None class GraphDump(object): def __init__(self): self.pid =",
"__init__(self): self.pid = None self.name = None self.labels = None",
"memory dumps. root = {} root['count'] = 0 root['size'] =",
"six.iteritems(processes): if filter_by_name and process.name != filter_by_name: continue if (filter_by_labels",
"and process.name != filter_by_name: continue if (filter_by_labels and (not process.labels",
"for a sequence of pair of processes. If start_process is",
"= None self.types = {} self.strings = {} self.stackframes =",
"being a potential memory leak') parser.add_argument( '--filter-by-name', type=str, help='Only keep",
"= options.trace[0] start_trace = None else: start_trace = options.trace[0] end_trace",
"entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif process.version == 2: raw_entries =",
"del processes[pid] return processes def ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id,",
"informations. if event['ph'] == 'M': if event['name'] == 'process_name' and",
"Find leaks leaks = [] FindLeaks(root, [], leaks, threshold, size_threshold)",
"in six.iteritems(processes): if filter_by_name and process.name != filter_by_name: continue if",
"as output: DumpTree(graph.root, '.', output, threshold, size_threshold) graph.root = filename",
"def IncrementHeapEntry(stack, count, size, typename, root): if not stack: root['count']",
"destination) def Main(): parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output",
"- entry.size, entry.type, root) for entry in end_entries: if entry.type:",
"if len(options.trace) == 1: end_trace = options.trace[0] start_trace = None",
"if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps)",
"in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root)",
"if file_path.endswith('.gz'): return gzip.open(file_path, mode + 'b') return open(file_path, mode",
"processes def ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id, stackframes): stackframe =",
"stack[:-1] if top not in root['children']: new_node = {} new_node['count']",
"sequence of pair of processes to be compared. processes =",
"processes.append((start_process, end_process)) return processes def BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build",
"= 'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if",
"the first memory dump. if not process.allocators: process.version = 1",
"_OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def",
"root['size'] -= total_size for typename in root['count_by_type']: total_count_for_type = 0",
"'trace', nargs='+', help='Trace files to be processed') options = parser.parse_args()",
"int(raw_entry['size'], 16) entry.type = int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif",
"== 2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count,",
"objects in end_trace. Otherwise, counts objects present in end_trace, but",
"filter_by_labels): remaining_processes = {} for pid, process in six.iteritems(processes): if",
"dump V2. # See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in",
"'parent' in stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r',",
"from __future__ import absolute_import from __future__ import print_function import argparse",
"indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']: process.strings[string['id']] =",
"destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) # Copy the D3",
"\\\"count\\\": \\\"%s\\\",' % root['count']) output.write(' \\\"children\\\": [') is_first = True",
"stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,) + tail def ResolveType(type_id, types):",
"stackframes: entry.stackframe = [] else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type",
"processes. If start_process is None, counts objects in end_trace. Otherwise,",
"process.allocators = dump['heaps_v2']['allocators'] # Remove processes with incomplete memory dump.",
"else '' print('Process[%d] %s: %s' % (pid, name, labels)) for",
"if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root =",
"int(raw_entry['bt']) entries.append(entry) elif process.version == 2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'],",
"string['string'] for node in maps['nodes']: node_v1 = {} node_v1['name'] =",
"= GetEntries(heap, end_process) graph = GraphDump() graph.pid = pid graph.name",
"not stack: root['count'] += count root['size'] += size if typename",
"memory leak') parser.add_argument( '--size-threshold', type=int, default=0, help='Size threshold for being",
"= BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR):",
"= False else: output.write(',') DumpTree(child, child_frame, output, threshold, size_threshold) output.write(']')",
"%s' % (pid, name, labels)) for heap in end_process.allocators: start_entries",
"leaked': graph.leak_objects, } for graph in graph_dumps], output) def WriteHTML():",
"process.strings[string['id']] = string['string'] for node in maps['nodes']: node_v1 = {}",
"raw_entry in process.allocators[heap]['entries']: # Cumulative sizes and types are skipped.",
"processed') options = parser.parse_args() if options.threshold == 0 and options.size_threshold",
"maps = event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']: process.strings[string['id']] = string['string']",
"not ((event['name'] == 'periodic_interval' or event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail']",
"= node_v1 for t in maps['types']: process.types[t['id']] = process.strings[t['name_sid']] #",
"types) def IncrementHeapEntry(stack, count, size, typename, root): if not stack:",
"looking into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries def FilterProcesses(processes,",
"= FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build a",
"stackframe are # available. if entry.stackframe not in stackframes: entry.stackframe",
"{} for stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name']",
"available. if entry.stackframe not in stackframes: entry.stackframe = [] else:",
"root['count'] += count root['size'] += size if typename not in",
"output: json.dump([ {'pid': graph.pid, 'heap': graph.heap, 'name': graph.name, 'labels': graph.labels,",
"if not (process.allocators and process.stackframes and process.types): del processes[pid] return",
"class Process(object): def __init__(self): self.pid = None self.name = None",
"key=lambda k: k['size']) if leaks: print(' %s: %d potential leaks",
"pid = event['pid'] if pid not in processes: processes[pid] =",
"process return remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels): #",
"= GraphDump() graph.pid = pid graph.name = name graph.labels =",
"= {} for entry in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, -",
"= None self.root = '' self.leaks = '' self.leak_stackframes =",
"%s: %s' % (pid, name, labels)) for heap in end_process.allocators:",
"matching_start_process: processes.append((matching_start_process, end_process)) else: # Processes are paired based on",
"present in end_trace, but not in start_process. \"\"\" graph_dumps =",
"gzip import json import os import shutil import six from",
"'name' in event['args']: process.name = event['args']['name'] if event['name'] == 'process_labels'",
"a sequence of pair of processes to be compared. processes",
"diffing start and end memory dumps. root = {} root['count']",
"remaining_processes[pid] = process return remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels,",
"= new_node IncrementHeapEntry(tail, count, size, typename, root['children'][top]) def CanonicalHeapEntries(root): total_count",
"if top not in root['children']: new_node = {} new_node['count'] =",
"= {} for pid, process in six.iteritems(processes): if filter_by_name and",
"stack, leaks, threshold, size_threshold) if root['count'] > threshold and root['size']",
"{} self.stackframes = {} self.allocators = None self.version = None",
"with matching labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match processes between runs",
"heap graph_dumps.append(graph) # Do the math: diffing start and end",
"first memory dump. if not process.allocators: dump = event['args']['dumps'] process.version",
"node_v1 = {} node_v1['name'] = process.strings[node['name_sid']] if 'parent' in node:",
"def DumpTree(root, frame, output, threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' %",
"import print_function import argparse import gzip import json import os",
"def __init__(self): self.count = None self.size = None self.type =",
"in root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename] += count else: top",
"ResolveType(entry.type, types) def IncrementHeapEntry(stack, count, size, typename, root): if not",
"typename in root['count_by_type']: total_count_for_type = 0 for child in six.itervalues(root['children']):",
"for graph in graph_dumps], output) def WriteHTML(): # Copy the",
"end_process = end_processes[pid] processes.append((start_process, end_process)) return processes def BuildGraphDumps(processes, threshold,",
"IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root = root #",
"= {} node_v1['name'] = process.strings[node['name_sid']] if 'parent' in node: node_v1['parent']",
"'heap': graph.heap, 'name': graph.name, 'labels': graph.labels, 'objects': graph.root, 'potential leaks':",
"[chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']: # Memory dump format",
"parser.add_argument( '--filter-by-labels', type=str, help='Only keep processes with matching labels') parser.add_argument(",
"destination) # Copy the D3 library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)),",
"V2 is dumping information incrementally. Update # the cumulated indexes.",
"with open(output_filename, 'w') as output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold,",
"> threshold and root['size'] > size_threshold: leaks.append({'count': root['count'], 'size': root['size'],",
"in six.iteritems(start_processes): if (start_process.name == end_process.name and (start_process.name in ['Browser',",
"in event['args']: process.name = event['args']['name'] if event['name'] == 'process_labels' and",
"leaks found.' % (heap, len(leaks))) graph.leaks = leaks graph.leak_stackframes =",
"out unknown entries, and doing some post processing to extract",
"entry.size = raw_size entry.type = raw_type entry.stackframe = raw_stackframe entries.append(entry)",
"16) entry.size = int(raw_entry['size'], 16) entry.type = int(raw_entry['type']) entry.stackframe =",
"for child in six.itervalues(root['children']): total_count += child['count'] total_size += child['size']",
"sizes and types are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type'",
"total_size += child['size'] root['count'] -= total_count root['size'] -= total_size for",
"{} root['children'][top] = new_node IncrementHeapEntry(tail, count, size, typename, root['children'][top]) def",
"for a memory dump V2. # See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h",
"is governed by a BSD-style license that can be #",
"!= filter_by_name: continue if (filter_by_labels and (not process.labels or filter_by_labels",
"= new_stackframe # Look for a detailed memory dump event.",
"action='store_true', help='Match processes between runs by labels') parser.add_argument( 'trace', nargs='+',",
"Update # the cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for string",
"raw_stackframe) in raw_entries: entry = Entry() entry.count = raw_count entry.size",
"in the LICENSE file. from __future__ import absolute_import from __future__",
"not process: return [] entries = [] if process.version ==",
"self.name = None self.labels = None self.types = {} self.strings",
"s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe # Look for",
"ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes",
"f: data = json.loads(f.read().decode('utf-8')) for event in data['traceEvents']: pid =",
"files to be processed') options = parser.parse_args() if options.threshold ==",
"[frame] + stack, leaks, threshold, size_threshold) if root['count'] > threshold",
"% (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w')",
"the associated memory dump. end_processes = FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes,",
"process: return [] entries = [] if process.version == 1:",
"options = parser.parse_args() if options.threshold == 0 and options.size_threshold ==",
"= start_process if matching_start_process: processes.append((matching_start_process, end_process)) else: # Processes are",
"event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']: process.strings[string['id']] = string['string'] for node",
"process.types[t['id']] = process.strings[t['name_sid']] # Get the first memory dump. if",
"Remove processes with incomplete memory dump. for pid, process in",
"process.allocators: process.version = 1 process.allocators = event['args']['dumps']['heaps'] # Check for",
"Use of this source code is governed by a BSD-style",
"count else: top = stack[-1] tail = stack[:-1] if top",
"help='Match processes between runs by labels') parser.add_argument( 'trace', nargs='+', help='Trace",
"processes[pid] # Retrieve process informations. if event['ph'] == 'M': if",
"output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph in",
"entries in a heap, after filtering out unknown entries, and",
"root['count']) output.write(' \\\"children\\\": [') is_first = True for child_frame, child",
"{} node_v1['name'] = process.strings[node['name_sid']] if 'parent' in node: node_v1['parent'] =",
"= 0 root['count_by_type'][typename] += count else: top = stack[-1] tail",
"types): return types[type_id] for entry in entries: # Stackframe may",
"FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes = None if start_trace: start_processes =",
"name, labels)) for heap in end_process.allocators: start_entries = GetEntries(heap, start_process)",
"= '' self.leaks = '' self.leak_stackframes = 0 self.leak_objects =",
"(raw_count, raw_size, raw_type, raw_stackframe) in raw_entries: entry = Entry() entry.count",
"= set(end_processes.keys()) & set(start_processes.keys()) for pid in relevant_pids: start_process =",
"raw_count entry.size = raw_size entry.type = raw_type entry.stackframe = raw_stackframe",
"in six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels: # Processes are paired",
"else: # Processes are paired based on their PID. relevant_pids",
"unknown entries, and doing some post processing to extract the",
"rights reserved. # Use of this source code is governed",
"start_process. \"\"\" graph_dumps = [] for (start_process, end_process) in processes:",
"be processed') options = parser.parse_args() if options.threshold == 0 and",
"[] for (start_process, end_process) in processes: pid = end_process.pid name",
"in six.itervalues(root['children']): total_count += child['count'] total_size += child['size'] root['count'] -=",
"# Copy the HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination",
"= os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w') as output: json.dump(graph.leaks, output)",
"processes.append((None, end_process)) elif match_by_labels: # Processes are paired based on",
"end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes = None if start_trace:",
"library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party',",
"graph_dumps], output) def WriteHTML(): # Copy the HTML page. source",
"maps['nodes']: node_v1 = {} node_v1['name'] = process.strings[node['name_sid']] if 'parent' in",
"__future__ import absolute_import from __future__ import print_function import argparse import",
"event['args']['labels'] if event['name'] == 'typeNames': process.types = {} for type_id,",
"process): \"\"\" Returns all entries in a heap, after filtering",
"end_process)) elif match_by_labels: # Processes are paired based on name/labels.",
"D3 library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing',",
"sequence of pair of processes. If start_process is None, counts",
"LICENSE file. from __future__ import absolute_import from __future__ import print_function",
"# Look for a detailed memory dump event. if not",
"output.write(' \\\"size\\\": \\\"%s\\\",' % root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' % root['count'])",
"options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if",
"processes and the associated memory dump. end_processes = FindMemoryDumps(end_trace) end_processes",
"graph_dumps def WritePotentialLeaks(graph_dumps): for graph in graph_dumps: if graph.leaks: filename",
"size, typename, root): if not stack: root['count'] += count root['size']",
"source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js')",
"= int(raw_entry['bt']) entries.append(entry) elif process.version == 2: raw_entries = list(zip(process.allocators[heap]['counts'],",
"Do the math: diffing start and end memory dumps. root",
"new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe # Look for a",
"end_process)) return processes def BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build graph",
"= ResolveType(entry.type, types) def IncrementHeapEntry(stack, count, size, typename, root): if",
"= True for child_frame, child in root['children'].items(): if is_first: is_first",
"license that can be # found in the LICENSE file.",
"self.name = None self.labels = None self.heap = None self.root",
"= 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def __init__(self):",
"Process(object): def __init__(self): self.pid = None self.name = None self.labels",
"Entry() entry.count = raw_count entry.size = raw_size entry.type = raw_type",
"# available. if entry.stackframe not in stackframes: entry.stackframe = []",
"# Use of this source code is governed by a",
"in root['children']: FindLeaks(root['children'][frame], [frame] + stack, leaks, threshold, size_threshold) if",
"output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with open(output_filename, 'w') as",
"Cumulative sizes and types are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if",
"parser.add_argument( 'trace', nargs='+', help='Trace files to be processed') options =",
"or not raw_entry['bt']: continue entry = Entry() entry.count = int(raw_entry['count'],",
"in processes: processes[pid] = Process() processes[pid].pid = pid process =",
"in start_process. \"\"\" graph_dumps = [] for (start_process, end_process) in",
"with incomplete memory dump. for pid, process in processes.items(): if",
"end_process.name if end_process.name else '' labels = end_process.labels if end_process.labels",
"leaks, threshold, size_threshold) if root['count'] > threshold and root['size'] >",
"= FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes = None if start_trace: start_processes",
"Processes are paired based on their PID. relevant_pids = set(end_processes.keys())",
"if event['name'] == 'stackFrames': process.stackframes = {} for stack_id, s",
"0 and options.size_threshold == 0: options.threshold = 1000 if len(options.trace)",
"= stack[-1] tail = stack[:-1] if top not in root['children']:",
"math: diffing start and end memory dumps. root = {}",
"post processing to extract the relevant fields. \"\"\" if not",
"of pair of processes. If start_process is None, counts objects",
"a BSD-style license that can be # found in the",
"a sequence of pair of processes. If start_process is None,",
"can be # found in the LICENSE file. from __future__",
"dump['heaps_v2']['allocators'] # Remove processes with incomplete memory dump. for pid,",
"'stackframes': stack}) def DumpTree(root, frame, output, threshold, size_threshold): output.write('\\n{ \\\"name\\\":",
"labels') parser.add_argument( 'trace', nargs='+', help='Trace files to be processed') options",
"if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant processes to be",
"node_v1['name'] = process.strings[node['name_sid']] if 'parent' in node: node_v1['parent'] = node['parent']",
"start_process.labels == end_process.labels)): matching_start_process = start_process if matching_start_process: processes.append((matching_start_process, end_process))",
"list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type, raw_stackframe) in",
"'graph') class Process(object): def __init__(self): self.pid = None self.name =",
"if event['ph'] == 'M': if event['name'] == 'process_name' and 'name'",
"def ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id] tail = () if",
"if not ((event['name'] == 'periodic_interval' or event['name'] == 'explicitly_triggered') and",
"GraphDump() graph.pid = pid graph.name = name graph.labels = labels",
"= dump['heaps_v2']['allocators'] # Remove processes with incomplete memory dump. for",
"maps['strings']: process.strings[string['id']] = string['string'] for node in maps['nodes']: node_v1 =",
"output, threshold, size_threshold) output.write(']') output.write('}') def GetEntries(heap, process): \"\"\" Returns",
"start_processes: # Only keep end-processes. for _, end_process in six.iteritems(end_processes):",
"help='Objects threshold for being a potential memory leak') parser.add_argument( '--size-threshold',",
"# Remove processes with incomplete memory dump. for pid, process",
"'').replace('\\n', '') return (name,) + tail def ResolveType(type_id, types): return",
"stackframes, types): def ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id] tail =",
"+= child['count'] total_size += child['size'] root['count'] -= total_count root['size'] -=",
"s['name'] if 'parent' in s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] =",
"= parser.parse_args() if options.threshold == 0 and options.size_threshold == 0:",
"potential memory leak') parser.add_argument( '--filter-by-name', type=str, help='Only keep processes with",
"processed. processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps =",
"process.types) return entries def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes = {}",
"six.moves import zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph')",
"entry.type, root) for entry in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count,",
"def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes = {} for pid, process",
"import shutil import six from six.moves import zip _OUTPUT_DIR =",
"for _, end_process in six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels: #",
"2 process.allocators = dump['heaps_v2']['allocators'] # Remove processes with incomplete memory",
"src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']: # Memory dump format V2",
"tree. filename = 'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR,",
"if not process.allocators: process.version = 1 process.allocators = event['args']['dumps']['heaps'] #",
"= [] if not start_processes: # Only keep end-processes. for",
"IncrementHeapEntry(stack, count, size, typename, root): if not stack: root['count'] +=",
"child_frame, output, threshold, size_threshold) output.write(']') output.write('}') def GetEntries(heap, process): \"\"\"",
"Copy the D3 library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir,",
"{} self.allocators = None self.version = None class Entry(object): def",
"If start_process is None, counts objects in end_trace. Otherwise, counts",
"GetEntries(heap, process): \"\"\" Returns all entries in a heap, after",
"= None self.labels = None self.heap = None self.root =",
"= name graph.labels = labels graph.heap = heap graph_dumps.append(graph) #",
"{} for type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if",
"16) entry.type = int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif process.version",
"node_v1 for t in maps['types']: process.types[t['id']] = process.strings[t['name_sid']] # Get",
"entry.size = int(raw_entry['size'], 16) entry.type = int(raw_entry['type']) entry.stackframe = int(raw_entry['bt'])",
"a memory dump V1. if u'heaps' in event['args']['dumps']: # Get",
"graph.name = name graph.labels = labels graph.heap = heap graph_dumps.append(graph)",
"filename) with open(output_filename, 'w') as output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps,",
"k: k['size']) if leaks: print(' %s: %d potential leaks found.'",
"Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str, help='Only keep processes with matching",
"processes: processes[pid] = Process() processes[pid].pid = pid process = processes[pid]",
"child in root['children'].items(): if is_first: is_first = False else: output.write(',')",
"'potential leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects, } for graph in",
"source code is governed by a BSD-style license that can",
"1 process.allocators = event['args']['dumps']['heaps'] # Check for a memory dump",
"for pid in relevant_pids: start_process = start_processes[pid] end_process = end_processes[pid]",
"dump. end_processes = FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes",
"'detailed'): continue # Check for a memory dump V1. if",
"None self.size = None self.type = None self.stackframe = None",
"-= total_count_for_type for child in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack,",
"if pid not in processes: processes[pid] = Process() processes[pid].pid =",
"= process.strings[node['name_sid']] if 'parent' in node: node_v1['parent'] = node['parent'] process.stackframes[node['id']]",
"event['args']['name'] if event['name'] == 'process_labels' and 'labels' in event['args']: process.labels",
"not in processes: processes[pid] = Process() processes[pid].pid = pid process",
"= leaks graph.leak_stackframes = len(leaks) for leak in leaks: graph.leak_objects",
"end_trace, but not in start_process. \"\"\" graph_dumps = [] for",
"FindLeaks(root, [], leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda k: k['size']) if",
"Stackframe may be -1 (18446744073709551615L) when not stackframe are #",
"= int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe # Look for a detailed",
"see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in raw_entry or not",
"options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant processes to",
"process.stackframes[node['id']] = node_v1 for t in maps['types']: process.types[t['id']] = process.strings[t['name_sid']]",
"options.trace[0] start_trace = None else: start_trace = options.trace[0] end_trace =",
"filter_by_name, filter_by_labels) # Build a sequence of pair of processes",
"processes with name (i.e. Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str,",
"graph_dumps: if graph.leaks: filename = 'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename",
"root['count_by_type']: total_count_for_type = 0 for child in six.itervalues(root['children']): if typename",
"{} new_node['count_by_type'] = {} root['children'][top] = new_node IncrementHeapEntry(tail, count, size,",
"is None, counts objects in end_trace. Otherwise, counts objects present",
"= {} root['children'][top] = new_node IncrementHeapEntry(tail, count, size, typename, root['children'][top])",
"new_stackframe = {} new_stackframe['name'] = s['name'] if 'parent' in s:",
"based on their PID. relevant_pids = set(end_processes.keys()) & set(start_processes.keys()) for",
"graph.leak_objects, } for graph in graph_dumps], output) def WriteHTML(): #",
"+= child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for child in six.itervalues(root['children']): CanonicalHeapEntries(child)",
"processes.append((matching_start_process, end_process)) else: # Processes are paired based on their",
"== 1: for raw_entry in process.allocators[heap]['entries']: # Cumulative sizes and",
"entry.type = int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry) elif process.version ==",
"= 0 for child in six.itervalues(root['children']): if typename in child['count_by_type']:",
"# Copy the D3 library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir,",
"dump. if not process.allocators: dump = event['args']['dumps'] process.version = 2",
"to be compared. processes = [] if not start_processes: #",
"DumpTree(root, frame, output, threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame)",
"= None self.stackframe = None class GraphDump(object): def __init__(self): self.pid",
"dump. if not process.allocators: process.version = 1 process.allocators = event['args']['dumps']['heaps']",
"None self.type = None self.stackframe = None class GraphDump(object): def",
"fields. \"\"\" if not process: return [] entries = []",
"typename, root['children'][top]) def CanonicalHeapEntries(root): total_count = 0 total_size = 0",
"raw_stackframe entries.append(entry) # Resolve fields by looking into indexes ResolveMemoryDumpFields(entries,",
"graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with open(output_filename, 'w')",
"start and end memory dumps. root = {} root['count'] =",
"u'heaps' in event['args']['dumps']: # Get the first memory dump. if",
"entry.stackframe = [] else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type =",
"None self.name = None self.labels = None self.heap = None",
"self.strings = {} self.stackframes = {} self.allocators = None self.version",
"a memory dump V2. # See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if",
"if root['count'] > threshold and root['size'] > size_threshold: leaks.append({'count': root['count'],",
"count root['size'] += size if typename not in root['count_by_type']: root['count_by_type'][typename]",
"leaks = [] FindLeaks(root, [], leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda",
"start_trace = options.trace[0] end_trace = options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR)",
"'r') as f: data = json.loads(f.read().decode('utf-8')) for event in data['traceEvents']:",
"dump V1. if u'heaps' in event['args']['dumps']: # Get the first",
"process informations. if event['ph'] == 'M': if event['name'] == 'process_name'",
"filter_by_labels not in process.labels)): continue remaining_processes[pid] = process return remaining_processes",
"end-processes. for _, end_process in six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels:",
"size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' % root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' %",
"if matching_start_process: processes.append((matching_start_process, end_process)) else: # Processes are paired based",
"self.allocators = None self.version = None class Entry(object): def __init__(self):",
"by looking into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries def",
"and (not process.labels or filter_by_labels not in process.labels)): continue remaining_processes[pid]",
"json import os import shutil import six from six.moves import",
"stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,) + tail",
"Get the first memory dump. if not process.allocators: process.version =",
"= [] for (start_process, end_process) in processes: pid = end_process.pid",
"entries = [] if process.version == 1: for raw_entry in",
"threshold, size_threshold) leaks.sort(reverse=True, key=lambda k: k['size']) if leaks: print(' %s:",
"matching_start_process = None for _, start_process in six.iteritems(start_processes): if (start_process.name",
"filter_by_labels, match_by_labels): # Retrieve the processes and the associated memory",
"process.strings[node['name_sid']] if 'parent' in node: node_v1['parent'] = node['parent'] process.stackframes[node['id']] =",
"destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def Main(): parser =",
"== 'stackFrames': process.stackframes = {} for stack_id, s in six.iteritems(event['args']['stackFrames']):",
"(i.e. Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str, help='Only keep processes",
"in a heap, after filtering out unknown entries, and doing",
"based on name/labels. for _, end_process in six.iteritems(end_processes): matching_start_process =",
"entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root = root # Find",
"is_first: is_first = False else: output.write(',') DumpTree(child, child_frame, output, threshold,",
"not (process.allocators and process.stackframes and process.types): del processes[pid] return processes",
"information incrementally. Update # the cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps']",
"== end_process.labels)): matching_start_process = start_process if matching_start_process: processes.append((matching_start_process, end_process)) else:",
"after filtering out unknown entries, and doing some post processing",
"total_count = 0 total_size = 0 for child in six.itervalues(root['children']):",
"return [] entries = [] if process.version == 1: for",
"'' self.leaks = '' self.leak_stackframes = 0 self.leak_objects = 0",
"- entry.count, - entry.size, entry.type, root) for entry in end_entries:",
"{} root['count_by_type'] = {} for entry in start_entries: if entry.type:",
"event['args']: process.labels = event['args']['labels'] if event['name'] == 'typeNames': process.types =",
"count, size, typename, root['children'][top]) def CanonicalHeapEntries(root): total_count = 0 total_size",
"else: top = stack[-1] tail = stack[:-1] if top not",
"of processes. If start_process is None, counts objects in end_trace.",
"...)') parser.add_argument( '--filter-by-labels', type=str, help='Only keep processes with matching labels')",
"in event['args']['dumps']: # Memory dump format V2 is dumping information",
"entry in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root)",
"and types are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not",
"six from six.moves import zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR =",
"some post processing to extract the relevant fields. \"\"\" if",
"= pid process = processes[pid] # Retrieve process informations. if",
"= {} self.allocators = None self.version = None class Entry(object):",
"event['pid'] if pid not in processes: processes[pid] = Process() processes[pid].pid",
"filter_by_name: continue if (filter_by_labels and (not process.labels or filter_by_labels not",
"graph.root = root # Find leaks leaks = [] FindLeaks(root,",
"The Chromium Authors. All rights reserved. # Use of this",
"in node: node_v1['parent'] = node['parent'] process.stackframes[node['id']] = node_v1 for t",
"in child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for child",
"source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination)",
"def Main(): parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output a",
"# Memory dump format V2 is dumping information incrementally. Update",
"elif process.version == 2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes']))",
"= 1000 if len(options.trace) == 1: end_trace = options.trace[0] start_trace",
"relevant_pids: start_process = start_processes[pid] end_process = end_processes[pid] processes.append((start_process, end_process)) return",
"graph.leak_objects += leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps): for graph in",
"= t if event['name'] == 'stackFrames': process.stackframes = {} for",
"open(file_path, mode + 't') def FindMemoryDumps(filename): processes = {} with",
"== 'process_labels' and 'labels' in event['args']: process.labels = event['args']['labels'] if",
"'periodic_interval' or event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'): continue",
"0 self.leak_objects = 0 def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return",
"child in six.itervalues(root['children']): total_count += child['count'] total_size += child['size'] root['count']",
"[] FindLeaks(root, [], leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda k: k['size'])",
"== 'detailed'): continue # Check for a memory dump V1.",
"start_process in six.iteritems(start_processes): if (start_process.name == end_process.name and (start_process.name in",
"in end_trace, but not in start_process. \"\"\" graph_dumps = []",
"between runs by labels') parser.add_argument( 'trace', nargs='+', help='Trace files to",
"'b') return open(file_path, mode + 't') def FindMemoryDumps(filename): processes =",
"process.version = 1 process.allocators = event['args']['dumps']['heaps'] # Check for a",
"= None self.type = None self.stackframe = None class GraphDump(object):",
"return entries def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes = {} for",
"= None else: start_trace = options.trace[0] end_trace = options.trace[1] if",
"in stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n',",
"= {} for type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t",
"event['args']['dumps']: # Get the first memory dump. if not process.allocators:",
"{} new_node['count'] = 0 new_node['size'] = 0 new_node['children'] = {}",
"root = {} root['count'] = 0 root['size'] = 0 root['children']",
"match_by_labels): # Retrieve the processes and the associated memory dump.",
"from six.moves import zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR,",
"Look for a detailed memory dump event. if not ((event['name']",
"\"\"\" if not process: return [] entries = [] if",
"entry.type = ResolveType(entry.type, types) def IncrementHeapEntry(stack, count, size, typename, root):",
"'--flame-graph', action='store_true', help='Output a flame graph based on stackframe allocations')",
"in six.iteritems(end_processes): matching_start_process = None for _, start_process in six.iteritems(start_processes):",
"False else: output.write(',') DumpTree(child, child_frame, output, threshold, size_threshold) output.write(']') output.write('}')",
"in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size, entry.type,",
"= {} new_stackframe['name'] = s['name'] if 'parent' in s: new_stackframe['parent']",
"process = processes[pid] # Retrieve process informations. if event['ph'] ==",
"= raw_stackframe entries.append(entry) # Resolve fields by looking into indexes",
"start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build a sequence of",
"page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source,",
"import os import shutil import six from six.moves import zip",
"root['count_by_type'][typename] -= total_count_for_type for child in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root,",
"(start_process, end_process) in processes: pid = end_process.pid name = end_process.name",
"self.stackframe = None class GraphDump(object): def __init__(self): self.pid = None",
"root['children'][top] = new_node IncrementHeapEntry(tail, count, size, typename, root['children'][top]) def CanonicalHeapEntries(root):",
"child in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks, threshold, size_threshold):",
"string in maps['strings']: process.strings[string['id']] = string['string'] for node in maps['nodes']:",
"%s: %d potential leaks found.' % (heap, len(leaks))) graph.leaks =",
"graph.root: with open(output_filename, 'w') as output: DumpTree(graph.root, '.', output, threshold,",
"graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w') as output:",
"detailed memory dump event. if not ((event['name'] == 'periodic_interval' or",
"\\\"size\\\": \\\"%s\\\",' % root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' % root['count']) output.write('",
"node['parent'] process.stackframes[node['id']] = node_v1 for t in maps['types']: process.types[t['id']] =",
"'third_party', 'd3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def",
"def CanonicalHeapEntries(root): total_count = 0 total_size = 0 for child",
"for graph in graph_dumps: # Dump the remaining allocated objects",
"0 for child in six.itervalues(root['children']): total_count += child['count'] total_size +=",
"top not in root['children']: new_node = {} new_node['count'] = 0",
"open(output_filename, 'w') as output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold, size_threshold):",
"= ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type, types) def IncrementHeapEntry(stack, count,",
"and 'name' in event['args']: process.name = event['args']['name'] if event['name'] ==",
"not raw_entry['bt']: continue entry = Entry() entry.count = int(raw_entry['count'], 16)",
"IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size, entry.type, root) for entry in",
"heap, after filtering out unknown entries, and doing some post",
"event['name'] == 'stackFrames': process.stackframes = {} for stack_id, s in",
"= None for _, start_process in six.iteritems(start_processes): if (start_process.name ==",
"end_process) graph = GraphDump() graph.pid = pid graph.name = name",
"V2. # See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']:",
"'process_labels' and 'labels' in event['args']: process.labels = event['args']['labels'] if event['name']",
"'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename) with open(output_filename,",
"start_processes = None if start_trace: start_processes = FindMemoryDumps(start_trace) start_processes =",
"tail = () if 'parent' in stackframe: tail = ResolveStackTrace(stackframe['parent'],",
"= 0 for child in six.itervalues(root['children']): total_count += child['count'] total_size",
"for child in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks, threshold,",
"type=str, help='Only keep processes with matching labels') parser.add_argument( '--match-by-labels', action='store_true',",
"process.labels or filter_by_labels not in process.labels)): continue remaining_processes[pid] = process",
"else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type, types) def",
"'index.json') with open(output_filename, 'w') as output: json.dump([ {'pid': graph.pid, 'heap':",
"graph.pid, 'heap': graph.heap, 'name': graph.name, 'labels': graph.labels, 'objects': graph.root, 'potential",
"\\\"%s\\\",' % frame) if root['count'] > threshold and root['count'] >",
"total_size for typename in root['count_by_type']: total_count_for_type = 0 for child",
"= event['args']['labels'] if event['name'] == 'typeNames': process.types = {} for",
"self.count = None self.size = None self.type = None self.stackframe",
"self.labels = None self.heap = None self.root = '' self.leaks",
"[] if not start_processes: # Only keep end-processes. for _,",
"filter_by_labels) start_processes = None if start_trace: start_processes = FindMemoryDumps(start_trace) start_processes",
"{} root['count'] = 0 root['size'] = 0 root['children'] = {}",
"'process_name' and 'name' in event['args']: process.name = event['args']['name'] if event['name']",
"their PID. relevant_pids = set(end_processes.keys()) & set(start_processes.keys()) for pid in",
"leak') parser.add_argument( '--size-threshold', type=int, default=0, help='Size threshold for being a",
"= () if 'parent' in stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes)",
"# found in the LICENSE file. from __future__ import absolute_import",
"action='store_true', help='Output a flame graph based on stackframe allocations') parser.add_argument(",
"[], leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda k: k['size']) if leaks:",
"'--threshold', type=int, default=0, help='Objects threshold for being a potential memory",
"process.types[int(type_id)] = t if event['name'] == 'stackFrames': process.stackframes = {}",
"'count_by_type': root['count_by_type'], 'stackframes': stack}) def DumpTree(root, frame, output, threshold, size_threshold):",
"# Find leaks leaks = [] FindLeaks(root, [], leaks, threshold,",
"process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type, raw_stackframe) in raw_entries:",
"else: start_trace = options.trace[0] end_trace = options.trace[1] if not os.path.exists(_OUTPUT_DIR):",
"os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w') as output: json.dump([ {'pid': graph.pid,",
"for pid, process in six.iteritems(processes): if filter_by_name and process.name !=",
"def WriteHTML(): # Copy the HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)),",
"options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if",
"top = stack[-1] tail = stack[:-1] if top not in",
"See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']: # Memory",
"(graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w') as",
"paired based on their PID. relevant_pids = set(end_processes.keys()) & set(start_processes.keys())",
"FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold)",
"governed by a BSD-style license that can be # found",
"potential leaks found.' % (heap, len(leaks))) graph.leaks = leaks graph.leak_stackframes",
"tail def ResolveType(type_id, types): return types[type_id] for entry in entries:",
"typename, root): if not stack: root['count'] += count root['size'] +=",
"def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels): # Retrieve the processes",
"WritePotentialLeaks(graph_dumps): for graph in graph_dumps: if graph.leaks: filename = 'process_%d_%s-leaks.json'",
"-= total_size for typename in root['count_by_type']: total_count_for_type = 0 for",
"1: end_trace = options.trace[0] start_trace = None else: start_trace =",
"end_trace, filter_by_name, filter_by_labels, match_by_labels): # Retrieve the processes and the",
"the first memory dump. if not process.allocators: dump = event['args']['dumps']",
"((event['name'] == 'periodic_interval' or event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] ==",
"+= count else: top = stack[-1] tail = stack[:-1] if",
"self.leak_objects = 0 def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return gzip.open(file_path,",
"= end_processes[pid] processes.append((start_process, end_process)) return processes def BuildGraphDumps(processes, threshold, size_threshold):",
"that can be # found in the LICENSE file. from",
"json.loads(f.read().decode('utf-8')) for event in data['traceEvents']: pid = event['pid'] if pid",
"threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame) if root['count'] >",
"may be -1 (18446744073709551615L) when not stackframe are # available.",
"return types[type_id] for entry in entries: # Stackframe may be",
"FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build a sequence of pair of",
"OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return gzip.open(file_path, mode + 'b') return",
"if graph.leaks: filename = 'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename =",
"# Processes are paired based on their PID. relevant_pids =",
"memory dump. end_processes = FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels)",
"for stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name'] =",
"stackframes[stack_id] tail = () if 'parent' in stackframe: tail =",
"= os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def __init__(self): self.pid = None",
"six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if event['name'] == 'stackFrames': process.stackframes =",
"if options.threshold == 0 and options.size_threshold == 0: options.threshold =",
"format V2 is dumping information incrementally. Update # the cumulated",
"pid, process in processes.items(): if not (process.allocators and process.stackframes and",
"Retrieve process informations. if event['ph'] == 'M': if event['name'] ==",
"self.types = {} self.strings = {} self.stackframes = {} self.allocators",
"% frame) if root['count'] > threshold and root['count'] > size_threshold:",
"in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks, threshold, size_threshold): for",
"process.allocators[heap]['entries']: # Cumulative sizes and types are skipped. see: #",
"options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph:",
"= root # Find leaks leaks = [] FindLeaks(root, [],",
"Otherwise, counts objects present in end_trace, but not in start_process.",
"file_path.endswith('.gz'): return gzip.open(file_path, mode + 'b') return open(file_path, mode +",
"if root['count'] > threshold and root['count'] > size_threshold: output.write(' \\\"size\\\":",
"= None self.heap = None self.root = '' self.leaks =",
"FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels): # Retrieve the processes and",
"allocated objects tree. filename = 'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename",
"\\\"%s\\\",' % root['count']) output.write(' \\\"children\\\": [') is_first = True for",
"'d3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def Main(): parser",
"graph.labels = labels graph.heap = heap graph_dumps.append(graph) # Do the",
"in ['Browser', 'GPU'] or start_process.labels == end_process.labels)): matching_start_process = start_process",
"remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name, filter_by_labels, match_by_labels): # Retrieve the",
"WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w') as output:",
"end_process.allocators: start_entries = GetEntries(heap, start_process) end_entries = GetEntries(heap, end_process) graph",
"def WritePotentialLeaks(graph_dumps): for graph in graph_dumps: if graph.leaks: filename =",
"'--match-by-labels', action='store_true', help='Match processes between runs by labels') parser.add_argument( 'trace',",
"= os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with open(output_filename, 'w') as output:",
"= Entry() entry.count = int(raw_entry['count'], 16) entry.size = int(raw_entry['size'], 16)",
"process.labels = event['args']['labels'] if event['name'] == 'typeNames': process.types = {}",
"Build a sequence of pair of processes to be compared.",
"_, start_process in six.iteritems(start_processes): if (start_process.name == end_process.name and (start_process.name",
"= os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) #",
"filename = 'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR, filename)",
"output) def WriteHTML(): # Copy the HTML page. source =",
"process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type, raw_stackframe) in raw_entries: entry =",
"processes with incomplete memory dump. for pid, process in processes.items():",
"for entry in entries: # Stackframe may be -1 (18446744073709551615L)",
"else: output.write(',') DumpTree(child, child_frame, output, threshold, size_threshold) output.write(']') output.write('}') def",
"self.pid = None self.name = None self.labels = None self.types",
"int(raw_entry['count'], 16) entry.size = int(raw_entry['size'], 16) entry.type = int(raw_entry['type']) entry.stackframe",
"if is_first: is_first = False else: output.write(',') DumpTree(child, child_frame, output,",
"= 0 root['children'] = {} root['count_by_type'] = {} for entry",
"entries: # Stackframe may be -1 (18446744073709551615L) when not stackframe",
"compared. processes = [] if not start_processes: # Only keep",
"else '' labels = end_process.labels if end_process.labels else '' print('Process[%d]",
"== 'process_name' and 'name' in event['args']: process.name = event['args']['name'] if",
"int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe # Look for a detailed memory",
"Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str, help='Only keep processes with",
"dump = event['args']['dumps'] process.version = 2 process.allocators = dump['heaps_v2']['allocators'] #",
"= labels graph.heap = heap graph_dumps.append(graph) # Do the math:",
"json.dump([ {'pid': graph.pid, 'heap': graph.heap, 'name': graph.name, 'labels': graph.labels, 'objects':",
"CanonicalHeapEntries(root) graph.root = root # Find leaks leaks = []",
"_, end_process in six.iteritems(end_processes): matching_start_process = None for _, start_process",
"processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes,",
"processing to extract the relevant fields. \"\"\" if not process:",
"root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' % root['count']) output.write(' \\\"children\\\": [') is_first",
"Dump the remaining allocated objects tree. filename = 'process_%d_%s-objects.json' %",
"if process.version == 1: for raw_entry in process.allocators[heap]['entries']: # Cumulative",
"incrementally. Update # the cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for",
"% (heap, len(leaks))) graph.leaks = leaks graph.leak_stackframes = len(leaks) for",
"start_process is None, counts objects in end_trace. Otherwise, counts objects",
"for heap in end_process.allocators: start_entries = GetEntries(heap, start_process) end_entries =",
"name graph.labels = labels graph.heap = heap graph_dumps.append(graph) # Do",
"process.types = {} for type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] =",
"total_count_for_type for child in six.itervalues(root['children']): CanonicalHeapEntries(child) def FindLeaks(root, stack, leaks,",
"entries.append(entry) # Resolve fields by looking into indexes ResolveMemoryDumpFields(entries, process.stackframes,",
"six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name'] = s['name'] if 'parent' in",
"types are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in",
"if event['name'] == 'typeNames': process.types = {} for type_id, t",
"end_process.labels else '' print('Process[%d] %s: %s' % (pid, name, labels))",
"os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js') destination =",
"return graph_dumps def WritePotentialLeaks(graph_dumps): for graph in graph_dumps: if graph.leaks:",
"Copy the HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination =",
"graph for a sequence of pair of processes. If start_process",
"from __future__ import print_function import argparse import gzip import json",
"node in maps['nodes']: node_v1 = {} node_v1['name'] = process.strings[node['name_sid']] if",
"{} new_stackframe['name'] = s['name'] if 'parent' in s: new_stackframe['parent'] =",
"= int(raw_entry['size'], 16) entry.type = int(raw_entry['type']) entry.stackframe = int(raw_entry['bt']) entries.append(entry)",
"Resolve fields by looking into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return",
"start_process) end_entries = GetEntries(heap, end_process) graph = GraphDump() graph.pid =",
"= stack[:-1] if top not in root['children']: new_node = {}",
"for leak in leaks: graph.leak_objects += leak['count'] return graph_dumps def",
"= {} root['count_by_type'] = {} for entry in start_entries: if",
"= 0 total_size = 0 for child in six.itervalues(root['children']): total_count",
"graph.heap = heap graph_dumps.append(graph) # Do the math: diffing start",
"is_first = False else: output.write(',') DumpTree(child, child_frame, output, threshold, size_threshold)",
"parser.add_argument( '--flame-graph', action='store_true', help='Output a flame graph based on stackframe",
"pid, process in six.iteritems(processes): if filter_by_name and process.name != filter_by_name:",
"set(start_processes.keys()) for pid in relevant_pids: start_process = start_processes[pid] end_process =",
"open(output_filename, 'w') as output: json.dump([ {'pid': graph.pid, 'heap': graph.heap, 'name':",
"for typename in root['count_by_type']: total_count_for_type = 0 for child in",
"leaks leaks = [] FindLeaks(root, [], leaks, threshold, size_threshold) leaks.sort(reverse=True,",
"= options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant processes",
"for frame in root['children']: FindLeaks(root['children'][frame], [frame] + stack, leaks, threshold,",
"'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'): continue # Check for a",
"a detailed memory dump event. if not ((event['name'] == 'periodic_interval'",
"os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) # Copy",
"size_threshold): for graph in graph_dumps: # Dump the remaining allocated",
"leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps): for graph in graph_dumps: if",
"labels)) for heap in end_process.allocators: start_entries = GetEntries(heap, start_process) end_entries",
"threshold, size_threshold) if root['count'] > threshold and root['size'] > size_threshold:",
"if end_process.name else '' labels = end_process.labels if end_process.labels else",
"filtering out unknown entries, and doing some post processing to",
"is_first = True for child_frame, child in root['children'].items(): if is_first:",
"new_node['size'] = 0 new_node['children'] = {} new_node['count_by_type'] = {} root['children'][top]",
"be compared. processes = [] if not start_processes: # Only",
"filter_by_name, filter_by_labels): remaining_processes = {} for pid, process in six.iteritems(processes):",
"graph.leaks: filename = 'process_%d_%s-leaks.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_DIR,",
"if 'parent' in stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes) name =",
"0 root['count_by_type'][typename] += count else: top = stack[-1] tail =",
"process.stackframes[int(stack_id)] = new_stackframe # Look for a detailed memory dump",
"if 'parent' in s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe",
"= 0 def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return gzip.open(file_path, mode",
"leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack}) def DumpTree(root,",
"= event['pid'] if pid not in processes: processes[pid] = Process()",
"output.write(' \\\"count\\\": \\\"%s\\\",' % root['count']) output.write(' \\\"children\\\": [') is_first =",
"def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w') as",
"the cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']:",
"with open(output_filename, 'w') as output: DumpTree(graph.root, '.', output, threshold, size_threshold)",
"graph.leak_stackframes = len(leaks) for leak in leaks: graph.leak_objects += leak['count']",
"FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes = {} for pid, process in",
"root) for entry in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size,",
"t in maps['types']: process.types[t['id']] = process.strings[t['name_sid']] # Get the first",
"Authors. All rights reserved. # Use of this source code",
"start_trace = None else: start_trace = options.trace[0] end_trace = options.trace[1]",
"memory dump. if not process.allocators: dump = event['args']['dumps'] process.version =",
"output, threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame) if root['count']",
"process in processes.items(): if not (process.allocators and process.stackframes and process.types):",
"a heap, after filtering out unknown entries, and doing some",
"__init__(self): self.count = None self.size = None self.type = None",
"Check for a memory dump V1. if u'heaps' in event['args']['dumps']:",
"# Build a sequence of pair of processes to be",
"(filter_by_labels and (not process.labels or filter_by_labels not in process.labels)): continue",
"graph_dumps.append(graph) # Do the math: diffing start and end memory",
"['Browser', 'GPU'] or start_process.labels == end_process.labels)): matching_start_process = start_process if",
"graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if not",
"len(leaks) for leak in leaks: graph.leak_objects += leak['count'] return graph_dumps",
"entries, and doing some post processing to extract the relevant",
"threshold and root['size'] > size_threshold: leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type':",
"entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root = root # Find leaks",
"self.heap = None self.root = '' self.leaks = '' self.leak_stackframes",
"for being a potential memory leak') parser.add_argument( '--size-threshold', type=int, default=0,",
"skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in raw_entry or",
"== 0: options.threshold = 1000 if len(options.trace) == 1: end_trace",
"= {} self.stackframes = {} self.allocators = None self.version =",
"= os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w') as output: json.dump([ {'pid':",
"for event in data['traceEvents']: pid = event['pid'] if pid not",
"root['count'] = 0 root['size'] = 0 root['children'] = {} root['count_by_type']",
"# Dump the remaining allocated objects tree. filename = 'process_%d_%s-objects.json'",
"root['count'] > size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' % root['size']) output.write(' \\\"count\\\":",
"entry = Entry() entry.count = int(raw_entry['count'], 16) entry.size = int(raw_entry['size'],",
"= [] if process.version == 1: for raw_entry in process.allocators[heap]['entries']:",
"# Check for a memory dump V1. if u'heaps' in",
"in raw_entries: entry = Entry() entry.count = raw_count entry.size =",
"and process.types): del processes[pid] return processes def ResolveMemoryDumpFields(entries, stackframes, types):",
"if event['name'] == 'process_name' and 'name' in event['args']: process.name =",
"u'heaps_v2' in event['args']['dumps']: # Memory dump format V2 is dumping",
"output.write(',') DumpTree(child, child_frame, output, threshold, size_threshold) output.write(']') output.write('}') def GetEntries(heap,",
"labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match processes between runs by labels')",
"0 root['children'] = {} root['count_by_type'] = {} for entry in",
"= os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) # Copy the D3 library",
"leaks: print(' %s: %d potential leaks found.' % (heap, len(leaks)))",
"root['count_by_type'], 'stackframes': stack}) def DumpTree(root, frame, output, threshold, size_threshold): output.write('\\n{",
"= None class Entry(object): def __init__(self): self.count = None self.size",
"threshold for being a potential memory leak') parser.add_argument( '--size-threshold', type=int,",
"end_trace = options.trace[0] start_trace = None else: start_trace = options.trace[0]",
"if event['name'] == 'process_labels' and 'labels' in event['args']: process.labels =",
"root): if not stack: root['count'] += count root['size'] += size",
"root) CanonicalHeapEntries(root) graph.root = root # Find leaks leaks =",
"\\\"name\\\": \\\"%s\\\",' % frame) if root['count'] > threshold and root['count']",
"not process.allocators: dump = event['args']['dumps'] process.version = 2 process.allocators =",
"for _, end_process in six.iteritems(end_processes): matching_start_process = None for _,",
"# Do the math: diffing start and end memory dumps.",
"if leaks: print(' %s: %d potential leaks found.' % (heap,",
"new_stackframe # Look for a detailed memory dump event. if",
"= 0 root['size'] = 0 root['children'] = {} root['count_by_type'] =",
"event['name'] == 'process_labels' and 'labels' in event['args']: process.labels = event['args']['labels']",
"memory dump V2. # See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2'",
"for a memory dump V1. if u'heaps' in event['args']['dumps']: #",
"= raw_size entry.type = raw_type entry.stackframe = raw_stackframe entries.append(entry) #",
"root['size'] > size_threshold: leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes':",
"for _, start_process in six.iteritems(start_processes): if (start_process.name == end_process.name and",
"when not stackframe are # available. if entry.stackframe not in",
"= heap graph_dumps.append(graph) # Do the math: diffing start and",
"Returns all entries in a heap, after filtering out unknown",
"import gzip import json import os import shutil import six",
"new_node['count_by_type'] = {} root['children'][top] = new_node IncrementHeapEntry(tail, count, size, typename,",
"parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output a flame graph",
"ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id] tail = () if 'parent'",
"filename def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w')",
"graph in graph_dumps: # Dump the remaining allocated objects tree.",
"t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if event['name'] == 'stackFrames':",
"mode): if file_path.endswith('.gz'): return gzip.open(file_path, mode + 'b') return open(file_path,",
"def GetEntries(heap, process): \"\"\" Returns all entries in a heap,",
"graph in graph_dumps], output) def WriteHTML(): # Copy the HTML",
"if graph.root: with open(output_filename, 'w') as output: DumpTree(graph.root, '.', output,",
"and the associated memory dump. end_processes = FindMemoryDumps(end_trace) end_processes =",
"None self.labels = None self.types = {} self.strings = {}",
"start_processes[pid] end_process = end_processes[pid] processes.append((start_process, end_process)) return processes def BuildGraphDumps(processes,",
"1000 if len(options.trace) == 1: end_trace = options.trace[0] start_trace =",
"output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename, 'w') as output: json.dump([",
"output) def WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph in graph_dumps: #",
"+ 't') def FindMemoryDumps(filename): processes = {} with OpenTraceFile(filename, 'r')",
"not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant processes to be processed.",
"% (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with",
"# Stackframe may be -1 (18446744073709551615L) when not stackframe are",
"help='Size threshold for being a potential memory leak') parser.add_argument( '--filter-by-name',",
"objects present in end_trace, but not in start_process. \"\"\" graph_dumps",
"and (start_process.name in ['Browser', 'GPU'] or start_process.labels == end_process.labels)): matching_start_process",
"raw_entry or not raw_entry['bt']: continue entry = Entry() entry.count =",
"# Get the first memory dump. if not process.allocators: dump",
"{} self.strings = {} self.stackframes = {} self.allocators = None",
"(graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with open(output_filename,",
"= event['args']['dumps']['heaps_v2']['maps'] for string in maps['strings']: process.strings[string['id']] = string['string'] for",
"total_count += child['count'] total_size += child['size'] root['count'] -= total_count root['size']",
"options.trace[0] end_trace = options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find",
"new_node['children'] = {} new_node['count_by_type'] = {} root['children'][top] = new_node IncrementHeapEntry(tail,",
"in six.itervalues(root['children']): if typename in child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename]",
"name/labels. for _, end_process in six.iteritems(end_processes): matching_start_process = None for",
"os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def Main(): parser = argparse.ArgumentParser() parser.add_argument(",
"for type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if event['name']",
"if (start_process.name == end_process.name and (start_process.name in ['Browser', 'GPU'] or",
"graph.labels, 'objects': graph.root, 'potential leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects, }",
"raw_size entry.type = raw_type entry.stackframe = raw_stackframe entries.append(entry) # Resolve",
"os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML() if __name__ ==",
"found in the LICENSE file. from __future__ import absolute_import from",
"if u'heaps_v2' in event['args']['dumps']: # Memory dump format V2 is",
"print_function import argparse import gzip import json import os import",
"Entry(object): def __init__(self): self.count = None self.size = None self.type",
"maps['types']: process.types[t['id']] = process.strings[t['name_sid']] # Get the first memory dump.",
"'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root:",
"by a BSD-style license that can be # found in",
"and doing some post processing to extract the relevant fields.",
"in maps['types']: process.types[t['id']] = process.strings[t['name_sid']] # Get the first memory",
"of pair of processes to be compared. processes = []",
"runs by labels') parser.add_argument( 'trace', nargs='+', help='Trace files to be",
"not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML() if __name__",
"def __init__(self): self.pid = None self.name = None self.labels =",
"self.type = None self.stackframe = None class GraphDump(object): def __init__(self):",
"elif match_by_labels: # Processes are paired based on name/labels. for",
"= stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,) + tail def ResolveType(type_id,",
"in stackframes: entry.stackframe = [] else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes)",
"= ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,)",
"2017 The Chromium Authors. All rights reserved. # Use of",
"data['traceEvents']: pid = event['pid'] if pid not in processes: processes[pid]",
"event['args']['dumps']['heaps'] # Check for a memory dump V2. # See",
"on name/labels. for _, end_process in six.iteritems(end_processes): matching_start_process = None",
"def ResolveType(type_id, types): return types[type_id] for entry in entries: #",
"WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph in graph_dumps: # Dump the",
"and 'labels' in event['args']: process.labels = event['args']['labels'] if event['name'] ==",
"process.allocators: dump = event['args']['dumps'] process.version = 2 process.allocators = dump['heaps_v2']['allocators']",
"GraphDump(object): def __init__(self): self.pid = None self.name = None self.labels",
"if (filter_by_labels and (not process.labels or filter_by_labels not in process.labels)):",
"options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps,",
"format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']: # Memory dump",
"entry in entries: # Stackframe may be -1 (18446744073709551615L) when",
"leak') parser.add_argument( '--filter-by-name', type=str, help='Only keep processes with name (i.e.",
"mode + 'b') return open(file_path, mode + 't') def FindMemoryDumps(filename):",
"All rights reserved. # Use of this source code is",
"processes to be processed. processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels,",
"= None self.size = None self.type = None self.stackframe =",
"dump event. if not ((event['name'] == 'periodic_interval' or event['name'] ==",
"stack}) def DumpTree(root, frame, output, threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",'",
"= [] FindLeaks(root, [], leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda k:",
"self.size = None self.type = None self.stackframe = None class",
"start_processes = FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build",
"processes: pid = end_process.pid name = end_process.name if end_process.name else",
"[] entries = [] if process.version == 1: for raw_entry",
"and end memory dumps. root = {} root['count'] = 0",
"six.itervalues(root['children']): total_count += child['count'] total_size += child['size'] root['count'] -= total_count",
"size_threshold): for frame in root['children']: FindLeaks(root['children'][frame], [frame] + stack, leaks,",
"the processes and the associated memory dump. end_processes = FindMemoryDumps(end_trace)",
"in root['children']: new_node = {} new_node['count'] = 0 new_node['size'] =",
"= argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output a flame graph based",
"= raw_count entry.size = raw_size entry.type = raw_type entry.stackframe =",
"'w') as output: json.dump([ {'pid': graph.pid, 'heap': graph.heap, 'name': graph.name,",
"leaks: graph.leak_objects += leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps): for graph",
"child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for child in six.itervalues(root['children']): CanonicalHeapEntries(child) def",
"\\\"%s\\\",' % root['size']) output.write(' \\\"count\\\": \\\"%s\\\",' % root['count']) output.write(' \\\"children\\\":",
"threshold, size_threshold): \"\"\" Build graph for a sequence of pair",
"for (raw_count, raw_size, raw_type, raw_stackframe) in raw_entries: entry = Entry()",
"process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size, raw_type, raw_stackframe) in raw_entries: entry",
"Chromium Authors. All rights reserved. # Use of this source",
"type=int, default=0, help='Size threshold for being a potential memory leak')",
"root['children'].items(): if is_first: is_first = False else: output.write(',') DumpTree(child, child_frame,",
"keep processes with name (i.e. Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels',",
"> threshold and root['count'] > size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' %",
"\"\"\" Build graph for a sequence of pair of processes.",
"_, end_process in six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels: # Processes",
"default=0, help='Objects threshold for being a potential memory leak') parser.add_argument(",
"output: DumpTree(graph.root, '.', output, threshold, size_threshold) graph.root = filename def",
"= {} new_node['count'] = 0 new_node['size'] = 0 new_node['children'] =",
"name = stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,) + tail def",
"end_entries = GetEntries(heap, end_process) graph = GraphDump() graph.pid = pid",
"Copyright 2017 The Chromium Authors. All rights reserved. # Use",
"by labels') parser.add_argument( 'trace', nargs='+', help='Trace files to be processed')",
"flame graph based on stackframe allocations') parser.add_argument( '--threshold', type=int, default=0,",
"= None self.name = None self.labels = None self.heap =",
"remaining_processes = {} for pid, process in six.iteritems(processes): if filter_by_name",
"entry in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size,",
"and root['size'] > size_threshold: leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'],",
"in process.labels)): continue remaining_processes[pid] = process return remaining_processes def FindRelevantProcesses(start_trace,",
"a potential memory leak') parser.add_argument( '--size-threshold', type=int, default=0, help='Size threshold",
"set(end_processes.keys()) & set(start_processes.keys()) for pid in relevant_pids: start_process = start_processes[pid]",
"0 def OpenTraceFile(file_path, mode): if file_path.endswith('.gz'): return gzip.open(file_path, mode +",
"options.size_threshold == 0: options.threshold = 1000 if len(options.trace) == 1:",
"data = json.loads(f.read().decode('utf-8')) for event in data['traceEvents']: pid = event['pid']",
"not in start_process. \"\"\" graph_dumps = [] for (start_process, end_process)",
"V1. if u'heaps' in event['args']['dumps']: # Get the first memory",
"in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if event['name'] == 'stackFrames': process.stackframes",
"CanonicalHeapEntries(root): total_count = 0 total_size = 0 for child in",
"# Copyright 2017 The Chromium Authors. All rights reserved. #",
"labels graph.heap = heap graph_dumps.append(graph) # Do the math: diffing",
"= end_process.name if end_process.name else '' labels = end_process.labels if",
"the remaining allocated objects tree. filename = 'process_%d_%s-objects.json' % (graph.pid,",
"zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class Process(object):",
"in data['traceEvents']: pid = event['pid'] if pid not in processes:",
"os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def __init__(self): self.pid = None self.name",
"pid in relevant_pids: start_process = start_processes[pid] end_process = end_processes[pid] processes.append((start_process,",
"# the cumulated indexes. maps = event['args']['dumps']['heaps_v2']['maps'] for string in",
"None self.heap = None self.root = '' self.leaks = ''",
"memory dump event. if not ((event['name'] == 'periodic_interval' or event['name']",
"potential memory leak') parser.add_argument( '--size-threshold', type=int, default=0, help='Size threshold for",
"% (pid, name, labels)) for heap in end_process.allocators: start_entries =",
"continue entry = Entry() entry.count = int(raw_entry['count'], 16) entry.size =",
"import six from six.moves import zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR",
"are paired based on name/labels. for _, end_process in six.iteritems(end_processes):",
"'objects': graph.root, 'potential leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects, } for",
"associated memory dump. end_processes = FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name,",
"= None self.version = None class Entry(object): def __init__(self): self.count",
"types): def ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id] tail = ()",
"self.stackframes = {} self.allocators = None self.version = None class",
"self.labels = None self.types = {} self.strings = {} self.stackframes",
"code is governed by a BSD-style license that can be",
"= s['name'] if 'parent' in s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)]",
"size, typename, root['children'][top]) def CanonicalHeapEntries(root): total_count = 0 total_size =",
"'stackFrames': process.stackframes = {} for stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe",
"not in root['count_by_type']: root['count_by_type'][typename] = 0 root['count_by_type'][typename] += count else:",
"None self.name = None self.labels = None self.types = {}",
"ResolveType(type_id, types): return types[type_id] for entry in entries: # Stackframe",
"root['count'] > threshold and root['size'] > size_threshold: leaks.append({'count': root['count'], 'size':",
"output.write(']') output.write('}') def GetEntries(heap, process): \"\"\" Returns all entries in",
"raw_entry['bt']: continue entry = Entry() entry.count = int(raw_entry['count'], 16) entry.size",
"raw_type, raw_stackframe) in raw_entries: entry = Entry() entry.count = raw_count",
"in root['count_by_type']: total_count_for_type = 0 for child in six.itervalues(root['children']): if",
"pair of processes to be compared. processes = [] if",
"counts objects in end_trace. Otherwise, counts objects present in end_trace,",
"= Entry() entry.count = raw_count entry.size = raw_size entry.type =",
"root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack}) def DumpTree(root, frame, output, threshold,",
"help='Only keep processes with name (i.e. Browser, Renderer, ...)') parser.add_argument(",
"'' self.leak_stackframes = 0 self.leak_objects = 0 def OpenTraceFile(file_path, mode):",
"start_process if matching_start_process: processes.append((matching_start_process, end_process)) else: # Processes are paired",
"os import shutil import six from six.moves import zip _OUTPUT_DIR",
"self.pid = None self.name = None self.labels = None self.heap",
"end_process in six.iteritems(end_processes): matching_start_process = None for _, start_process in",
"type=str, help='Only keep processes with name (i.e. Browser, Renderer, ...)')",
"six.iteritems(end_processes): processes.append((None, end_process)) elif match_by_labels: # Processes are paired based",
"_OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class Process(object): def __init__(self): self.pid =",
"indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries def FilterProcesses(processes, filter_by_name, filter_by_labels):",
"None for _, start_process in six.iteritems(start_processes): if (start_process.name == end_process.name",
"threshold, size_threshold) output.write(']') output.write('}') def GetEntries(heap, process): \"\"\" Returns all",
"1: for raw_entry in process.allocators[heap]['entries']: # Cumulative sizes and types",
"matching_start_process = start_process if matching_start_process: processes.append((matching_start_process, end_process)) else: # Processes",
"= options.trace[0] end_trace = options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) #",
"event['name'] == 'process_name' and 'name' in event['args']: process.name = event['args']['name']",
"'typeNames': process.types = {} for type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)]",
"are # available. if entry.stackframe not in stackframes: entry.stackframe =",
"'M': if event['name'] == 'process_name' and 'name' in event['args']: process.name",
"not in root['children']: new_node = {} new_node['count'] = 0 new_node['size']",
"all entries in a heap, after filtering out unknown entries,",
"event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'): continue # Check",
"FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build a sequence",
"= {} for stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe = {}",
"or start_process.labels == end_process.labels)): matching_start_process = start_process if matching_start_process: processes.append((matching_start_process,",
"'labels': graph.labels, 'objects': graph.root, 'potential leaks': graph.leak_stackframes, 'objects leaked': graph.leak_objects,",
"s in six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name'] = s['name'] if",
"dump format V2 is dumping information incrementally. Update # the",
"gzip.open(file_path, mode + 'b') return open(file_path, mode + 't') def",
"process.strings[t['name_sid']] # Get the first memory dump. if not process.allocators:",
"not process.allocators: process.version = 1 process.allocators = event['args']['dumps']['heaps'] # Check",
"FindLeaks(root['children'][frame], [frame] + stack, leaks, threshold, size_threshold) if root['count'] >",
"= None self.name = None self.labels = None self.types =",
"'w') as output: json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold, size_threshold): for",
"entry.stackframe not in stackframes: entry.stackframe = [] else: entry.stackframe =",
"or filter_by_labels not in process.labels)): continue remaining_processes[pid] = process return",
"in process.allocators[heap]['entries']: # Cumulative sizes and types are skipped. see:",
"return processes def ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id, stackframes): stackframe",
"return open(file_path, mode + 't') def FindMemoryDumps(filename): processes = {}",
"= FilterProcesses(start_processes, filter_by_name, filter_by_labels) # Build a sequence of pair",
"json.dump(graph.leaks, output) def WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph in graph_dumps:",
"(process.allocators and process.stackframes and process.types): del processes[pid] return processes def",
"incomplete memory dump. for pid, process in processes.items(): if not",
"in s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe # Look",
"relevant_pids = set(end_processes.keys()) & set(start_processes.keys()) for pid in relevant_pids: start_process",
"ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n', '') return (name,) +",
"FindLeaks(root, stack, leaks, threshold, size_threshold): for frame in root['children']: FindLeaks(root['children'][frame],",
"import json import os import shutil import six from six.moves",
"output, threshold, size_threshold) graph.root = filename def WriteIndex(graph_dumps): output_filename =",
"'') return (name,) + tail def ResolveType(type_id, types): return types[type_id]",
"process.stackframes and process.types): del processes[pid] return processes def ResolveMemoryDumpFields(entries, stackframes,",
"BSD-style license that can be # found in the LICENSE",
"{} for pid, process in six.iteritems(processes): if filter_by_name and process.name",
"= string['string'] for node in maps['nodes']: node_v1 = {} node_v1['name']",
"frame in root['children']: FindLeaks(root['children'][frame], [frame] + stack, leaks, threshold, size_threshold)",
"dumping information incrementally. Update # the cumulated indexes. maps =",
"if 'type' not in raw_entry or not raw_entry['bt']: continue entry",
"0 new_node['size'] = 0 new_node['children'] = {} new_node['count_by_type'] = {}",
"six.itervalues(root['children']): if typename in child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -=",
"as output: json.dump([ {'pid': graph.pid, 'heap': graph.heap, 'name': graph.name, 'labels':",
"for being a potential memory leak') parser.add_argument( '--filter-by-name', type=str, help='Only",
"[') is_first = True for child_frame, child in root['children'].items(): if",
"help='Only keep processes with matching labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match",
"# Get the first memory dump. if not process.allocators: process.version",
"[] if process.version == 1: for raw_entry in process.allocators[heap]['entries']: #",
"'' print('Process[%d] %s: %s' % (pid, name, labels)) for heap",
"not in process.labels)): continue remaining_processes[pid] = process return remaining_processes def",
"[] else: entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type, types)",
"graph in graph_dumps: if graph.leaks: filename = 'process_%d_%s-leaks.json' % (graph.pid,",
"type_id, t in six.iteritems(event['args']['typeNames']): process.types[int(type_id)] = t if event['name'] ==",
"process.version = 2 process.allocators = dump['heaps_v2']['allocators'] # Remove processes with",
"size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame) if root['count'] > threshold",
"+= child['size'] root['count'] -= total_count root['size'] -= total_size for typename",
"stackframes): stackframe = stackframes[stack_id] tail = () if 'parent' in",
"for node in maps['nodes']: node_v1 = {} node_v1['name'] = process.strings[node['name_sid']]",
"processes[pid] return processes def ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id, stackframes):",
"continue if (filter_by_labels and (not process.labels or filter_by_labels not in",
"shutil.copyfile(source, destination) def Main(): parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true',",
"the math: diffing start and end memory dumps. root =",
"os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js')",
"leaks graph.leak_stackframes = len(leaks) for leak in leaks: graph.leak_objects +=",
"parser.add_argument( '--threshold', type=int, default=0, help='Objects threshold for being a potential",
"= os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def Main(): parser = argparse.ArgumentParser()",
"== end_process.name and (start_process.name in ['Browser', 'GPU'] or start_process.labels ==",
"on their PID. relevant_pids = set(end_processes.keys()) & set(start_processes.keys()) for pid",
"in maps['nodes']: node_v1 = {} node_v1['name'] = process.strings[node['name_sid']] if 'parent'",
"'objects leaked': graph.leak_objects, } for graph in graph_dumps], output) def",
"six.iteritems(end_processes): matching_start_process = None for _, start_process in six.iteritems(start_processes): if",
"in leaks: graph.leak_objects += leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps): for",
"self.version = None class Entry(object): def __init__(self): self.count = None",
"be -1 (18446744073709551615L) when not stackframe are # available. if",
"for entry in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type,",
"event in data['traceEvents']: pid = event['pid'] if pid not in",
"total_size = 0 for child in six.itervalues(root['children']): total_count += child['count']",
"nargs='+', help='Trace files to be processed') options = parser.parse_args() if",
"typename in child['count_by_type']: total_count_for_type += child['count_by_type'][typename] root['count_by_type'][typename] -= total_count_for_type for",
"child in six.itervalues(root['children']): if typename in child['count_by_type']: total_count_for_type += child['count_by_type'][typename]",
"entry.stackframe = ResolveStackTrace(entry.stackframe, stackframes) entry.type = ResolveType(entry.type, types) def IncrementHeapEntry(stack,",
"and event['args']['dumps']['level_of_detail'] == 'detailed'): continue # Check for a memory",
"output_filename = os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w') as output: json.dump(graph.leaks,",
"argparse import gzip import json import os import shutil import",
"memory leak') parser.add_argument( '--filter-by-name', type=str, help='Only keep processes with name",
"= 1 process.allocators = event['args']['dumps']['heaps'] # Check for a memory",
"None class Entry(object): def __init__(self): self.count = None self.size =",
"continue remaining_processes[pid] = process return remaining_processes def FindRelevantProcesses(start_trace, end_trace, filter_by_name,",
"# Retrieve process informations. if event['ph'] == 'M': if event['name']",
"name (i.e. Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str, help='Only keep",
"be # found in the LICENSE file. from __future__ import",
"import zip _OUTPUT_DIR = 'output' _OUTPUT_GRAPH_DIR = os.path.join(_OUTPUT_DIR, 'graph') class",
"leaks, threshold, size_threshold) leaks.sort(reverse=True, key=lambda k: k['size']) if leaks: print('",
"threshold, size_threshold): for graph in graph_dumps: # Dump the remaining",
"Process() processes[pid].pid = pid process = processes[pid] # Retrieve process",
"return processes def BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build graph for",
"stackframe = stackframes[stack_id] tail = () if 'parent' in stackframe:",
"processes between runs by labels') parser.add_argument( 'trace', nargs='+', help='Trace files",
"file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir, 'tracing', 'third_party', 'd3',",
"of processes to be compared. processes = [] if not",
"options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold,",
"os.path.join(_OUTPUT_DIR, filename) with open(output_filename, 'w') as output: json.dump(graph.leaks, output) def",
"counts objects present in end_trace, but not in start_process. \"\"\"",
"end_processes = FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes =",
"the D3 library file. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir, os.path.pardir,",
"BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps) if options.flame_graph: if not os.path.exists(_OUTPUT_GRAPH_DIR): os.makedirs(_OUTPUT_GRAPH_DIR)",
"== 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'): continue # Check for",
"os.makedirs(_OUTPUT_GRAPH_DIR) WriteGrahDumps(graph_dumps, options.threshold, options.size_threshold) WriteIndex(graph_dumps) WriteHTML() if __name__ == '__main__':",
"size_threshold) graph.root = filename def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json')",
"== 'M': if event['name'] == 'process_name' and 'name' in event['args']:",
"remaining allocated objects tree. filename = 'process_%d_%s-objects.json' % (graph.pid, graph.heap)",
"= {} root['count'] = 0 root['size'] = 0 root['children'] =",
"start_trace: start_processes = FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes, filter_by_name, filter_by_labels) #",
"filter_by_name and process.name != filter_by_name: continue if (filter_by_labels and (not",
"len(leaks))) graph.leaks = leaks graph.leak_stackframes = len(leaks) for leak in",
"output.write(' \\\"children\\\": [') is_first = True for child_frame, child in",
"= None if start_trace: start_processes = FindMemoryDumps(start_trace) start_processes = FilterProcesses(start_processes,",
"objects tree. filename = 'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename =",
"end memory dumps. root = {} root['count'] = 0 root['size']",
"def WriteGrahDumps(graph_dumps, threshold, size_threshold): for graph in graph_dumps: # Dump",
"if not stack: root['count'] += count root['size'] += size if",
"os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant processes to be processed. processes",
"Main(): parser = argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output a flame",
"'t') def FindMemoryDumps(filename): processes = {} with OpenTraceFile(filename, 'r') as",
"dump. for pid, process in processes.items(): if not (process.allocators and",
"'.', output, threshold, size_threshold) graph.root = filename def WriteIndex(graph_dumps): output_filename",
"None self.version = None class Entry(object): def __init__(self): self.count =",
"entry.type = raw_type entry.stackframe = raw_stackframe entries.append(entry) # Resolve fields",
"and root['count'] > size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' % root['size']) output.write('",
"to be processed. processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels)",
"% root['count']) output.write(' \\\"children\\\": [') is_first = True for child_frame,",
"root['count_by_type'] = {} for entry in start_entries: if entry.type: IncrementHeapEntry(entry.stackframe,",
"os.path.pardir, 'tracing', 'third_party', 'd3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source,",
"(start_process.name == end_process.name and (start_process.name in ['Browser', 'GPU'] or start_process.labels",
"HTML page. source = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html')",
"threshold and root['count'] > size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",' % root['size'])",
"doing some post processing to extract the relevant fields. \"\"\"",
"os.path.join(_OUTPUT_GRAPH_DIR, filename) if graph.root: with open(output_filename, 'w') as output: DumpTree(graph.root,",
"stack_id, s in six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name'] = s['name']",
"for a detailed memory dump event. if not ((event['name'] ==",
"entry.count = raw_count entry.size = raw_size entry.type = raw_type entry.stackframe",
"OpenTraceFile(filename, 'r') as f: data = json.loads(f.read().decode('utf-8')) for event in",
"= FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes = None",
"DumpTree(graph.root, '.', output, threshold, size_threshold) graph.root = filename def WriteIndex(graph_dumps):",
"FindMemoryDumps(end_trace) end_processes = FilterProcesses(end_processes, filter_by_name, filter_by_labels) start_processes = None if",
"help='Output a flame graph based on stackframe allocations') parser.add_argument( '--threshold',",
"shutil import six from six.moves import zip _OUTPUT_DIR = 'output'",
"t if event['name'] == 'stackFrames': process.stackframes = {} for stack_id,",
"if filter_by_name and process.name != filter_by_name: continue if (filter_by_labels and",
"total_count root['size'] -= total_size for typename in root['count_by_type']: total_count_for_type =",
"in maps['strings']: process.strings[string['id']] = string['string'] for node in maps['nodes']: node_v1",
"memory dump. for pid, process in processes.items(): if not (process.allocators",
"in end_trace. Otherwise, counts objects present in end_trace, but not",
"in graph_dumps: # Dump the remaining allocated objects tree. filename",
"stackframe allocations') parser.add_argument( '--threshold', type=int, default=0, help='Objects threshold for being",
"'diff_heap_profiler.html') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'index.html') shutil.copyfile(source, destination) # Copy the",
"threshold for being a potential memory leak') parser.add_argument( '--filter-by-name', type=str,",
"process.types): del processes[pid] return processes def ResolveMemoryDumpFields(entries, stackframes, types): def",
"size_threshold) output.write(']') output.write('}') def GetEntries(heap, process): \"\"\" Returns all entries",
"and options.size_threshold == 0: options.threshold = 1000 if len(options.trace) ==",
"a flame graph based on stackframe allocations') parser.add_argument( '--threshold', type=int,",
"= None class GraphDump(object): def __init__(self): self.pid = None self.name",
"root['count'] -= total_count root['size'] -= total_size for typename in root['count_by_type']:",
"'d3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination) def Main():",
"def FindLeaks(root, stack, leaks, threshold, size_threshold): for frame in root['children']:",
"None self.types = {} self.strings = {} self.stackframes = {}",
"'parent' in s: new_stackframe['parent'] = int(s['parent']) process.stackframes[int(stack_id)] = new_stackframe #",
"being a potential memory leak') parser.add_argument( '--size-threshold', type=int, default=0, help='Size",
"dumps. root = {} root['count'] = 0 root['size'] = 0",
"= 0 new_node['size'] = 0 new_node['children'] = {} new_node['count_by_type'] =",
"into indexes ResolveMemoryDumpFields(entries, process.stackframes, process.types) return entries def FilterProcesses(processes, filter_by_name,",
"with name (i.e. Browser, Renderer, ...)') parser.add_argument( '--filter-by-labels', type=str, help='Only",
"frame, output, threshold, size_threshold): output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame) if",
"continue # Check for a memory dump V1. if u'heaps'",
"new_node IncrementHeapEntry(tail, count, size, typename, root['children'][top]) def CanonicalHeapEntries(root): total_count =",
"relevant fields. \"\"\" if not process: return [] entries =",
"(not process.labels or filter_by_labels not in process.labels)): continue remaining_processes[pid] =",
"process.name != filter_by_name: continue if (filter_by_labels and (not process.labels or",
"# Check for a memory dump V2. # See format:",
"entry.type: IncrementHeapEntry(entry.stackframe, - entry.count, - entry.size, entry.type, root) for entry",
"end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps = BuildGraphDumps(processes, options.threshold, options.size_threshold) WritePotentialLeaks(graph_dumps)",
"processes with matching labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match processes between",
"stackframes) entry.type = ResolveType(entry.type, types) def IncrementHeapEntry(stack, count, size, typename,",
"in relevant_pids: start_process = start_processes[pid] end_process = end_processes[pid] processes.append((start_process, end_process))",
"parser.add_argument( '--match-by-labels', action='store_true', help='Match processes between runs by labels') parser.add_argument(",
"# Retrieve the processes and the associated memory dump. end_processes",
"(heap, len(leaks))) graph.leaks = leaks graph.leak_stackframes = len(leaks) for leak",
"+ tail def ResolveType(type_id, types): return types[type_id] for entry in",
"process.version == 1: for raw_entry in process.allocators[heap]['entries']: # Cumulative sizes",
"raw_entries: entry = Entry() entry.count = raw_count entry.size = raw_size",
"k['size']) if leaks: print(' %s: %d potential leaks found.' %",
"== 'typeNames': process.types = {} for type_id, t in six.iteritems(event['args']['typeNames']):",
"first memory dump. if not process.allocators: process.version = 1 process.allocators",
"len(options.trace) == 1: end_trace = options.trace[0] start_trace = None else:",
"if not process.allocators: dump = event['args']['dumps'] process.version = 2 process.allocators",
"new_node = {} new_node['count'] = 0 new_node['size'] = 0 new_node['children']",
"end_process.name else '' labels = end_process.labels if end_process.labels else ''",
"be processed. processes = FindRelevantProcesses(start_trace, end_trace, options.filter_by_name, options.filter_by_labels, options.match_by_labels) graph_dumps",
"for child_frame, child in root['children'].items(): if is_first: is_first = False",
"if not start_processes: # Only keep end-processes. for _, end_process",
"= process.strings[t['name_sid']] # Get the first memory dump. if not",
"keep processes with matching labels') parser.add_argument( '--match-by-labels', action='store_true', help='Match processes",
"graph.leaks = leaks graph.leak_stackframes = len(leaks) for leak in leaks:",
"BuildGraphDumps(processes, threshold, size_threshold): \"\"\" Build graph for a sequence of",
"# Cumulative sizes and types are skipped. see: # https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294",
"not stackframe are # available. if entry.stackframe not in stackframes:",
"entry.size, entry.type, root) for entry in end_entries: if entry.type: IncrementHeapEntry(entry.stackframe,",
"ResolveMemoryDumpFields(entries, stackframes, types): def ResolveStackTrace(stack_id, stackframes): stackframe = stackframes[stack_id] tail",
"pid not in processes: processes[pid] = Process() processes[pid].pid = pid",
"= '' self.leak_stackframes = 0 self.leak_objects = 0 def OpenTraceFile(file_path,",
"process.stackframes, process.types) return entries def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes =",
"= len(leaks) for leak in leaks: graph.leak_objects += leak['count'] return",
"end_processes[pid] processes.append((start_process, end_process)) return processes def BuildGraphDumps(processes, threshold, size_threshold): \"\"\"",
"print('Process[%d] %s: %s' % (pid, name, labels)) for heap in",
"in graph_dumps: if graph.leaks: filename = 'process_%d_%s-leaks.json' % (graph.pid, graph.heap)",
"processes = {} with OpenTraceFile(filename, 'r') as f: data =",
"0 total_size = 0 for child in six.itervalues(root['children']): total_count +=",
"entry.type: IncrementHeapEntry(entry.stackframe, entry.count, entry.size, entry.type, root) CanonicalHeapEntries(root) graph.root = root",
"root['children']: FindLeaks(root['children'][frame], [frame] + stack, leaks, threshold, size_threshold) if root['count']",
"FindMemoryDumps(filename): processes = {} with OpenTraceFile(filename, 'r') as f: data",
"in six.iteritems(event['args']['stackFrames']): new_stackframe = {} new_stackframe['name'] = s['name'] if 'parent'",
"node: node_v1['parent'] = node['parent'] process.stackframes[node['id']] = node_v1 for t in",
"# See format: [chromium] src/base/trace_event/heap_profiler_event_writer.h if u'heaps_v2' in event['args']['dumps']: #",
"shutil.copyfile(source, destination) # Copy the D3 library file. source =",
"graph = GraphDump() graph.pid = pid graph.name = name graph.labels",
"size_threshold) leaks.sort(reverse=True, key=lambda k: k['size']) if leaks: print(' %s: %d",
"filename = 'process_%d_%s-objects.json' % (graph.pid, graph.heap) output_filename = os.path.join(_OUTPUT_GRAPH_DIR, filename)",
"stack[-1] tail = stack[:-1] if top not in root['children']: new_node",
"entries def FilterProcesses(processes, filter_by_name, filter_by_labels): remaining_processes = {} for pid,",
"'tracing', 'third_party', 'd3', 'd3.min.js') destination = os.path.join(_OUTPUT_GRAPH_DIR, 'd3.min.js') shutil.copyfile(source, destination)",
"+= leak['count'] return graph_dumps def WritePotentialLeaks(graph_dumps): for graph in graph_dumps:",
"# Processes are paired based on name/labels. for _, end_process",
"= filename def WriteIndex(graph_dumps): output_filename = os.path.join(_OUTPUT_GRAPH_DIR, 'index.json') with open(output_filename,",
"graph.leak_stackframes, 'objects leaked': graph.leak_objects, } for graph in graph_dumps], output)",
"output.write('\\n{ \\\"name\\\": \\\"%s\\\",' % frame) if root['count'] > threshold and",
"DumpTree(child, child_frame, output, threshold, size_threshold) output.write(']') output.write('}') def GetEntries(heap, process):",
"end_process) in processes: pid = end_process.pid name = end_process.name if",
"raw_type entry.stackframe = raw_stackframe entries.append(entry) # Resolve fields by looking",
"child['count'] total_size += child['size'] root['count'] -= total_count root['size'] -= total_size",
"match_by_labels: # Processes are paired based on name/labels. for _,",
"node_v1['parent'] = node['parent'] process.stackframes[node['id']] = node_v1 for t in maps['types']:",
"stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes) name = stackframe['name'].replace('\\r', '').replace('\\n', '')",
"(18446744073709551615L) when not stackframe are # available. if entry.stackframe not",
"for graph in graph_dumps: if graph.leaks: filename = 'process_%d_%s-leaks.json' %",
"processes to be compared. processes = [] if not start_processes:",
"in root['children'].items(): if is_first: is_first = False else: output.write(',') DumpTree(child,",
"memory dump. if not process.allocators: process.version = 1 process.allocators =",
"end_process.name and (start_process.name in ['Browser', 'GPU'] or start_process.labels == end_process.labels)):",
"if not process: return [] entries = [] if process.version",
"'--filter-by-name', type=str, help='Only keep processes with name (i.e. Browser, Renderer,",
"end_trace = options.trace[1] if not os.path.exists(_OUTPUT_DIR): os.makedirs(_OUTPUT_DIR) # Find relevant",
"size_threshold: leaks.append({'count': root['count'], 'size': root['size'], 'count_by_type': root['count_by_type'], 'stackframes': stack}) def",
"{} with OpenTraceFile(filename, 'r') as f: data = json.loads(f.read().decode('utf-8')) for",
"end_process.labels if end_process.labels else '' print('Process[%d] %s: %s' % (pid,",
"graph.heap, 'name': graph.name, 'labels': graph.labels, 'objects': graph.root, 'potential leaks': graph.leak_stackframes,",
"event['args']['dumps'] process.version = 2 process.allocators = dump['heaps_v2']['allocators'] # Remove processes",
"raw_size, raw_type, raw_stackframe) in raw_entries: entry = Entry() entry.count =",
"None self.root = '' self.leaks = '' self.leak_stackframes = 0",
"= Process() processes[pid].pid = pid process = processes[pid] # Retrieve",
"= 2 process.allocators = dump['heaps_v2']['allocators'] # Remove processes with incomplete",
"event['ph'] == 'M': if event['name'] == 'process_name' and 'name' in",
"or event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'): continue #",
"Build graph for a sequence of pair of processes. If",
"absolute_import from __future__ import print_function import argparse import gzip import",
"None, counts objects in end_trace. Otherwise, counts objects present in",
"= event['args']['dumps'] process.version = 2 process.allocators = dump['heaps_v2']['allocators'] # Remove",
"labels = end_process.labels if end_process.labels else '' print('Process[%d] %s: %s'",
"== 'periodic_interval' or event['name'] == 'explicitly_triggered') and event['args']['dumps']['level_of_detail'] == 'detailed'):",
"entry.stackframe = raw_stackframe entries.append(entry) # Resolve fields by looking into",
"\"\"\" graph_dumps = [] for (start_process, end_process) in processes: pid",
"+ stack, leaks, threshold, size_threshold) if root['count'] > threshold and",
"os.makedirs(_OUTPUT_DIR) # Find relevant processes to be processed. processes =",
"2: raw_entries = list(zip(process.allocators[heap]['counts'], process.allocators[heap]['sizes'], process.allocators[heap]['types'], process.allocators[heap]['nodes'])) for (raw_count, raw_size,",
"() if 'parent' in stackframe: tail = ResolveStackTrace(stackframe['parent'], stackframes) name",
"print(' %s: %d potential leaks found.' % (heap, len(leaks))) graph.leaks",
"root['count'] > threshold and root['count'] > size_threshold: output.write(' \\\"size\\\": \\\"%s\\\",'",
"argparse.ArgumentParser() parser.add_argument( '--flame-graph', action='store_true', help='Output a flame graph based on",
"parser.add_argument( '--filter-by-name', type=str, help='Only keep processes with name (i.e. Browser,",
"} for graph in graph_dumps], output) def WriteHTML(): # Copy",
"= {} self.strings = {} self.stackframes = {} self.allocators =",
"'--size-threshold', type=int, default=0, help='Size threshold for being a potential memory",
"https://chromium.googlesource.com/chromium/src/+/a990af190304be5bf38b120799c594df5a293518/base/trace_event/heap_profiler_heap_dump_writer.cc#294 if 'type' not in raw_entry or not raw_entry['bt']: continue"
] |
[
"--task, --raw, --bids_root.') bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq,",
"file') parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS compatible folder.')",
"parser.add_option('--raw', dest='raw_fname', help='path to the raw MEG file') parser.add_option('--bids_root', dest='bids_root',",
"help=\"whether to overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency",
"help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the MEG",
"dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the",
"compatible format') parser.add_option('--run', dest='run', help='run number for this dataset') parser.add_option('--acq',",
"specify arguments without flags. Found: \"{}\".\\n' .format(args)) if not all([opt.subject_id,",
"opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to specify at least",
"to the raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path of",
"# License: BSD (3-clause) import mne_bids from mne_bids import write_raw_bids,",
"Hz \" \"(e.g. 50 or 60). If unknown, pass None\")",
"(BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of the line noise in",
"get_optparser parser = get_optparser(__file__, usage=\"usage: %prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__)",
"the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name in BIDS",
"the MEG marker points') parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer",
"def run(): \"\"\"Run the raw_to_bids command.\"\"\" from mne.commands.utils import get_optparser",
"If unknown, pass None\") opt, args = parser.parse_args() if len(args)",
"--raw data.edf --bids_root new_path \"\"\" # Authors: <NAME> <<EMAIL>> #",
"data is based on') parser.add_option('--raw', dest='raw_fname', help='path to the raw",
"task the data is based on') parser.add_option('--raw', dest='raw_fname', help='path to",
"parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq',",
"all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to",
"parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path",
"unknown, pass None\") opt, args = parser.parse_args() if len(args) >",
"files to BIDS format. example usage: $ mne_bids raw_to_bids --subject_id",
"bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield",
"--raw, --bids_root.') bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task,",
"rest --raw data.edf --bids_root new_path \"\"\" # Authors: <NAME> <<EMAIL>>",
"arguments without flags. Found: \"{}\".\\n' .format(args)) if not all([opt.subject_id, opt.task,",
"--subject_id sub01 --task rest --raw data.edf --bids_root new_path \"\"\" #",
"BIDS compatible format') parser.add_option('--run', dest='run', help='run number for this dataset')",
"Found: \"{}\".\\n' .format(args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help()",
"import get_optparser parser = get_optparser(__file__, usage=\"usage: %prog options args\", prog_prefix='mne_bids',",
"noise in Hz \" \"(e.g. 50 or 60). If unknown,",
"--bids_root.') bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root)",
"parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to",
"to BIDS format. example usage: $ mne_bids raw_to_bids --subject_id sub01",
"= get_optparser(__file__, usage=\"usage: %prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id',",
"None: line_freq = None if opt.line_freq == \"None\" else opt.line_freq",
"(3-clause) import mne_bids from mne_bids import write_raw_bids, BIDSPath from mne_bids.read",
"= False if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw = _read_raw(opt.raw_fname,",
"to specify at least the' 'following: --subject_id, --task, --raw, --bids_root.')",
"electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not None: line_freq",
"or 60). If unknown, pass None\") opt, args = parser.parse_args()",
"hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not None: line_freq =",
"parser.error('Do not specify arguments without flags. Found: \"{}\".\\n' .format(args)) if",
"line_freq = None if opt.line_freq == \"None\" else opt.line_freq raw.info['line_freq']",
"\"\"\" # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #",
"parser.parse_args() if len(args) > 0: parser.print_help() parser.error('Do not specify arguments",
"help=('subject name in BIDS compatible format ' '(01, 02, etc.)'))",
"dest='hpi', help='path to the MEG marker points') parser.add_option('--electrode', dest='electrode', help='path",
"parser.add_option('--hsp', dest='hsp', help='path to headshape points') parser.add_option('--config', dest='config', help='path to",
"help='session name in BIDS compatible format') parser.add_option('--run', dest='run', help='run number",
"allow_maxshield = True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config,",
"50 or 60). If unknown, pass None\") opt, args =",
"not None: line_freq = None if opt.line_freq == \"None\" else",
"in BIDS compatible format ' '(01, 02, etc.)')) parser.add_option('--task', dest='task',",
"help=\"The frequency of the line noise in Hz \" \"(e.g.",
"parser.print_help() parser.error('Arguments missing. You need to specify at least the'",
"%prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in",
"BIDS compatible format ' '(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name",
"the raw_to_bids command.\"\"\" from mne.commands.utils import get_optparser parser = get_optparser(__file__,",
"digitizer points') parser.add_option('--hsp', dest='hsp', help='path to headshape points') parser.add_option('--config', dest='config',",
"Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD",
"if len(args) > 0: parser.print_help() parser.error('Do not specify arguments without",
"data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of the line noise",
"if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode,",
"License: BSD (3-clause) import mne_bids from mne_bids import write_raw_bids, BIDSPath",
"of the line noise in Hz \" \"(e.g. 50 or",
"to the MEG marker points') parser.add_option('--electrode', dest='electrode', help='path to head-native",
"# <NAME> <<EMAIL>> # # License: BSD (3-clause) import mne_bids",
"folder.') parser.add_option('--session_id', dest='session_id', help='session name in BIDS compatible format') parser.add_option('--run',",
"not specify arguments without flags. Found: \"{}\".\\n' .format(args)) if not",
"command.\"\"\" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage=\"usage: %prog",
"points') parser.add_option('--config', dest='config', help='path to the configuration file') parser.add_option('--overwrite', dest='overwrite',",
"overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of the",
"args = parser.parse_args() if len(args) > 0: parser.print_help() parser.error('Do not",
"path of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name",
"configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite existing data (BOOLEAN)\")",
"existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of the line",
"= _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is",
"head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path to headshape points') parser.add_option('--config',",
"<NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause)",
"None if opt.line_freq == \"None\" else opt.line_freq raw.info['line_freq'] = line_freq",
"$ mne_bids raw_to_bids --subject_id sub01 --task rest --raw data.edf --bids_root",
"options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS",
"run(): \"\"\"Run the raw_to_bids command.\"\"\" from mne.commands.utils import get_optparser parser",
"import mne_bids from mne_bids import write_raw_bids, BIDSPath from mne_bids.read import",
"dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for this dataset') parser.add_option('--events_data', dest='events_data',",
"parser.add_option('--hpi', dest='hpi', help='path to the MEG marker points') parser.add_option('--electrode', dest='electrode',",
"from mne_bids import write_raw_bids, BIDSPath from mne_bids.read import _read_raw def",
"raw_to_bids --subject_id sub01 --task rest --raw data.edf --bids_root new_path \"\"\"",
"help='path to headshape points') parser.add_option('--config', dest='config', help='path to the configuration",
"for this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for this dataset')",
"usage=\"usage: %prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name",
"parameter for this dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id',",
"help='The path of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session",
"of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name in",
"dest='electrode', help='path to head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path to",
"without flags. Found: \"{}\".\\n' .format(args)) if not all([opt.subject_id, opt.task, opt.raw_fname,",
"missing. You need to specify at least the' 'following: --subject_id,",
"mne_bids from mne_bids import write_raw_bids, BIDSPath from mne_bids.read import _read_raw",
"(events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path",
"import write_raw_bids, BIDSPath from mne_bids.read import _read_raw def run(): \"\"\"Run",
"'(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name of the task the",
"parser = get_optparser(__file__, usage=\"usage: %prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id',",
"opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to specify at",
"dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the MEG marker points')",
"parser.add_option('--acq', dest='acq', help='acquisition parameter for this dataset') parser.add_option('--events_data', dest='events_data', help='events",
"# # License: BSD (3-clause) import mne_bids from mne_bids import",
"BIDS format. example usage: $ mne_bids raw_to_bids --subject_id sub01 --task",
"number for this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for this",
"--subject_id, --task, --raw, --bids_root.') bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run,",
"subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False if",
"allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw =",
"You need to specify at least the' 'following: --subject_id, --task,",
"help='path to the configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite",
"dest='overwrite', help=\"whether to overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The",
"False if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw = _read_raw(opt.raw_fname, hpi=opt.hpi,",
"flags. Found: \"{}\".\\n' .format(args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]):",
"not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need",
"hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not None:",
"from mne_bids.read import _read_raw def run(): \"\"\"Run the raw_to_bids command.\"\"\"",
"usage: $ mne_bids raw_to_bids --subject_id sub01 --task rest --raw data.edf",
"opt, args = parser.parse_args() if len(args) > 0: parser.print_help() parser.error('Do",
"bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True) if __name__ == '__main__': run()",
"line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True) if __name__ ==",
"raw files to BIDS format. example usage: $ mne_bids raw_to_bids",
"help='path to the raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path",
"mne_bids import write_raw_bids, BIDSPath from mne_bids.read import _read_raw def run():",
"_read_raw def run(): \"\"\"Run the raw_to_bids command.\"\"\" from mne.commands.utils import",
"opt.raw_fname.endswith('.fif'): allow_maxshield = True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp,",
"\"None\" else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data,",
"dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid')",
"raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq",
"<<EMAIL>> # # License: BSD (3-clause) import mne_bids from mne_bids",
"help='path to head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path to headshape",
"specify at least the' 'following: --subject_id, --task, --raw, --bids_root.') bids_path",
"mne.commands.utils import get_optparser parser = get_optparser(__file__, usage=\"usage: %prog options args\",",
"= None if opt.line_freq == \"None\" else opt.line_freq raw.info['line_freq'] =",
"at least the' 'following: --subject_id, --task, --raw, --bids_root.') bids_path =",
"parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of the line noise in Hz",
"02, etc.)')) parser.add_option('--task', dest='task', help='name of the task the data",
"in Hz \" \"(e.g. 50 or 60). If unknown, pass",
"BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False",
"\"{}\".\\n' .format(args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments",
"version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS compatible format '",
"parser.add_option('--run', dest='run', help='run number for this dataset') parser.add_option('--acq', dest='acq', help='acquisition",
"BSD (3-clause) import mne_bids from mne_bids import write_raw_bids, BIDSPath from",
"the' 'following: --subject_id, --task, --raw, --bids_root.') bids_path = BIDSPath( subject=opt.subject_id,",
"metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the MEG marker points') parser.add_option('--electrode',",
"dest='hsp', help='path to headshape points') parser.add_option('--config', dest='config', help='path to the",
"dest='line_freq', help=\"The frequency of the line noise in Hz \"",
"= True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield)",
"the raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path of the",
"based on') parser.add_option('--raw', dest='raw_fname', help='path to the raw MEG file')",
"compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name in BIDS compatible format')",
"the line noise in Hz \" \"(e.g. 50 or 60).",
"write_raw_bids, BIDSPath from mne_bids.read import _read_raw def run(): \"\"\"Run the",
"format. example usage: $ mne_bids raw_to_bids --subject_id sub01 --task rest",
"to the configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite existing",
"dest='subject_id', help=('subject name in BIDS compatible format ' '(01, 02,",
"root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw",
"BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name in BIDS compatible",
"= line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True) if __name__",
"help='run number for this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for",
"'following: --subject_id, --task, --raw, --bids_root.') bids_path = BIDSPath( subject=opt.subject_id, session=opt.session_id,",
"on') parser.add_option('--raw', dest='raw_fname', help='path to the raw MEG file') parser.add_option('--bids_root',",
"if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You",
"example usage: $ mne_bids raw_to_bids --subject_id sub01 --task rest --raw",
"id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the MEG marker",
"config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not None: line_freq = None",
"parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict',",
"least the' 'following: --subject_id, --task, --raw, --bids_root.') bids_path = BIDSPath(",
"_read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not",
"dest='run', help='run number for this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter",
"opt.line_freq == \"None\" else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path,",
"session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'):",
"parser.add_option('--config', dest='config', help='path to the configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether",
"MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS compatible",
"to headshape points') parser.add_option('--config', dest='config', help='path to the configuration file')",
"parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS compatible folder.') parser.add_option('--session_id',",
"parser.print_help() parser.error('Do not specify arguments without flags. Found: \"{}\".\\n' .format(args))",
"parser.add_option('--task', dest='task', help='name of the task the data is based",
"help='name of the task the data is based on') parser.add_option('--raw',",
"is based on') parser.add_option('--raw', dest='raw_fname', help='path to the raw MEG",
"True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if",
".format(args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing.",
"from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage=\"usage: %prog options",
"write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True) if __name__ == '__main__':",
"sub01 --task rest --raw data.edf --bids_root new_path \"\"\" # Authors:",
"to head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path to headshape points')",
"help='path to the MEG marker points') parser.add_option('--electrode', dest='electrode', help='path to",
"--task rest --raw data.edf --bids_root new_path \"\"\" # Authors: <NAME>",
"parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS compatible format ' '(01,",
"headshape points') parser.add_option('--config', dest='config', help='path to the configuration file') parser.add_option('--overwrite',",
"raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS",
"raw_to_bids command.\"\"\" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage=\"usage:",
"file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi',",
"name in BIDS compatible format ' '(01, 02, etc.)')) parser.add_option('--task',",
"file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq',",
"import _read_raw def run(): \"\"\"Run the raw_to_bids command.\"\"\" from mne.commands.utils",
"len(args) > 0: parser.print_help() parser.error('Do not specify arguments without flags.",
"format') parser.add_option('--run', dest='run', help='run number for this dataset') parser.add_option('--acq', dest='acq',",
"dest='config', help='path to the configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to",
"\"\"\"Run the raw_to_bids command.\"\"\" from mne.commands.utils import get_optparser parser =",
"etc.)')) parser.add_option('--task', dest='task', help='name of the task the data is",
"help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi',",
"opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to specify",
"\"(e.g. 50 or 60). If unknown, pass None\") opt, args",
"parser.add_option('--session_id', dest='session_id', help='session name in BIDS compatible format') parser.add_option('--run', dest='run',",
"compatible format ' '(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name of",
"to overwrite existing data (BOOLEAN)\") parser.add_option('--line_freq', dest='line_freq', help=\"The frequency of",
"args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS compatible",
"raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True) if",
"60). If unknown, pass None\") opt, args = parser.parse_args() if",
"opt.line_freq is not None: line_freq = None if opt.line_freq ==",
"data.edf --bids_root new_path \"\"\" # Authors: <NAME> <<EMAIL>> # <NAME>",
"mne_bids.read import _read_raw def run(): \"\"\"Run the raw_to_bids command.\"\"\" from",
"acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield =",
"points') parser.add_option('--hsp', dest='hsp', help='path to headshape points') parser.add_option('--config', dest='config', help='path",
"line noise in Hz \" \"(e.g. 50 or 60). If",
"help='acquisition parameter for this dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)')",
"MEG marker points') parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer points')",
"<NAME> <<EMAIL>> # # License: BSD (3-clause) import mne_bids from",
"dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id",
"if opt.line_freq is not None: line_freq = None if opt.line_freq",
"# Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License:",
"this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for this dataset') parser.add_option('--events_data',",
"points') parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer points') parser.add_option('--hsp', dest='hsp',",
"' '(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name of the task",
"need to specify at least the' 'following: --subject_id, --task, --raw,",
"for this dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id',",
"pass None\") opt, args = parser.parse_args() if len(args) > 0:",
"task=opt.task, root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield = True",
"dest='task', help='name of the task the data is based on')",
"the task the data is based on') parser.add_option('--raw', dest='raw_fname', help='path",
"if opt.line_freq == \"None\" else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw,",
"prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS compatible format",
"marker points') parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer points') parser.add_option('--hsp',",
"= BIDSPath( subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield =",
"None\") opt, args = parser.parse_args() if len(args) > 0: parser.print_help()",
"mne_bids raw_to_bids --subject_id sub01 --task rest --raw data.edf --bids_root new_path",
"<<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause) import",
"BIDSPath from mne_bids.read import _read_raw def run(): \"\"\"Run the raw_to_bids",
"of the task the data is based on') parser.add_option('--raw', dest='raw_fname',",
"run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield",
"name in BIDS compatible format') parser.add_option('--run', dest='run', help='run number for",
"frequency of the line noise in Hz \" \"(e.g. 50",
"dest='acq', help='acquisition parameter for this dataset') parser.add_option('--events_data', dest='events_data', help='events file",
"== \"None\" else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id,",
"the configuration file') parser.add_option('--overwrite', dest='overwrite', help=\"whether to overwrite existing data",
"> 0: parser.print_help() parser.error('Do not specify arguments without flags. Found:",
"dest='session_id', help='session name in BIDS compatible format') parser.add_option('--run', dest='run', help='run",
"in BIDS compatible format') parser.add_option('--run', dest='run', help='run number for this",
"\" \"(e.g. 50 or 60). If unknown, pass None\") opt,",
"the data is based on') parser.add_option('--raw', dest='raw_fname', help='path to the",
"allow_maxshield=allow_maxshield) if opt.line_freq is not None: line_freq = None if",
"--bids_root new_path \"\"\" # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>>",
"is not None: line_freq = None if opt.line_freq == \"None\"",
"format ' '(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name of the",
"dest='raw_fname', help='path to the raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The",
"\"\"\"Write raw files to BIDS format. example usage: $ mne_bids",
"parser.error('Arguments missing. You need to specify at least the' 'following:",
"dest='bids_root', help='The path of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id',",
"this dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event",
"0: parser.print_help() parser.error('Do not specify arguments without flags. Found: \"{}\".\\n'",
"= parser.parse_args() if len(args) > 0: parser.print_help() parser.error('Do not specify",
"get_optparser(__file__, usage=\"usage: %prog options args\", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject",
"new_path \"\"\" # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> #",
"else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite,",
"opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True)"
] |
[
"+ self.second) def subtract(self): print(self.first - self.second) def multiply(self): print(self.first",
"\")) chooseop = 1 calc=Calculations(a, b) while (chooseop == 1)",
"print(self.first / self.second) def main(): print(\"Calculator has started\") while True:",
"1) & (chooseop != 2) & (chooseop != 3) &",
"addition, 2 for subtraction, 3 for multiplication and 4 for",
"number \")) b = float(input(\"Enter second number \")) chooseop =",
"division \")) print(chooseop) if chooseop == 1: calc.add() break elif",
"!= 3) & (chooseop != 4): print(\"Invalid operation number\") if",
"2) | (chooseop == 3) | (chooseop == 4): chooseop",
"| (chooseop == 3) | (chooseop == 4): chooseop =",
"by zero\") else: print(self.first / self.second) def main(): print(\"Calculator has",
"def main(): print(\"Calculator has started\") while True: a = float(input(\"Enter",
"!= 2) & (chooseop != 3) & (chooseop != 4):",
"else: print(self.first / self.second) def main(): print(\"Calculator has started\") while",
"divide(self): if second == 0: print(\"Can't divide by zero\") else:",
"(chooseop == 2) | (chooseop == 3) | (chooseop ==",
"float(input(\"Enter first number \")) b = float(input(\"Enter second number \"))",
"== 2) | (chooseop == 3) | (chooseop == 4):",
"| (chooseop == 4): chooseop = int(input(\"Enter 1 for addition,",
"3 for multiplication and 4 for division \")) print(chooseop) if",
"main(): print(\"Calculator has started\") while True: a = float(input(\"Enter first",
"if second == 0: print(\"Can't divide by zero\") else: print(self.first",
"second == 0: print(\"Can't divide by zero\") else: print(self.first /",
"for subtraction, 3 for multiplication and 4 for division \"))",
"\")) print(chooseop) if chooseop == 1: calc.add() break elif chooseop",
"self.second) def subtract(self): print(self.first - self.second) def multiply(self): print(self.first *",
"chooseop == 2: calc.subtract() break elif chooseop == 3: calc.multiply()",
"zero\") else: print(self.first / self.second) def main(): print(\"Calculator has started\")",
"chooseop == 1: calc.add() break elif chooseop == 2: calc.subtract()",
"self.second) def divide(self): if second == 0: print(\"Can't divide by",
"chooseop == 4: calc.divide() break elif (chooseop != 1) &",
"float(input(\"Enter second number \")) chooseop = 1 calc=Calculations(a, b) while",
"def subtract(self): print(self.first - self.second) def multiply(self): print(self.first * self.second)",
"while (chooseop == 1) | (chooseop == 2) | (chooseop",
"print(self.first + self.second) def subtract(self): print(self.first - self.second) def multiply(self):",
"first self.second = second def add(self): print(self.first + self.second) def",
"self.first = first self.second = second def add(self): print(self.first +",
"print(\"Calculator has started\") while True: a = float(input(\"Enter first number",
"break elif chooseop == 2: calc.subtract() break elif chooseop ==",
"= float(input(\"Enter second number \")) chooseop = 1 calc=Calculations(a, b)",
"number \")) chooseop = 1 calc=Calculations(a, b) while (chooseop ==",
"started\") while True: a = float(input(\"Enter first number \")) b",
"\")) b = float(input(\"Enter second number \")) chooseop = 1",
"(chooseop == 3) | (chooseop == 4): chooseop = int(input(\"Enter",
"self.second) def main(): print(\"Calculator has started\") while True: a =",
"while True: a = float(input(\"Enter first number \")) b =",
"add(self): print(self.first + self.second) def subtract(self): print(self.first - self.second) def",
"calc.divide() break elif (chooseop != 1) & (chooseop != 2)",
"break elif chooseop == 4: calc.divide() break elif (chooseop !=",
"(chooseop != 2) & (chooseop != 3) & (chooseop !=",
"chooseop == 3: calc.multiply() break elif chooseop == 4: calc.divide()",
"def add(self): print(self.first + self.second) def subtract(self): print(self.first - self.second)",
"| (chooseop == 2) | (chooseop == 3) | (chooseop",
"= float(input(\"Enter first number \")) b = float(input(\"Enter second number",
"chooseop = 1 calc=Calculations(a, b) while (chooseop == 1) |",
"(chooseop == 4): chooseop = int(input(\"Enter 1 for addition, 2",
"first, second): self.first = first self.second = second def add(self):",
"print(self.first - self.second) def multiply(self): print(self.first * self.second) def divide(self):",
"True: a = float(input(\"Enter first number \")) b = float(input(\"Enter",
"subtract(self): print(self.first - self.second) def multiply(self): print(self.first * self.second) def",
"<gh_stars>0 class Calculations: def __init__(self, first, second): self.first = first",
"(chooseop != 4): print(\"Invalid operation number\") if __name__ == \"__main__\":",
"chooseop = int(input(\"Enter 1 for addition, 2 for subtraction, 3",
"== 3) | (chooseop == 4): chooseop = int(input(\"Enter 1",
"for addition, 2 for subtraction, 3 for multiplication and 4",
"calc=Calculations(a, b) while (chooseop == 1) | (chooseop == 2)",
"= first self.second = second def add(self): print(self.first + self.second)",
"!= 1) & (chooseop != 2) & (chooseop != 3)",
"self.second = second def add(self): print(self.first + self.second) def subtract(self):",
"print(\"Can't divide by zero\") else: print(self.first / self.second) def main():",
"int(input(\"Enter 1 for addition, 2 for subtraction, 3 for multiplication",
"2: calc.subtract() break elif chooseop == 3: calc.multiply() break elif",
"break elif (chooseop != 1) & (chooseop != 2) &",
"& (chooseop != 2) & (chooseop != 3) & (chooseop",
"calc.add() break elif chooseop == 2: calc.subtract() break elif chooseop",
"elif chooseop == 4: calc.divide() break elif (chooseop != 1)",
"for division \")) print(chooseop) if chooseop == 1: calc.add() break",
"& (chooseop != 3) & (chooseop != 4): print(\"Invalid operation",
"def divide(self): if second == 0: print(\"Can't divide by zero\")",
"b = float(input(\"Enter second number \")) chooseop = 1 calc=Calculations(a,",
"!= 4): print(\"Invalid operation number\") if __name__ == \"__main__\": main()",
"1) | (chooseop == 2) | (chooseop == 3) |",
"* self.second) def divide(self): if second == 0: print(\"Can't divide",
"def __init__(self, first, second): self.first = first self.second = second",
"class Calculations: def __init__(self, first, second): self.first = first self.second",
"== 2: calc.subtract() break elif chooseop == 3: calc.multiply() break",
"a = float(input(\"Enter first number \")) b = float(input(\"Enter second",
"second): self.first = first self.second = second def add(self): print(self.first",
"calc.subtract() break elif chooseop == 3: calc.multiply() break elif chooseop",
"2) & (chooseop != 3) & (chooseop != 4): print(\"Invalid",
"second def add(self): print(self.first + self.second) def subtract(self): print(self.first -",
"== 4): chooseop = int(input(\"Enter 1 for addition, 2 for",
"4 for division \")) print(chooseop) if chooseop == 1: calc.add()",
"1 calc=Calculations(a, b) while (chooseop == 1) | (chooseop ==",
"= 1 calc=Calculations(a, b) while (chooseop == 1) | (chooseop",
"& (chooseop != 4): print(\"Invalid operation number\") if __name__ ==",
"second number \")) chooseop = 1 calc=Calculations(a, b) while (chooseop",
"(chooseop != 1) & (chooseop != 2) & (chooseop !=",
"1 for addition, 2 for subtraction, 3 for multiplication and",
"print(chooseop) if chooseop == 1: calc.add() break elif chooseop ==",
"multiply(self): print(self.first * self.second) def divide(self): if second == 0:",
"1: calc.add() break elif chooseop == 2: calc.subtract() break elif",
"== 0: print(\"Can't divide by zero\") else: print(self.first / self.second)",
"== 4: calc.divide() break elif (chooseop != 1) & (chooseop",
"b) while (chooseop == 1) | (chooseop == 2) |",
"for multiplication and 4 for division \")) print(chooseop) if chooseop",
"(chooseop == 1) | (chooseop == 2) | (chooseop ==",
"/ self.second) def main(): print(\"Calculator has started\") while True: a",
"4): chooseop = int(input(\"Enter 1 for addition, 2 for subtraction,",
"0: print(\"Can't divide by zero\") else: print(self.first / self.second) def",
"3) | (chooseop == 4): chooseop = int(input(\"Enter 1 for",
"4: calc.divide() break elif (chooseop != 1) & (chooseop !=",
"elif chooseop == 2: calc.subtract() break elif chooseop == 3:",
"calc.multiply() break elif chooseop == 4: calc.divide() break elif (chooseop",
"subtraction, 3 for multiplication and 4 for division \")) print(chooseop)",
"def multiply(self): print(self.first * self.second) def divide(self): if second ==",
"(chooseop != 3) & (chooseop != 4): print(\"Invalid operation number\")",
"has started\") while True: a = float(input(\"Enter first number \"))",
"self.second) def multiply(self): print(self.first * self.second) def divide(self): if second",
"- self.second) def multiply(self): print(self.first * self.second) def divide(self): if",
"first number \")) b = float(input(\"Enter second number \")) chooseop",
"== 1) | (chooseop == 2) | (chooseop == 3)",
"__init__(self, first, second): self.first = first self.second = second def",
"elif chooseop == 3: calc.multiply() break elif chooseop == 4:",
"break elif chooseop == 3: calc.multiply() break elif chooseop ==",
"= second def add(self): print(self.first + self.second) def subtract(self): print(self.first",
"3: calc.multiply() break elif chooseop == 4: calc.divide() break elif",
"and 4 for division \")) print(chooseop) if chooseop == 1:",
"multiplication and 4 for division \")) print(chooseop) if chooseop ==",
"divide by zero\") else: print(self.first / self.second) def main(): print(\"Calculator",
"Calculations: def __init__(self, first, second): self.first = first self.second =",
"if chooseop == 1: calc.add() break elif chooseop == 2:",
"== 1: calc.add() break elif chooseop == 2: calc.subtract() break",
"== 3: calc.multiply() break elif chooseop == 4: calc.divide() break",
"2 for subtraction, 3 for multiplication and 4 for division",
"elif (chooseop != 1) & (chooseop != 2) & (chooseop",
"print(self.first * self.second) def divide(self): if second == 0: print(\"Can't",
"3) & (chooseop != 4): print(\"Invalid operation number\") if __name__",
"= int(input(\"Enter 1 for addition, 2 for subtraction, 3 for"
] |
[
"collections import deque def solution(A, K): # write your code",
"rotate the deque in positive K steps Convert the deque",
"the rotate() method the rotate the deque in positive K",
"a given number of steps K. Covert the array to",
"a deque Apply the rotate() method the rotate the deque",
"message\") ''' Rotate an array A to the right by",
"given number of steps K. Covert the array to a",
"to the right by a given number of steps K.",
"method the rotate the deque in positive K steps Convert",
"# write your code in Python 3.6 deq_A = deque(A)",
"can write to stdout for debugging purposes, e.g. # print(\"this",
"# print(\"this is a debug message\") ''' Rotate an array",
"debug message\") ''' Rotate an array A to the right",
"an array A to the right by a given number",
"steps K. Covert the array to a deque Apply the",
"K. Covert the array to a deque Apply the rotate()",
"import deque def solution(A, K): # write your code in",
"debugging purposes, e.g. # print(\"this is a debug message\") '''",
"to array ''' from collections import deque def solution(A, K):",
"array A to the right by a given number of",
"from collections import deque def solution(A, K): # write your",
"by a given number of steps K. Covert the array",
"''' from collections import deque def solution(A, K): # write",
"deque def solution(A, K): # write your code in Python",
"write your code in Python 3.6 deq_A = deque(A) deq_A.rotate(K)",
"<reponame>Jeans212/codility-dev-training # you can write to stdout for debugging purposes,",
"Apply the rotate() method the rotate the deque in positive",
"steps Convert the deque to array ''' from collections import",
"positive K steps Convert the deque to array ''' from",
"write to stdout for debugging purposes, e.g. # print(\"this is",
"deque to array ''' from collections import deque def solution(A,",
"in positive K steps Convert the deque to array '''",
"Covert the array to a deque Apply the rotate() method",
"deque in positive K steps Convert the deque to array",
"e.g. # print(\"this is a debug message\") ''' Rotate an",
"stdout for debugging purposes, e.g. # print(\"this is a debug",
"rotate() method the rotate the deque in positive K steps",
"the rotate the deque in positive K steps Convert the",
"deque Apply the rotate() method the rotate the deque in",
"for debugging purposes, e.g. # print(\"this is a debug message\")",
"K steps Convert the deque to array ''' from collections",
"''' Rotate an array A to the right by a",
"number of steps K. Covert the array to a deque",
"A to the right by a given number of steps",
"Rotate an array A to the right by a given",
"# you can write to stdout for debugging purposes, e.g.",
"print(\"this is a debug message\") ''' Rotate an array A",
"array to a deque Apply the rotate() method the rotate",
"purposes, e.g. # print(\"this is a debug message\") ''' Rotate",
"of steps K. Covert the array to a deque Apply",
"the deque in positive K steps Convert the deque to",
"the deque to array ''' from collections import deque def",
"to stdout for debugging purposes, e.g. # print(\"this is a",
"you can write to stdout for debugging purposes, e.g. #",
"the right by a given number of steps K. Covert",
"Convert the deque to array ''' from collections import deque",
"your code in Python 3.6 deq_A = deque(A) deq_A.rotate(K) return",
"code in Python 3.6 deq_A = deque(A) deq_A.rotate(K) return list(deq_A)",
"to a deque Apply the rotate() method the rotate the",
"K): # write your code in Python 3.6 deq_A =",
"is a debug message\") ''' Rotate an array A to",
"def solution(A, K): # write your code in Python 3.6",
"solution(A, K): # write your code in Python 3.6 deq_A",
"array ''' from collections import deque def solution(A, K): #",
"the array to a deque Apply the rotate() method the",
"right by a given number of steps K. Covert the",
"a debug message\") ''' Rotate an array A to the"
] |
[
"= parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] = [",
"self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\" Test State.reset(). \"\"\"",
"'a') with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'),",
"parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config",
"\"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks,",
"1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r =",
"exclude parent tags. \"\"\" test = \"\"\" Some +test+ and",
"<NAME> (the original version) License: BSD (see LICENSE.md for details).",
"to create temp config files. \"\"\" if not isinstance(config, markdown.util.string_type):",
") def testProsessingInstruction(self): \"\"\" Test serialization of ProcessignInstruction. \"\"\" pi",
"\"\"\" Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\"",
"<NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright 2007-2018 The",
"output=outfile) with os.fdopen(outfd, 'r') as fp: output = fp.read() self.assertEqual(output,",
"extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'),",
"markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\" Test QName escaping.",
"'a', 20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2)",
"del r[0] # TODO: restore this when deprecated __del__ is",
"em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual(",
"WARNING, CRITICAL import yaml import tempfile from io import BytesIO",
"= markdown.util.Registry() # Add first item r.add('c', Item('c'), '_begin') self.assertEqual(list(r),",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError): del r[0] # TODO:",
"mn = markdown.util.etree.SubElement(msup, 'mn') mn.text = '2' ann = markdown.util.etree.SubElement(sem,",
"def testEntryPointExtension(self): \"\"\" Test Extension loading with an entry point.",
"def __repr__(self): return repr(self.data) def __eq__(self, other): return self.data ==",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b', 'a']) def",
"['b', 'c', 'a']) def testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted, False)",
"__del__ is removed. # with self.assertRaises(TypeError): # del r['a'] #",
"\"\"\" Test that last <br> in tree has a new",
"\"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test failure of",
"'block') sem = markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem, 'msup') mi",
"self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\" Test that an extension",
"'b', 'c']) # Add before non-first item r.add('a1', Item('a1'), '<b')",
"\"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class",
"'lazy_ol': True, 'extensions': [], 'extension_configs': {}, } self.tempfile = ''",
"Test failure on bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def",
"\"\"\" Tests of the State class for BlockParser. \"\"\" def",
"self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def testReset(self): \"\"\"",
"when deprecated __setitem__ is removed. # with self.assertRaises(TypeError): # r['a']",
"markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test that",
"point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test Extension loading with",
"not isinstance(config, markdown.util.string_type): # convert to string config = yaml.dump(config)",
"Test that the base Extension class will raise NotImplemented. \"\"\"",
"class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of the Markdown class. \"\"\"",
"\"\"\" Test that an extension can exclude parent tags when",
"as it replaces the module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version', dir_attr)",
"def __eq__(self, other): return self.data == other class RegistryTests(unittest.TestCase): \"\"\"",
"div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' )",
"'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r =",
"}, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } import json self.create_config_file(json.dumps(config))",
"the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w))",
"itself, we should certainly support any third party extensions which",
"testEncodingOption(self): options, logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options,",
"raised as errors warnings.simplefilter('error') def tearDown(self): # Reset warning behavior",
"def testBadQNameTag(self): \"\"\" Test serialization of QName with no tag.",
"def testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1)",
"loading a non Extension object as an extension. \"\"\" self.assertRaises(TypeError,",
"markdown's (x)html serializer). While markdown doesn't use ElementTree.Comment itself, we",
"back to default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test falure on",
"attribute. \"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div",
"# deregister non-existant item with strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1)",
"markdown.blockparser.State() def testBlankState(self): \"\"\" Test State when empty. \"\"\" self.assertEqual(self.state,",
"\"\"\" Test Extension loading with a class instance. \"\"\" from",
"'bar'] ) def testReset(self): \"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter,",
"span1.text = markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1, 'span') span2.text =",
"\"\"\" def fakeSerializer(elem): # Ignore input and return hardcoded output",
"<span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def assertParses(self,",
"'a1', 'b', 'c']) # Add after non-last item r.add('b1', Item('b1'),",
"inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def",
"'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo <&escaped>' p.set('hidden',",
"Test parsing of Command Line Interface Options. \"\"\" def setUp(self):",
"= markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase):",
"False) self.assertParses(0., False) self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None,",
"if hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment",
"= tempfile.mkstemp(suffix='.html') return infile, outfile, outfd def testFileNames(self): infile, outfile,",
"markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual(",
"extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading with non-existant class",
"Extension object as an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def",
"import unicode_literals import unittest import sys import os import markdown",
"span2 = markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text* ') span3 =",
"https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/). Maintained",
"), '<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br",
"case. \"\"\" el = markdown.util.etree.Element('MixedCase') el.text = 'not valid '",
"md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True) md2 =",
"for testing. \"\"\" def __init__(self, data): self.data = data def",
"loading with a class instance. \"\"\" from markdown.extensions.footnotes import FootnoteExtension",
"= Item('b') self.assertEqual(list(r), ['a', 'b']) r['a'] = Item('a1') self.assertEqual(list(r), ['a1',",
"testIsSate(self): \"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True)",
"with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c',",
"before non-first item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1', 'b',",
"script = markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">' el.tail = \"tail",
"Test serialization of QName attribute. \"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'),",
"with third party serializers (including markdown's (x)html serializer). While markdown",
"options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options)",
"mn.text = '2' ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2'",
"Create instance of Markdown. \"\"\" self.md = markdown.Markdown() def testBlankInput(self):",
"class instance. \"\"\" from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self):",
"setUp(self): self.saved = sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout",
"comment node self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment =",
"for two temp files. \"\"\" infd, infile = tempfile.mkstemp(suffix='.txt') with",
"self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c',",
"Item('f'), 'badlocation') # Check the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning)",
"pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase):",
"when empty. \"\"\" self.assertEqual(self.state, []) def testSetSate(self): \"\"\" Test State.set().",
"div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\"",
"self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase):",
"else: self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test that an",
"from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test Extension",
"= markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el),",
"Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def",
"def testCommentSerialization(self): \"\"\" Test that an ElementTree Comment serializes properly.",
"setUp(self): self.state = markdown.blockparser.State() def testBlankState(self): \"\"\" Test State when",
"'<p>foo</p>') def testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO()",
"el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>' p.set('hidden',",
"= markdown.util.etree.Element('MixedCase') el.text = 'not valid ' em = markdown.util.etree.SubElement(el,",
"') span1 = markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more* ') span2",
"self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r') as fp: output =",
"**kwargs): \"\"\"Initialize.\"\"\" self.config = {} def extendMarkdown(self, md): \"\"\"Modify inline",
"testEntryPointExtension(self): \"\"\" Test Extension loading with an entry point. \"\"\"",
"20) with self.assertRaises(TypeError): del r[0] # TODO: restore this when",
"self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\" Test that",
"'<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>'",
"testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html',",
"' baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual(",
"self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\" Test HtmlStash.store with",
"md.output_formats['fake'] = fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz',",
"= \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>'",
"TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character append. \"\"\" def testAppend(self): \"\"\"",
"testBlockAppend(self): \"\"\" Test that appended escapes are only in the",
"\"\"\" Create instance of BlockParser. \"\"\" self.parser = markdown.Markdown().parser def",
"self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\" Test input of only whitespace.",
"md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of tags in",
"Test QName escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el =",
"fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8')) outfile",
"placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo',",
"self.assertRaises(TypeError): # del r['a'] # TODO: remove this when deprecated",
"'', ' baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True)",
"# Add before first item r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a',",
"config files. \"\"\" if not isinstance(config, markdown.util.string_type): # convert to",
"version) License: BSD (see LICENSE.md for details). Python-Markdown Regression Tests",
"pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\" Element Tail",
"= markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True) md2 = markdown.Markdown()",
"self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) class TestErrors(unittest.TestCase):",
"r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError): del r[0] # TODO: restore",
"\"\"\" self.md = markdown.Markdown() def testBlankInput(self): \"\"\" Test blank input.",
"ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi),",
"def testString(self): \"\"\" Test that a regular string is parsed.",
"DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute of",
"getTempFiles(self, src): \"\"\" Return the file names for two temp",
"= 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>'",
"the base Extension class will raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError,",
"self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self): options, logging_level =",
"ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def",
"self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def testReset(self): \"\"\" Test HtmlStash.reset.",
"markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo",
"Markdown class. \"\"\" def setUp(self): \"\"\" Create instance of Markdown.",
"ElementTree Comment serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def",
"block kHTML append. \"\"\" def testBlockAppend(self): \"\"\" Test that appended",
"strict=False) self.assertEqual(len(r), 1) # deregister non-existant item with strict=False r.deregister('d',",
"os.fdopen(outfd, 'r') as fp: output = fp.read() self.assertEqual(output, '<p>foo</p>') def",
"el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self):",
"'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config)",
"\"\"\"Test that version is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: #",
"a new line tail \"\"\" root = markdown.util.etree.Element('root') br =",
"'_end') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd', 'e']) with",
"self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options, logging_level = parse_options(['-q']) self.assertGreater(logging_level,",
"'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } import json",
"Markdown's HtmlStash. \"\"\" def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder =",
"self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\" Test",
"Test Markdown's HtmlStash. \"\"\" def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder",
"testQuietOption(self): options, logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options,",
"'<b') self.assertEqual(list(r), ['a', 'b', 'c']) # Add before non-first item",
"Test Extension loading with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self):",
"markdown doesn't use ElementTree.Comment itself, we should certainly support any",
") def testReset(self): \"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0)",
"markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree) self.assertEqual(",
"markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\"",
"self.assertEqual(list(r), ['a']) def testRegistryContains(self): r = markdown.util.Registry() item = Item('a')",
"r) self.assertNotIn('b', r) def testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"def testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"is maintained. \"\"\" def setUp(self): # Create comment node self.comment",
"unicode_literals import unittest import sys import os import markdown import",
"w: warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r), ['a']) r['b'] = Item('b')",
"Test serialization of QName tag. \"\"\" div = markdown.util.etree.Element('div') qname",
"escapes are only in the current instance. \"\"\" md =",
"= parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options, logging_level = parse_options(['foo.txt'])",
"'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } import json self.create_config_file(json.dumps(config)) options,",
"r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r",
"class will raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] )",
"be a concern when using cElementTree with third party serializers",
"1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__`",
"def testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"While markdown doesn't use ElementTree.Comment itself, we should certainly support",
"\"\"\" def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test",
"__init__(self, data): self.data = data def __repr__(self): return repr(self.data) def",
"testCommentIsComment(self): \"\"\" Test that an ElementTree Comment passes the `is",
"['a1', 'b']) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning)",
"markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\" Test loading of an",
"*text*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def",
"'<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' ) def testQNameAttribute(self): \"\"\" Test serialization",
"\"\"\" def setUp(self): # Create comment node self.comment = markdown.util.etree.Comment('foo')",
"Test serialization of ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag,",
"by <NAME> (http://www.freewisdom.org). Currently maintained by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57)",
"deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that version is deprecated.\"\"\" with warnings.catch_warnings(record=True)",
"warnings to always be triggered. warnings.simplefilter(\"always\") # Trigger a warning.",
"'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testMixedCaseTags(self): \"\"\"\" Test",
"'b', 30) self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self): r = markdown.util.Registry()",
"= False self.assertEqual(options, self.default_options) def testExtensionOption(self): options, logging_level = parse_options(['-x',",
"markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading with class name",
"<em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\" Test that a simple AtomicString",
"[]) def testSetSate(self): \"\"\" Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state'])",
"'annotations') ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">'",
"def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' )",
"a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\" Test",
"markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test Extension loading with an entry",
"markdown.version_info # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info,",
"self.default_options = { 'input': None, 'output': None, 'encoding': None, 'output_format':",
"unittest import sys import os import markdown import warnings from",
"md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\" Test that",
"that a simple AtomicString is not parsed. \"\"\" tree =",
"\"\"\" def setUp(self): self.saved = sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo',",
"an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test",
"for details). Python-Markdown Regression Tests ================================ Tests of the various",
"self.assertEqual(list(r), ['a1', 'b']) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category,",
"Python implementation of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI:",
"= markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\"",
"outfile = tempfile.mkstemp(suffix='.html') return infile, outfile, outfd def testFileNames(self): infile,",
"as fp: fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html') return infile, outfile,",
"'b1', 'c']) # Add after last item r.add('d', Item('d'), '>c')",
"el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo <&escaped>'",
"a few years by <NAME> (http://www.freewisdom.org). Currently maintained by <NAME>",
"'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f', 'foo.html',",
"[footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class",
"AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES = ('a',) def handleMatch(self,",
"\"\"\" lines = ['#foo', '', 'bar', '', ' baz'] tree",
"repr(self.data) def __eq__(self, other): return self.data == other class RegistryTests(unittest.TestCase):",
"License: BSD (see LICENSE.md for details). Python-Markdown Regression Tests ================================",
"for x in w)) def testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'),",
"root = markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root)",
"def create_config_file(self, config): \"\"\" Helper to create temp config files.",
"= ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options, logging_level = parse_options([",
"\"\"\" def setUp(self): # Set warnings to be raised as",
"to load. \"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self):",
"def testXhtml(self): \"\"\"\" Test XHTML serialization. \"\"\" el = markdown.util.etree.Element('div')",
"markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\" Test that",
"options, logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options)",
"string is parsed. \"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree,",
"testVerboseOption(self): options, logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options,",
") def buildExtension(self): \"\"\" Build an extension which registers fakeSerializer.",
"\"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo",
"tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = 'some",
"TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of the Markdown class. \"\"\" def",
"for x in w)) def testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'),",
"in md.block_level_elements, True) md2 = markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements,",
"bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test",
"def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r = markdown.util.Registry()",
"self.assertEqual(list(r), ['b', 'c']) # Add before first item r.add('a', Item('a'),",
"testHtml(self): \"\"\" Test HTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id',",
"serialization of ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction)",
"with os.fdopen(infd, 'w') as fp: fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html')",
"testBadQNameTag(self): \"\"\" Test serialization of QName with no tag. \"\"\"",
"\"\"\" Tests block kHTML append. \"\"\" def testBlockAppend(self): \"\"\" Test",
"'</math>' '</div>' ) def testQNameAttribute(self): \"\"\" Test serialization of QName",
"self.assertEqual(list(r), ['b', 'c', 'a']) def testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted,",
"= r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def setUp(self): \"\"\"Setup markdown",
"self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self): \"\"\" Test State.isstate(). \"\"\"",
"\"\"\" Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2')",
"def testCommentPrettify(self): \"\"\" Test that an ElementTree Comment is prettified",
"Project (v. 1.7 and later) Copyright 2004, 2005, 2006 <NAME>",
"non-existant item with strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError):",
"r) def testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r),",
"3) self.assertEqual(list(r), ['b', 'c', 'a']) def testIsSorted(self): r = markdown.util.Registry()",
"TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash. \"\"\" def setUp(self): self.stash =",
"a simple AtomicString is not parsed. \"\"\" tree = markdown.util.etree.Element('div')",
"Test serialization of QName with no tag. \"\"\" qname =",
"'<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p",
"of Command Line Interface Options. \"\"\" def setUp(self): self.default_options =",
"# with self.assertRaises(TypeError): # r['a'] = 'a' # TODO: remove",
"of tags in ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor",
"these tests are included to ensure such support is maintained.",
"concern when using cElementTree with third party serializers (including markdown's",
"parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options,",
"test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test that an",
"'mn') mn.text = '2' ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text =",
"has a new line tail \"\"\" root = markdown.util.etree.Element('root') br",
"non Extension object as an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object])",
"= markdown.util.Registry() item = Item('a') r.register(item, 'a', 20) self.assertIs('a' in",
"20) r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r),",
"') span2 = markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text* ') span3",
"None, 'encoding': None, 'output_format': 'xhtml', 'lazy_ol': True, 'extensions': [], 'extension_configs':",
"in ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\"",
"self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True)",
"ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\" Test",
"tests should only be a concern when using cElementTree with",
"self.placeholder = self.stash.store('foo') def testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder,",
"self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistryDelItem(self): r =",
"Tests of the BlockParser class. \"\"\" def setUp(self): \"\"\" Create",
"an ElementTree Comment passes the `is Comment` test. \"\"\" self.assertIs(self.comment.tag,",
"current instance. \"\"\" md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements,",
"def setUp(self): # Create comment node self.comment = markdown.util.etree.Comment('foo') if",
"= markdown.util.etree.SubElement(msup, 'mn') mn.text = '2' ann = markdown.util.etree.SubElement(sem, 'annotations')",
"that an ElementTree Comment is recognized as BlockLevel. \"\"\" md",
"as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c', 10) del",
"script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div",
"\"\"\" result = \"\"\"<p>Some <strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset()",
"when deprecated __setitem__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\")",
"*to*') span2.tail = markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString(' *with*') new",
") class TestConfigParsing(unittest.TestCase): def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result)",
"self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self): r",
"BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root, text)",
"{ 'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config) options, logging_level = parse_options(['-c',",
"the class as it replaces the module's.\"\"\" dir_attr = dir(markdown)",
"and return hardcoded output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self,",
"\"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\" Test",
"['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character append. \"\"\"",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1],",
"\"\"\" Test Extension loading with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def",
"of QName with no tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el",
"1.7 and later) Copyright 2004, 2005, 2006 <NAME> (v. 0.2-1.6b)",
"self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config =",
"'math') math = markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem = markdown.util.etree.SubElement(math,",
"BlockParser class. \"\"\" def setUp(self): \"\"\" Create instance of BlockParser.",
"'script') script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el),",
"= markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree)",
"options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options, logging_level",
"create_config_file(self, config): \"\"\" Helper to create temp config files. \"\"\"",
"parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options, logging_level = parse_options(['-v']) self.assertEqual(logging_level,",
"21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted = False r.get_index_for_name('a')",
"TODO: restore this when deprecated __setitem__ is removed. # with",
"# Add after last item r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a',",
"Test input of only whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '') def",
"\"\"\"Modify inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0)",
"that an extension can exclude parent tags. \"\"\" test =",
"\"\"\" Tests of the BlockParser class. \"\"\" def setUp(self): \"\"\"",
"'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c') def",
"self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash. \"\"\"",
"of the Markdown class. \"\"\" def setUp(self): \"\"\" Create instance",
"'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r =",
"markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual(",
"PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase):",
"Element Tail Tests \"\"\" def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def",
"span2.text = markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2, 'span') span3.text =",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry)",
"DeprecationWarning) for x in w)) def testRegistrySlice(self): r = markdown.util.Registry()",
"options, logging_level = parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options) def",
"def __init__(self, data): self.data = data def __repr__(self): return repr(self.data)",
"the python markdown lib. \"\"\" from __future__ import unicode_literals import",
"Comment is recognized as BlockLevel. \"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag),",
"logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def",
"this when deprecated __setitem__ is removed. with warnings.catch_warnings(record=True) as w:",
"import unittest import sys import os import markdown import warnings",
"# Ignore input and return hardcoded output return '<div><p>foo</p></div>' class",
"loading with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test",
"blank input. \"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\" Test input",
"kHTML append. \"\"\" def testBlockAppend(self): \"\"\" Test that appended escapes",
"State class for BlockParser. \"\"\" def setUp(self): self.state = markdown.blockparser.State()",
"BytesIO() def tearDown(self): sys.stdin, sys.stdout = self.saved def getTempFiles(self, src):",
"p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some *text*') new =",
"\"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\" Test input of only",
"'</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' ) def testQNameAttribute(self): \"\"\" Test",
"mi = markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x' mn = markdown.util.etree.SubElement(msup,",
"self.assertIn(item, r) self.assertNotIn('b', r) def testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'),",
"config = \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options,",
"restore this when deprecated __setitem__ is removed. # with self.assertRaises(TypeError):",
"0) with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'),",
"'a', 20) self.assertIs('a' in r, True) self.assertIn(item, r) self.assertNotIn('b', r)",
"to end r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1',",
"testExtensionOption(self): options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options,",
"\"\"\" Create instance of Markdown. \"\"\" self.md = markdown.Markdown() def",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1)",
"'<div><p>some *text*</p></div>' ) def testNestedAtomicString(self): \"\"\" Test that a nested",
"tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\"",
"'<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self): \"\"\" Test serialization",
"markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\"",
"warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test falure on non-unicode source text.",
"el = markdown.util.etree.Element(self.tag) el.text = m.group(2) return el, m.start(0), m.end(0)",
"not PY3: def bytes(string, encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\"",
"'b', 30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2)",
"markdown.util.etree.SubElement(el, None) non_element.text = 'non-element text' script = markdown.util.etree.SubElement(non_element, 'script')",
"def tearDown(self): sys.stdin, sys.stdout = self.saved def getTempFiles(self, src): \"\"\"",
"def testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\") text",
"loading with class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\"",
"QName escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname)",
"tempfile from io import BytesIO from xml.etree.ElementTree import ProcessingInstruction PY3",
"['foo', 'bar'] ) def testReset(self): \"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset()",
"del r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del r['badname'] del r['c']",
"None) self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none', False) def",
"that an extension can exclude parent tags when dealing with",
"self.assertEqual(list(r), ['a', 'b', 'c']) # Add before non-first item r.add('a1',",
"'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options, logging_level = parse_options(['-o', 'html'])",
"passes the `is Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self):",
"'some *text*' new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' )",
"Test that last <br> in tree has a new line",
"included to ensure such support is maintained. \"\"\" def setUp(self):",
"using cElementTree with third party serializers (including markdown's (x)html serializer).",
"input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\" Test Extension loading",
"self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\" Tests",
"= markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some *text*')",
"markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem = markdown.util.etree.SubElement(math, 'semantics') msup =",
"'<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' ) def",
"2007-2018 The Python Markdown Project (v. 1.7 and later) Copyright",
"testWhitespaceOnly(self): \"\"\" Test input of only whitespace. \"\"\" self.assertEqual(self.md.convert(' '),",
"BytesIO from xml.etree.ElementTree import ProcessingInstruction PY3 = sys.version_info[0] == 3",
"an Extension with no makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util'])",
"w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c', 10) del r['b']",
"= fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()],",
"testCommentSerialization(self): \"\"\" Test that an ElementTree Comment serializes properly. \"\"\"",
"only in the current instance. \"\"\" md = markdown.Markdown() md.block_level_elements.append('test')",
"def testMixedCaseTags(self): \"\"\"\" Test preservation of tag case. \"\"\" el",
"r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del r['badname'] del r['c'] self.assertEqual(list(r),",
"\"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES = ('a',) def handleMatch(self, m,",
"non-unicode source text. \"\"\" if not PY3: source = \"foo\".encode('utf-16')",
"Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by <NAME>",
"def testDeregister(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"[]) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test",
"testXhtml(self): \"\"\"\" Test XHTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id',",
"object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test that an",
"markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>'",
"testOutputFileOption(self): options, logging_level = parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options,",
"attribute of the class as it replaces the module's.\"\"\" dir_attr",
"= markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted, True)",
"(x)html serializer). While markdown doesn't use ElementTree.Comment itself, we should",
"The Python Markdown Project (v. 1.7 and later) Copyright 2004,",
"x in w)) def testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"with self.assertRaises(ValueError): # deregister non-existant item with strict=True r.deregister('e') self.assertEqual(list(r),",
"testFileNames(self): infile, outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd,",
"'markdown.extensions.toc': { 'title': 'Some Title', 'anchorlink': True, 'permalink': True }",
"self.assertEqual(list(r), ['a']) r['b'] = Item('b') self.assertEqual(list(r), ['a', 'b']) r['a'] =",
"'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options, logging_level",
"Test that an ElementTree Comment is recognized as BlockLevel. \"\"\"",
"item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1', 'b', 'c']) #",
"= sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO()",
"= parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self):",
"def testWhitespaceOnly(self): \"\"\" Test input of only whitespace. \"\"\" self.assertEqual(self.md.convert('",
"is already partially escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el",
"tags when dealing with a tail. \"\"\" test = \"\"\"",
"testNestedAtomicString(self): \"\"\" Test that a nested AtomicString is not parsed.",
"line tail \"\"\" root = markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br')",
"markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def testString(self): \"\"\" Test that a",
"NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\"",
"['a', 'b']) r['a'] = Item('a1') self.assertEqual(list(r), ['a1', 'b']) # Check",
"to be raised as errors warnings.simplefilter('error') def tearDown(self): # Reset",
"as an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\"",
"= 'a' # TODO: restore this when deprecated __setitem__ is",
"input and return hardcoded output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def",
"el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\" Test",
"dealing with a tail. \"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\"",
"') span3 = markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*') span3.tail =",
"self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options, logging_level =",
"\"\"\" def setUp(self): \"\"\" Create instance of BlockParser. \"\"\" self.parser",
"TestBlockParser(unittest.TestCase): \"\"\" Tests of the BlockParser class. \"\"\" def setUp(self):",
"'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self): options, logging_level",
"'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self):",
"= r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def",
"'<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\" Test serialization of QName",
"self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"'span') span3.text = markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*') span2.tail =",
"infile = BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0)",
"return self.data == other class RegistryTests(unittest.TestCase): \"\"\" Test the processor",
"options, logging_level = parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options)",
"Maintained for a few years by <NAME> (http://www.freewisdom.org). Currently maintained",
"def buildExtension(self): \"\"\" Build an extension which registers fakeSerializer. \"\"\"",
"fp.write(config) def testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/',",
"markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div, qname) math.set('display',",
"deprecated __del__ is removed. # with self.assertRaises(TypeError): # del r['a']",
"registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer return registerFakeSerializer() def",
"Item('c'), '_begin') self.assertEqual(list(r), ['c']) # Added to beginning r.add('b', Item('b'),",
"\"\"\" self.assertEqual(self.state, []) def testSetSate(self): \"\"\" Test State.set(). \"\"\" self.state.set('a_state')",
"Python-Markdown Regression Tests ================================ Tests of the various APIs with",
"self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self): r = markdown.util.Registry()",
"text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self):",
"testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 21)",
"self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options,",
"Test failure of an extension to load. \"\"\" self.assertRaises( ImportError,",
"are honored (not parsed). \"\"\" def setUp(self): md = markdown.Markdown()",
"(`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading with",
"result) def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE',",
"(not parsed). \"\"\" def setUp(self): md = markdown.Markdown() self.inlineprocessor =",
"self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options, logging_level = parse_options(['-n']) self.default_options['lazy_ol'] =",
"with strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self): r = markdown.util.Registry()",
"self.default_options) def testOutputFormatOption(self): options, logging_level = parse_options(['-o', 'html']) self.default_options['output_format'] =",
"not in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML",
"with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r = markdown.util.Registry() with self.assertRaises(TypeError):",
"Line Interface Options. \"\"\" def setUp(self): self.default_options = { 'input':",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0)",
"'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile])",
"current instance. \"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS,",
"Item(object): \"\"\" A dummy Registry item object for testing. \"\"\"",
"'c']) # Add after last item r.add('d', Item('d'), '>c') self.assertEqual(list(r),",
"self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\"",
"self.default_options) def textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc': { 'title': 'Some",
"= sys.version_info[0] == 3 if not PY3: def bytes(string, encoding):",
"1) with self.assertRaises(ValueError): # deregister non-existant item with strict=True r.deregister('e')",
"LICENSE.md for details). Python-Markdown Regression Tests ================================ Tests of the",
"2) self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w:",
"\"\"\" Test loading a non Extension object as an extension.",
"\"\"\" Test that ElementTree Comments work. These tests should only",
"self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options, logging_level =",
"markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>'",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a', 'b1'])",
"'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def create_config_file(self, config): \"\"\" Helper",
"= markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test that last <br> in",
"setUp(self): self.default_options = { 'input': None, 'output': None, 'encoding': None,",
"\"\"\" Tests of ConvertFile. \"\"\" def setUp(self): self.saved = sys.stdin,",
"infile, outfile, outfd def testFileNames(self): infile, outfile, outfd = self.getTempFiles('foo')",
"an ElementTree Comment is prettified properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())",
"markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup, 'mi')",
"md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True) md2 =",
"the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w))",
"= markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString('",
"Extension with no makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def",
"testOutputFormatOption(self): options, logging_level = parse_options(['-o', 'html']) self.default_options['output_format'] = 'html' self.assertEqual(options,",
"= markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self):",
"self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options, logging_level = parse_options(['foo.txt']) self.default_options['input'] =",
"logging_level = parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options) def",
"the BlockParser class. \"\"\" def setUp(self): \"\"\" Create instance of",
"Some +test+ and a [+link+](http://test.com) \"\"\" result = \"\"\"<p>Some <strong>test</strong>",
"\"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase):",
"markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self): \"\"\" Test",
"def setUp(self): md = markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def testString(self):",
"\"\"\" Test falure on non-unicode source text. \"\"\" if not",
"HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\"",
"self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\" Build an",
"{ 'title': 'Some Title', 'anchorlink': True, 'permalink': True } }",
"dummy Registry item object for testing. \"\"\" def __init__(self, data):",
"= \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr",
"may. Therefore, these tests are included to ensure such support",
"self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\"",
"with self.assertRaises(TypeError): # r['a'] = 'a' # TODO: remove this",
"'c']) # Add before first item r.add('a', Item('a'), '<b') self.assertEqual(list(r),",
"config = yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd, 'w')",
"def tearDown(self): # Reset warning behavior back to default warnings.simplefilter('default')",
"= BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'),",
"testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings are honored (not parsed). \"\"\"",
"def testHtml(self): \"\"\" Test HTML serialization. \"\"\" el = markdown.util.etree.Element('div')",
"self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test loading a non",
"qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div, qname) math.set('display', 'block')",
"item = Item('a') r.register(item, 'a', 20) self.assertIs('a' in r, True)",
"'a' # TODO: restore this when deprecated __setitem__ is removed.",
"'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } import",
"'b', 'c']) # Add after non-last item r.add('b1', Item('b1'), '>b')",
"\"\"\" ANCESTOR_EXCLUDES = ('a',) def handleMatch(self, m, data): \"\"\" Handle",
"2) r.deregister('c', strict=False) self.assertEqual(len(r), 1) # deregister non-existant item with",
"can exclude parent tags when dealing with a tail. \"\"\"",
"self.config = {} def extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\" pattern",
"\"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading with class",
"Test BlockParser.parseDocument. \"\"\" lines = ['#foo', '', 'bar', '', '",
"'-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty'",
"= False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted = False repr(r) self.assertIs(r._is_sorted,",
"self.md = markdown.Markdown() def testBlankInput(self): \"\"\" Test blank input. \"\"\"",
"'</semantics>' '</math>' '</div>' ) def testQNameAttribute(self): \"\"\" Test serialization of",
"testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile)",
"source) def testBadOutputFormat(self): \"\"\" Test failure on bad output_format. \"\"\"",
"= parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options, logging_level = parse_options(['-v'])",
"'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\"",
"AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\" Test that the",
"self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that version info",
"NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree",
"= markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True) md2 = markdown.Markdown()",
"loading with an entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\"",
"href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def",
"True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML append. \"\"\" def",
"\"\"\" Return the file names for two temp files. \"\"\"",
"errors warnings.simplefilter('error') def tearDown(self): # Reset warning behavior back to",
"el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>'",
"Comment serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self):",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r),",
"strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError): # deregister non-existant",
"is recognized as BlockLevel. \"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False)",
"HTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p =",
"recognized as BlockLevel. \"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def",
"markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'),",
"def setUp(self): \"\"\" Create instance of BlockParser. \"\"\" self.parser =",
"r['b'] self.assertEqual(list(r), ['a', 'c']) del r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError):",
"'<div foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\" Test serialization of QName",
"return infile, outfile, outfd def testFileNames(self): infile, outfile, outfd =",
"def testRegisterWithoutPriority(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self):",
"markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test Extension loading",
"a warning. version = markdown.version # Verify some things self.assertEqual(len(w),",
"# TODO: restore this when deprecated __del__ is removed. #",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) slc",
"markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\" Test",
"item r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c',",
"Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading",
"A dummy Registry item object for testing. \"\"\" def __init__(self,",
"self.assertRaises(TypeError): r[0] = 'a' # TODO: restore this when deprecated",
"markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1, 'span')",
"True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted",
"will raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class",
"warning behavior back to default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test",
"two temp files. \"\"\" infd, infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd,",
"\"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test the html and xhtml serializers.",
"def testIsSate(self): \"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'),",
"later) Copyright 2004, 2005, 2006 <NAME> (v. 0.2-1.6b) Copyright 2004",
"be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version_info = markdown.version_info",
"testing. \"\"\" def __init__(self, data): self.data = data def __repr__(self):",
"class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character append. \"\"\" def testAppend(self):",
"self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES',",
"Ignore input and return hardcoded output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension):",
"self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c', 'a']) def testIsSorted(self): r =",
"support is maintained. \"\"\" def setUp(self): # Create comment node",
"Reset warning behavior back to default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\"",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c',",
"testQNameEscaping(self): \"\"\" Test QName escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div')",
"markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString(' *test*') span1.tail",
"'w') as fp: fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html') return infile,",
"bytes(string, encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of",
"= BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile()",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b',",
"\"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\" lines =",
"last <br> in tree has a new line tail \"\"\"",
"= \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self): \"\"\" Test failure",
"qname) math.set('display', 'block') sem = markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem,",
"in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML append.",
"def testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile,",
"TestErrors(unittest.TestCase): \"\"\" Test Error Reporting. \"\"\" def setUp(self): # Set",
"setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self): \"\"\"",
"convert to string config = yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml')",
"p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text =",
"def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def",
"testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b', 10)",
"\"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el)",
"Test that ElementTree Comments work. These tests should only be",
"def testQuietOption(self): options, logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self):",
"False repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self): r = markdown.util.Registry() r.register(Item('a'),",
"markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test that an ElementTree Comment is",
"def test_ancestors_tail(self): \"\"\" Test that an extension can exclude parent",
"r.get_index_for_name('c') def testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'),",
"append. \"\"\" def testAppend(self): \"\"\" Test that appended escapes are",
"False) r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21)",
"= markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem",
"properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' )",
"False) self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def",
"return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer",
"markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' )",
"def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test that",
"'b', 21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c',",
"info is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause all",
"self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistryDelItem(self):",
"result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that",
"warning. version_info = markdown.version_info # Verify some things self.assertEqual(len(w), 1)",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40)",
"# deregister non-existant item with strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def",
"details). Python-Markdown Regression Tests ================================ Tests of the various APIs",
"\"\"\" def __init__(self, data): self.data = data def __repr__(self): return",
"self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>' 'non-element text'",
"that AtomicStrings are honored (not parsed). \"\"\" def setUp(self): md",
"loading of an Extension with no makeExtension function. \"\"\" self.assertRaises(AttributeError,",
"'p') p.text = markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p, 'span') span1.text",
"to always be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version",
"sys.version_info[0] == 3 if not PY3: def bytes(string, encoding): return",
"serializer). While markdown doesn't use ElementTree.Comment itself, we should certainly",
"python markdown lib. \"\"\" from __future__ import unicode_literals import unittest",
"'bar', '', ' baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()),",
"self.default_options) def testOutputFileOption(self): options, logging_level = parse_options(['-f', 'foo.html']) self.default_options['output'] =",
"p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo <&escaped>' p.set('hidden', 'hidden')",
"import parse_options from logging import DEBUG, WARNING, CRITICAL import yaml",
"'a' # TODO: remove this when deprecated __setitem__ is removed.",
"r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd',",
"result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None)",
"os.remove(self.tempfile) def testNoOptions(self): options, logging_level = parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level,",
"of the various APIs with the python markdown lib. \"\"\"",
"an ElementTree Comment is recognized as BlockLevel. \"\"\" md =",
"(`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile. \"\"\"",
"'a']) def testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"(including markdown's (x)html serializer). While markdown doesn't use ElementTree.Comment itself,",
"= 'some *text*' new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>'",
"an extension which registers fakeSerializer. \"\"\" def fakeSerializer(elem): # Ignore",
"TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that version is",
"del r['a'] # TODO: remove this when deprecated __del__ is",
"# del r['a'] # TODO: remove this when deprecated __del__",
"{ 'input': None, 'output': None, 'encoding': None, 'output_format': 'xhtml', 'lazy_ol':",
"already partially escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el =",
"self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes]",
"testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self):",
"'b', 'b1', 'c', 'd']) # Add to end r.add('e', Item('e'),",
"non_element.text = 'non-element text' script = markdown.util.etree.SubElement(non_element, 'script') script.text =",
"testNoLazyOlOption(self): options, logging_level = parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options)",
"self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"with os.fdopen(outfd, 'r') as fp: output = fp.read() self.assertEqual(output, '<p>foo</p>')",
"\"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\" Test",
"-*- \"\"\" Python Markdown A Python implementation of <NAME>'s Markdown.",
"parsed. \"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text",
"config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks': {",
"load. \"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\"",
"things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests",
"Tests \"\"\" def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\"",
"version = markdown.version # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category,",
"hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment def",
"<NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by",
"infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as fp: fp.write(src) outfd,",
"Interface Options. \"\"\" def setUp(self): self.default_options = { 'input': None,",
"None, 'output': None, 'encoding': None, 'output_format': 'xhtml', 'lazy_ol': True, 'extensions':",
"to beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c']) # Add",
"last item r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1',",
"the Markdown class. \"\"\" def setUp(self): \"\"\" Create instance of",
"testNonUnicodeSource(self): \"\"\" Test falure on non-unicode source text. \"\"\" if",
"DeprecationWarning) for x in w)) class TestErrors(unittest.TestCase): \"\"\" Test Error",
"= Item('a1') self.assertEqual(list(r), ['a1', 'b']) # Check the warnings self.assertEqual(len(w),",
"output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings are",
"testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r = markdown.util.Registry() #",
"'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>'",
"r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r),",
"before first item r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a', 'b', 'c'])",
"'<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testMixedCaseTags(self):",
"self.state = markdown.blockparser.State() def testBlankState(self): \"\"\" Test State when empty.",
"self.data == other class RegistryTests(unittest.TestCase): \"\"\" Test the processor registry.",
"self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\" A dummy Registry item object",
"\"\"\"Initialize.\"\"\" self.config = {} def extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\"",
"'xhtml', 'lazy_ol': True, 'extensions': [], 'extension_configs': {}, } self.tempfile =",
"'c', 'd']) # Add to end r.add('e', Item('e'), '_end') self.assertEqual(list(r),",
"= markdown.blockparser.State() def testBlankState(self): \"\"\" Test State when empty. \"\"\"",
"= markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>'",
"2004, 2005, 2006 <NAME> (v. 0.2-1.6b) Copyright 2004 <NAME> (the",
"Test preservation of tag case. \"\"\" el = markdown.util.etree.Element('MixedCase') el.text",
"self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options, logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING)",
"sys.stdin, sys.stdout = self.saved def getTempFiles(self, src): \"\"\" Return the",
"\"\"\" Test HTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">')",
"extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension",
"Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object):",
"self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\" Test QName",
"of QName tag. \"\"\" div = markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML',",
"class Item(object): \"\"\" A dummy Registry item object for testing.",
"markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def",
"TODO: remove this when deprecated __setitem__ is removed. with warnings.catch_warnings(record=True)",
"as BlockLevel. \"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self):",
"CRITICAL) def testVerboseOption(self): options, logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING) def",
"def testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\" lines = ['#foo', '',",
"= self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" )",
"md = markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def testString(self): \"\"\" Test",
"'_begin') self.assertEqual(list(r), ['c']) # Added to beginning r.add('b', Item('b'), '_begin')",
"\"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result)",
"= yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as",
"that ElementTree Comments work. These tests should only be a",
"ConvertFile. \"\"\" def setUp(self): self.saved = sys.stdin, sys.stdout sys.stdin =",
"p.text = 'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element =",
"\"\"\" Test that an ElementTree Comment passes the `is Comment`",
"r['badname'] del r['c'] self.assertEqual(list(r), []) # Check the warnings self.assertEqual(len(w),",
"\"\"\" Test that the base Extension class will raise NotImplemented.",
"parsed). \"\"\" def setUp(self): md = markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline']",
"def testMultipleExtensionOptions(self): options, logging_level = parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty'",
"self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options,",
"def setUp(self): # Set warnings to be raised as errors",
"def testRegistrySetItem(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r[0] = 'a'",
"\"\"\" el = markdown.util.etree.Element('MixedCase') el.text = 'not valid ' em",
"general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that version is deprecated.\"\"\" with",
"is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause all warnings",
"markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\" Test serialization of",
"testReset(self): \"\"\" Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1')",
"parse_options(['-o', 'html']) self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options,",
"id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text'",
"Test that appended escapes are only in the current instance.",
"non-existant class name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] )",
"0) def setUp(self): \"\"\"Setup markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def",
"preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test",
"extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar',",
"markdown.Markdown() def testBlankInput(self): \"\"\" Test blank input. \"\"\" self.assertEqual(self.md.convert(''), '')",
"['c']) # Added to beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b',",
"= markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>'",
"with os.fdopen(fd, 'w') as fp: fp.write(config) def testExtensionConfigOption(self): config =",
"markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\" Build",
"self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>'",
"Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2'])",
"self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute",
"'script') script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el),",
"r[0] # TODO: restore this when deprecated __del__ is removed.",
"fp: fp.write(config) def testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks': { 'base_url':",
"class. \"\"\" def setUp(self): \"\"\" Create instance of BlockParser. \"\"\"",
"self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape",
"Tests of the various APIs with the python markdown lib.",
"= self.saved def getTempFiles(self, src): \"\"\" Return the file names",
"import json self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] =",
"= markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text =",
"`__dir__` attribute of the class as it replaces the module's.\"\"\"",
"3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistryDelItem(self): r",
"def testQNameTag(self): \"\"\" Test serialization of QName tag. \"\"\" div",
"Tests escape character append. \"\"\" def testAppend(self): \"\"\" Test that",
"node self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment",
"'semantics') msup = markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup, 'mi') mi.text",
"ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES",
"value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue',",
"Started by <NAME> (http://www.dwerg.net/). Maintained for a few years by",
"\"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self): \"\"\" Test that",
"import sys import os import markdown import warnings from markdown.__main__",
"' '*to*</span> *test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def assertParses(self, value,",
"markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\"",
"markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p, 'span')",
"'') def testWhitespaceOnly(self): \"\"\" Test input of only whitespace. \"\"\"",
"default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test falure on non-unicode source",
"self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r[0]",
"with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r), ['a'])",
"Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test that",
"r.register(Item('c'), 'c', 10) del r['b'] self.assertEqual(list(r), ['a', 'c']) del r['a']",
"self.test_comment = markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self): \"\"\"",
"self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r",
"markdown.util.string_type): # convert to string config = yaml.dump(config) fd, self.tempfile",
"outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self):",
"21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c', 'a'])",
"md.treeprocessors['inline'] def testString(self): \"\"\" Test that a regular string is",
"= tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as fp: fp.write(config) def testExtensionConfigOption(self):",
"to default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test falure on non-unicode",
"\"\"\" A dummy Registry item object for testing. \"\"\" def",
"for BlockParser. \"\"\" def setUp(self): self.state = markdown.blockparser.State() def testBlankState(self):",
"# Check the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x",
"def testBrTailNoNewline(self): \"\"\" Test that last <br> in tree has",
"p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el,",
"parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options,",
"testRegisterWithoutPriority(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r",
"fakeSerializer(elem): # Ignore input and return hardcoded output return '<div><p>foo</p></div>'",
"True) md2 = markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements, True) class",
"'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2',",
"Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)",
"r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted,",
"self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test the html and",
"serialization of QName attribute. \"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar'))",
"parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options,",
"Trigger a warning. version = markdown.version # Verify some things",
"= markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\" Test QName",
"md): md.output_formats['fake'] = fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown(",
"with non-existant class name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension']",
"ElementTree Comment passes the `is Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment)",
"\"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'),",
"if not PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def",
"self.assertNotIn('b', r) def testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"replaces the module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__', dir_attr)",
"TestConfigParsing(unittest.TestCase): def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self):",
"the `is Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\"",
"markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\" Tests of the State",
"self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def testNestedAtomicString(self): \"\"\" Test",
"self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none', False)",
"implementation of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/",
"tags. \"\"\" test = \"\"\" Some +test+ and a [+link+](http://test.com)",
"self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def testReset(self): \"\"\" Test HtmlStash.reset. \"\"\"",
"['a', 'a1', 'b', 'b1', 'c', 'd', 'e']) with self.assertRaises(ValueError): r.add('f',",
"= ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' )",
"PyPI: https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/). Maintained for a few",
"Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\" Test",
"30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True)",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a')",
"False), result) def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES', True)",
"self.assertEqual(self.state, []) def testSetSate(self): \"\"\" Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state,",
"self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\"",
"['a', 'b', 'c']) # Add before non-first item r.add('a1', Item('a1'),",
"markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def testBadQNameTag(self):",
"self.assertRaises(TypeError): # r['a'] = 'a' # TODO: remove this when",
"def testCommentIsBlockLevel(self): \"\"\" Test that an ElementTree Comment is recognized",
"def testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests",
"that the base Extension class will raise NotImplemented. \"\"\" self.assertRaises(",
"def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config =",
"self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's",
"extensions which may. Therefore, these tests are included to ensure",
"serializers (including markdown's (x)html serializer). While markdown doesn't use ElementTree.Comment",
"= markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p,",
"BlockParser. \"\"\" self.parser = markdown.Markdown().parser def testParseChunk(self): \"\"\" Test BlockParser.parseChunk.",
"['b', 'a']) def testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"\"\"\"Setup markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test",
"PY3: def bytes(string, encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests",
"import warnings from markdown.__main__ import parse_options from logging import DEBUG,",
"Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd', 'e'])",
"extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\" Test that the base Extension",
"p.text = 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el,",
"markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test failure of an extension",
"for x in w)) class TestErrors(unittest.TestCase): \"\"\" Test Error Reporting.",
"new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def testNestedAtomicString(self):",
"<NAME> (https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown Project (v. 1.7",
"'<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>'",
"testStoreMore(self): \"\"\" Test HtmlStash.store with additional blocks. \"\"\" placeholder =",
"FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test Extension loading with an",
"self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False)",
"def testInputFileOption(self): options, logging_level = parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options,",
"of the BlockParser class. \"\"\" def setUp(self): \"\"\" Create instance",
"text' ) def testMixedCaseTags(self): \"\"\"\" Test preservation of tag case.",
"'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test",
"markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo",
"self.default_options) def testMultipleExtensionOptions(self): options, logging_level = parse_options([ '-x', 'markdown.extensions.footnotes', '-x',",
"True, 'extensions': [], 'extension_configs': {}, } self.tempfile = '' def",
"testQNameTag(self): \"\"\" Test serialization of QName tag. \"\"\" div =",
"'c']) del r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del r['badname'] del",
"be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version = markdown.version",
"\"\"\"<p>Some <strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def",
"'a', 20) r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3)",
"markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text = 'non-element text'",
"BlockParser. \"\"\" def setUp(self): self.state = markdown.blockparser.State() def testBlankState(self): \"\"\"",
"testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError,",
"# Add after non-last item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a',",
"a nested AtomicString is not parsed. \"\"\" tree = markdown.util.etree.Element('div')",
"span3.tail = markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString(' *test*') span1.tail =",
"instance of BlockParser. \"\"\" self.parser = markdown.Markdown().parser def testParseChunk(self): \"\"\"",
"test_ancestors_tail(self): \"\"\" Test that an extension can exclude parent tags",
"self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\" A dummy Registry",
"= parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self):",
"'markdown.extensions.smarty' ]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options)",
"testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of",
"= markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\"",
"with self.assertRaises(TypeError): del r['badname'] del r['c'] self.assertEqual(list(r), []) # Check",
"Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c']) # Add",
"= parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options, logging_level",
"the various APIs with the python markdown lib. \"\"\" from",
"honored (not parsed). \"\"\" def setUp(self): md = markdown.Markdown() self.inlineprocessor",
"self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') # Check the warnings self.assertEqual(len(w), 7)",
"is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a'] = Item('a')",
"= markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\"",
") def testQNamePreEscaping(self): \"\"\" Test QName that is already partially",
"'input': None, 'output': None, 'encoding': None, 'output_format': 'xhtml', 'lazy_ol': True,",
"m.group(2) return el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def __init__(self, *args,",
"+test+ and a [+link+](http://test.com) \"\"\" result = \"\"\"<p>Some <strong>test</strong> and",
"temp files. \"\"\" infd, infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w')",
"a tail. \"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result =",
"warnings to be raised as errors warnings.simplefilter('error') def tearDown(self): #",
"20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r = markdown.util.Registry()",
"self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\" Test serialization",
"'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ]",
"makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test",
"this when deprecated __del__ is removed. # with self.assertRaises(TypeError): #",
"['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~",
"\"\"\" def testBlockAppend(self): \"\"\" Test that appended escapes are only",
"markdown.markdown, source) def testBadOutputFormat(self): \"\"\" Test failure on bad output_format.",
"output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake'] =",
"Command Line Interface Options. \"\"\" def setUp(self): self.default_options = {",
"Item('a'), '<b') self.assertEqual(list(r), ['a', 'b', 'c']) # Add before non-first",
"a class instance. \"\"\" from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def",
"= markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1,",
"config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html', 'html_class':",
"escape character append. \"\"\" def testAppend(self): \"\"\" Test that appended",
"md2 = markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase):",
"text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element",
"'<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail",
"'<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testXhtml(self): \"\"\"\"",
"self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\"",
"logging_level = parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options,",
"self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase):",
"with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\" Test Extension",
"'strong'), 'ancestor-test', 0) def setUp(self): \"\"\"Setup markdown object.\"\"\" self.md =",
"20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError):",
"def getTempFiles(self, src): \"\"\" Return the file names for two",
"self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options) def testExtensionOption(self): options, logging_level =",
"outfd def testFileNames(self): infile, outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile)",
"\"\"\" Test that appended escapes are only in the current",
"testProsessingInstruction(self): \"\"\" Test serialization of ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo',",
"class as it replaces the module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version',",
"self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\" Test loading",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self):",
"= 'non-element text' script = markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">'",
"markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\"",
"testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0.,",
"2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a']) def",
"self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r = markdown.util.Registry()",
"*test*') span1.tail = markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new),",
"class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of tags in ancestor list.",
"def testEncodingOption(self): options, logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8'",
"markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading with non-existant",
"/></MixedCase>' ) def testProsessingInstruction(self): \"\"\" Test serialization of ProcessignInstruction. \"\"\"",
"\"\"\" Test blank input. \"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\"",
"'base_url': 'http://example.com/', 'end_url': '.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER':",
"an extension can exclude parent tags. \"\"\" test = \"\"\"",
"`is Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test",
"None, 'output_format': 'xhtml', 'lazy_ol': True, 'extensions': [], 'extension_configs': {}, }",
"self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\" Test that an extension can",
"'b1', 'c', 'd', 'e']) with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') #",
"'b', 'b1', 'c', 'd', 'e']) with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation')",
"self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\" Test QName escaping. \"\"\"",
"def extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern,",
"\"\"\" def setUp(self): md = markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def",
"'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text = 'non-element text' script",
"any third party extensions which may. Therefore, these tests are",
"\"\"\" Test that an ElementTree Comment is prettified properly. \"\"\"",
"\"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />'",
"strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self): r = markdown.util.Registry() item",
"of the State class for BlockParser. \"\"\" def setUp(self): self.state",
"ElementTree Comment is recognized as BlockLevel. \"\"\" md = markdown.Markdown()",
"el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self):",
"valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self): \"\"\" Test serialization of",
"30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c',",
"restore this when deprecated __del__ is removed. # with self.assertRaises(TypeError):",
"# -*- coding: utf-8 -*- \"\"\" Python Markdown A Python",
"no makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\"",
"self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def",
"r.deregister('d', strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError): # deregister non-existant item",
"self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c']) # Add after last",
"(see LICENSE.md for details). Python-Markdown Regression Tests ================================ Tests of",
"self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del r['badname'] del r['c'] self.assertEqual(list(r), [])",
"\"\"\" Test failure of an extension to load. \"\"\" self.assertRaises(",
"Trigger a warning. version_info = markdown.version_info # Verify some things",
"with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"# Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__)",
"\"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\" Test Extension loading with",
"third party serializers (including markdown's (x)html serializer). While markdown doesn't",
"markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\" Test serialization of",
"= 'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options, logging_level = parse_options(['-o',",
"test_version_deprecation(self): \"\"\"Test that version is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w:",
"patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def setUp(self):",
"instance. \"\"\" from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\"",
"from __future__ import unicode_literals import unittest import sys import os",
"logging_level = parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] =",
"self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>'",
"which may. Therefore, these tests are included to ensure such",
"\"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile. \"\"\" def",
"options, logging_level = parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self):",
"\"\"\" Test Extension loading with non-existant class name (`path.to.module:Class`). \"\"\"",
"= '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">'",
"'_begin') self.assertEqual(list(r), ['b', 'c']) # Add before first item r.add('a',",
"item r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c']) # Added to beginning",
"the `__dir__` attribute of the class as it replaces the",
"remove this when deprecated __setitem__ is removed. with warnings.catch_warnings(record=True) as",
"xhtml serializers. \"\"\" def testHtml(self): \"\"\" Test HTML serialization. \"\"\"",
"in w)) class TestErrors(unittest.TestCase): \"\"\" Test Error Reporting. \"\"\" def",
"\"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\"",
"Test Extension loading with a class instance. \"\"\" from markdown.extensions.footnotes",
"class TestErrors(unittest.TestCase): \"\"\" Test Error Reporting. \"\"\" def setUp(self): #",
"testRegistryIter(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
"BSD (see LICENSE.md for details). Python-Markdown Regression Tests ================================ Tests",
"'<div><p>*some* <span>*more* <span>*text* <span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>' ) class",
"string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of the Markdown class.",
"3 if not PY3: def bytes(string, encoding): return string.encode(encoding) class",
"tree has a new line tail \"\"\" root = markdown.util.etree.Element('root')",
"False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted, True)",
"text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\" Test BlockParser.parseDocument.",
"el = markdown.util.etree.Element('MixedCase') el.text = 'not valid ' em =",
"= markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test that an extension can",
"x in w)) class TestErrors(unittest.TestCase): \"\"\" Test Error Reporting. \"\"\"",
"} } import json self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c', self.tempfile])",
"r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c']) #",
"tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options, logging_level = parse_options([])",
"self.default_options['output'] = 'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self):",
"failure of an extension to load. \"\"\" self.assertRaises( ImportError, markdown.Markdown,",
"xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\" Build an extension which registers",
"registry. \"\"\" def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self):",
"'<!--foo-->' ) def testCommentPrettify(self): \"\"\" Test that an ElementTree Comment",
"'PLACE_MARKER': '~~~footnotes~~~' } } import json self.create_config_file(json.dumps(config)) options, logging_level =",
"None) non_element.text = 'non-element text' script = markdown.util.etree.SubElement(non_element, 'script') script.text",
"an extension can exclude parent tags when dealing with a",
"markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test that an extension can exclude",
"import DEBUG, WARNING, CRITICAL import yaml import tempfile from io",
"as fp: fp.write(config) def testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks': {",
"as w: # Cause all warnings to always be triggered.",
"outfile, outfd def testFileNames(self): infile, outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile,",
"deregister non-existant item with strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1) with",
"markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\" Build an extension",
"return el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs):",
"# with self.assertRaises(TypeError): # del r['a'] # TODO: remove this",
"testBadOutputFormat(self): \"\"\" Test failure on bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown,",
"el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo",
"r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c', 10) del r['b'] self.assertEqual(list(r), ['a',",
"<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text",
"self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests",
"Test blank input. \"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\" Test",
"\"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\"",
"= False repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self): r = markdown.util.Registry()",
"markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test that",
"~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\"",
"__repr__(self): return repr(self.data) def __eq__(self, other): return self.data == other",
"logging_level = parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self):",
"extension can exclude parent tags when dealing with a tail.",
"self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self): \"\"\" Test",
"'p') p.text = markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new),",
"def setUp(self): \"\"\" Create instance of Markdown. \"\"\" self.md =",
"in the current instance. \"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|'",
"div = markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div,",
"self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of Command",
"a regular string is parsed. \"\"\" tree = markdown.util.etree.Element('div') p",
"= markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text*",
"that an ElementTree Comment passes the `is Comment` test. \"\"\"",
"PY3 = sys.version_info[0] == 3 if not PY3: def bytes(string,",
"['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options, logging_level = parse_options([ '-x',",
"30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self):",
"markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile. \"\"\" def setUp(self):",
"import tempfile from io import BytesIO from xml.etree.ElementTree import ProcessingInstruction",
"sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO() def tearDown(self): sys.stdin,",
"appended escapes are only in the current instance. \"\"\" md",
"Tests block kHTML append. \"\"\" def testBlockAppend(self): \"\"\" Test that",
"# TODO: remove this when deprecated __del__ is removed. with",
"'>b') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c']) # Add after",
"'<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer return",
"warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r), ['a']) r['b']",
"br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class",
"self.assertEqual(list(r), ['a', 'a1', 'b', 'c']) # Add after non-last item",
"markdown.Markdown().parser def testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\")",
"testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html'",
"outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r') as",
"True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\" Test State.reset().",
"item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c'])",
"setUp(self): # Set warnings to be raised as errors warnings.simplefilter('error')",
"= markdown.util.etree.SubElement(el, 'p') p.text = 'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el,",
"Test that an ElementTree Comment passes the `is Comment` test.",
"options, logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options, logging_level",
"testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\" lines = ['#foo', '', 'bar',",
"item with strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError): #",
"Test HtmlStash.store with additional blocks. \"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder,",
"'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text = 'non-element",
"regular string is parsed. \"\"\" tree = markdown.util.etree.Element('div') p =",
"tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string,",
"Add before non-first item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1',",
"= '2' ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2' self.assertEqual(",
"of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started",
"parse_options from logging import DEBUG, WARNING, CRITICAL import yaml import",
"class AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config = {}",
"' em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el, 'HR')",
"Extension loading with a class instance. \"\"\" from markdown.extensions.footnotes import",
"self.tempfile = '' def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self):",
"qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def",
"self.inlineprocessor = md.treeprocessors['inline'] def testString(self): \"\"\" Test that a regular",
"'<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p",
"from xml.etree.ElementTree import ProcessingInstruction PY3 = sys.version_info[0] == 3 if",
") def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class",
"removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'),",
"0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\" A dummy Registry item",
"'ancestor-test', 0) def setUp(self): \"\"\"Setup markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()])",
"/>\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' )",
"def testLoadExtensionFailure(self): \"\"\" Test failure of an extension to load.",
"\"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class",
"self.assertEqual('test' in md.block_level_elements, True) md2 = markdown.Markdown() self.assertEqual('test' not in",
"'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r =",
"testString(self): \"\"\" Test that a regular string is parsed. \"\"\"",
"testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
"2006 <NAME> (v. 0.2-1.6b) Copyright 2004 <NAME> (the original version)",
"Comment is prettified properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual(",
"= { 'input': None, 'output': None, 'encoding': None, 'output_format': 'xhtml',",
"strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError): # deregister non-existant item with",
"valid ' em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el,",
"= markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString(' *test*')",
"Added to beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c']) #",
"text. \"\"\" if not PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown,",
"testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config = \"\"\"",
"basics of the Markdown class. \"\"\" def setUp(self): \"\"\" Create",
"'<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\"",
"Test Extension loading with an entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def",
"'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options, logging_level",
"True) self.assertIn(item, r) self.assertNotIn('b', r) def testRegistryIter(self): r = markdown.util.Registry()",
"we should certainly support any third party extensions which may.",
") def testXhtml(self): \"\"\"\" Test XHTML serialization. \"\"\" el =",
"def testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"= parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input'] = 'foo.txt'",
"= markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2,",
"parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options, logging_level =",
"'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension':",
"'http://example.com/', 'end_url': '.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~'",
"extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\" Test loading of an Extension",
"self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self): \"\"\"",
"buildExtension(self): \"\"\" Build an extension which registers fakeSerializer. \"\"\" def",
"markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some *text*') new",
"['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r),",
") def testSimpleAtomicString(self): \"\"\" Test that a simple AtomicString is",
"# TODO: remove this when deprecated __setitem__ is removed. with",
"Extension loading with an entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self):",
"self.assertParses(0., False) self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True))",
"self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r), 1)",
"non_element = markdown.util.etree.SubElement(el, None) non_element.text = 'non-element text' script =",
"fd, self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as fp: fp.write(config)",
"def testStoreMore(self): \"\"\" Test HtmlStash.store with additional blocks. \"\"\" placeholder",
"# Create comment node self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'):",
"'') def testSimpleInput(self): \"\"\" Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>')",
"/>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testMixedCaseTags(self): \"\"\"\"",
"def testInstanceExtension(self): \"\"\" Test Extension loading with a class instance.",
"r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c']) # Added to beginning r.add('b',",
"markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x' mn = markdown.util.etree.SubElement(msup, 'mn') mn.text",
"self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test that last <br>",
"*text*' new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def",
"self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def testNestedAtomicString(self): \"\"\" Test that",
"True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\" Tests of",
"def testQNamePreEscaping(self): \"\"\" Test QName that is already partially escaped.",
"markdown.util.etree.Element('MixedCase') el.text = 'not valid ' em = markdown.util.etree.SubElement(el, 'EMPHASIS')",
"p.text = markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some",
"'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self): options, logging_level = parse_options(['-e', 'utf-8'])",
"'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self):",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c', 20.5)",
"testSimpleAtomicString(self): \"\"\" Test that a simple AtomicString is not parsed.",
"self.assertEqual(options, self.default_options) def testEncodingOption(self): options, logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding']",
"first item r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a', 'b', 'c']) #",
"40) slc = r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b',",
"= markdown.version # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning))",
"def testBooleansParsing(self): self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE', False)",
"Add to end r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1', 'b',",
"<a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\" Test that",
"tearDown(self): sys.stdin, sys.stdout = self.saved def getTempFiles(self, src): \"\"\" Return",
"self.stash.store('foo') def testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter,",
"20) self.assertIs('a' in r, True) self.assertIn(item, r) self.assertNotIn('b', r) def",
"testDotNotationExtension(self): \"\"\" Test Extension loading with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes'])",
"\"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>'",
"r['a'] = Item('a1') self.assertEqual(list(r), ['a1', 'b']) # Check the warnings",
"Add after last item r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1',",
"self.assertParses(True, True) self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0., False)",
"'c', 'a']) def testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'),",
"text = 'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def",
"parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self): options, logging_level",
"r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self): r = markdown.util.Registry() item =",
"self.assertIs(r._is_sorted, True) def testDeregister(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r),",
"20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'),",
"additional blocks. \"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2)",
"def testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading with class name (`path.to.module:Class`).",
"= markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\"",
"prettified properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n'",
"span1.tail = markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some*",
"def testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url':",
"markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of Command Line",
"output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test failure",
"self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self):",
"= config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks':",
"import BytesIO from xml.etree.ElementTree import ProcessingInstruction PY3 = sys.version_info[0] ==",
"20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c', 'a']) def testIsSorted(self): r",
"display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>'",
"<NAME> (v. 0.2-1.6b) Copyright 2004 <NAME> (the original version) License:",
"'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of Command Line Interface",
"Copyright 2004 <NAME> (the original version) License: BSD (see LICENSE.md",
"'end_url': '.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' }",
"def testSimpleAtomicString(self): \"\"\" Test that a simple AtomicString is not",
"= parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self):",
"import markdown import warnings from markdown.__main__ import parse_options from logging",
"self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config = {",
"import yaml import tempfile from io import BytesIO from xml.etree.ElementTree",
"class TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile. \"\"\" def setUp(self): self.saved",
"textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc': { 'title': 'Some Title', 'anchorlink':",
"only in the current instance. \"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|')",
"self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test failure of an",
"self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment else:",
"\"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading",
"self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test the html and xhtml",
"self.default_options) def testExtensionOption(self): options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] =",
"'test_comment'): self.test_comment = markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self):",
"\"\"\"\" Test XHTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">')",
"{ 'PLACE_MARKER': '~~~footnotes~~~' } } import json self.create_config_file(json.dumps(config)) options, logging_level",
"triggered. warnings.simplefilter(\"always\") # Trigger a warning. version = markdown.version #",
"parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options, logging_level = parse_options(['foo.txt']) self.default_options['input']",
"setUp(self): # Create comment node self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree,",
"def testNoLazyOlOption(self): options, logging_level = parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options,",
"'~~~footnotes~~~' } } self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs']",
"} self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config",
"after non-last item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1', 'b',",
"r['a'] self.assertIs(r._is_sorted, True) r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted",
"<NAME> (http://www.dwerg.net/). Maintained for a few years by <NAME> (http://www.freewisdom.org).",
"markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text* ')",
"md): \"\"\"Modify inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test',",
"self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self): \"\"\" Test failure on bad",
"= tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as fp: fp.write(src) outfd, outfile",
"support any third party extensions which may. Therefore, these tests",
"*args, **kwargs): \"\"\"Initialize.\"\"\" self.config = {} def extendMarkdown(self, md): \"\"\"Modify",
"\"\"\" if not PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source)",
"markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more* ')",
"\"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test Extension loading with Name",
"'', 'bar', '', ' baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree)",
"r = markdown.util.Registry() # Add first item r.add('c', Item('c'), '_begin')",
"BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO() def tearDown(self): sys.stdin, sys.stdout =",
"] self.assertEqual(options, self.default_options) def create_config_file(self, config): \"\"\" Helper to create",
"r = markdown.util.Registry() with self.assertRaises(TypeError): r[0] = 'a' # TODO:",
"def testOutputFormatOption(self): options, logging_level = parse_options(['-o', 'html']) self.default_options['output_format'] = 'html'",
"markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'),",
"\"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo'])",
"src): \"\"\" Return the file names for two temp files.",
"self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a'])",
"'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options, logging_level",
"extension to load. \"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def",
"= markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem = markdown.util.etree.SubElement(math, 'semantics') msup",
"testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading with non-existant class name (`path.to.module:Class`).",
"parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes] PLACE_MARKER=",
"self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\")",
"not PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self):",
"r['b'] = Item('b') self.assertEqual(list(r), ['a', 'b']) r['a'] = Item('a1') self.assertEqual(list(r),",
"'p') p.text = 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element =",
"result) def test_ancestors_tail(self): \"\"\" Test that an extension can exclude",
"__del__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b',",
"['a', 'a1', 'b', 'c']) # Add after non-last item r.add('b1',",
"markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests of the",
"options, logging_level = parse_options(['-o', 'html']) self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options)",
"Test HTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p",
"markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute of the class",
"of QName attribute. \"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual(",
"el.text = m.group(2) return el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def",
"self.default_options) def testNoLazyOlOption(self): options, logging_level = parse_options(['-n']) self.default_options['lazy_ol'] = False",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'),",
"instance of Markdown. \"\"\" self.md = markdown.Markdown() def testBlankInput(self): \"\"\"",
"md.block_level_elements, True) md2 = markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements, True)",
"= markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math",
"def textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc': { 'title': 'Some Title',",
"Item('a1') self.assertEqual(list(r), ['a1', 'b']) # Check the warnings self.assertEqual(len(w), 3)",
"markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>'",
"is not parsed. \"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree,",
"\"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self):",
"['foo']) def testStoreMore(self): \"\"\" Test HtmlStash.store with additional blocks. \"\"\"",
"extension which registers fakeSerializer. \"\"\" def fakeSerializer(elem): # Ignore input",
"self.assertEqual(list(r), ['c']) # Added to beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r),",
"class name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def",
"work. These tests should only be a concern when using",
"AtomicString is not parsed. \"\"\" tree = markdown.util.etree.Element('div') p =",
"30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self):",
"Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def",
"'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r),",
"span1 = markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more* ') span2 =",
"Test that a nested AtomicString is not parsed. \"\"\" tree",
"setUp(self): md = markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def testString(self): \"\"\"",
"HtmlStash.store with additional blocks. \"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1))",
"'b') with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r = markdown.util.Registry() with",
"Test loading of an Extension with no makeExtension function. \"\"\"",
"\"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True) md2",
"]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def",
"testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue')",
"with a tail. \"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result",
"infd, infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as fp: fp.write(src)",
"def testNestedAtomicString(self): \"\"\" Test that a nested AtomicString is not",
"{} def extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\" pattern = r'(\\+)([^\\+]+)\\1'",
"TestBlockParserState(unittest.TestCase): \"\"\" Tests of the State class for BlockParser. \"\"\"",
"Item('a') r.register(item, 'a', 20) self.assertIs('a' in r, True) self.assertIn(item, r)",
"io import BytesIO from xml.etree.ElementTree import ProcessingInstruction PY3 = sys.version_info[0]",
"return hardcoded output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md):",
"= self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def testNestedAtomicString(self): \"\"\"",
"'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3] def",
"self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config = {",
"a non Extension object as an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown,",
"'<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' ) def testQNameAttribute(self): \"\"\"",
"fp: fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html') return infile, outfile, outfd",
"markdown lib. \"\"\" from __future__ import unicode_literals import unittest import",
"self.default_options) def testEncodingOption(self): options, logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding'] =",
"deprecated __setitem__ is removed. # with self.assertRaises(TypeError): # r['a'] =",
"\"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text =",
"testNoOptions(self): options, logging_level = parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def",
"markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\" Element",
"def testFileNames(self): infile, outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with",
"json self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config",
"= self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\"",
"class testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree Comments work. These tests",
"= markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*')",
"7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) class TestErrors(unittest.TestCase): \"\"\"",
"markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString(' *with*')",
"tags in ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test.",
"'d', 'e']) with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') # Check the",
"[], 'extension_configs': {}, } self.tempfile = '' def tearDown(self): if",
"'<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' ) def testQNameAttribute(self):",
"self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\" Test that",
"when using cElementTree with third party serializers (including markdown's (x)html",
"logging_level = parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input'] =",
"outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r') as fp:",
"new line tail \"\"\" root = markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root,",
"WARNING) def testNoisyOption(self): options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def",
"return repr(self.data) def __eq__(self, other): return self.data == other class",
"'<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail",
"markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test Extension loading with Name (`path.to.module`).",
"'<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>'",
"source text. \"\"\" if not PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError,",
"'permalink': True } } self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile])",
"del r['badname'] del r['c'] self.assertEqual(list(r), []) # Check the warnings",
"import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test Extension loading with",
"list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES =",
"'a']) def testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a',",
"version_info = markdown.version_info # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category,",
"'not valid ' em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html'",
"in md.ESCAPED_CHARS, True) md2 = markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS,",
"el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text",
"dir_attr = dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__', dir_attr) self.assertNotIn('version_info', dir_attr) self.assertIn('__version_info__',",
"logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options, logging_level =",
"parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config",
"{ 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html', 'html_class': 'test', },",
"\"\"\" Test serialization of QName attribute. \"\"\" div = markdown.util.etree.Element('div')",
"ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>'",
"\"\"\" Tests exclusion of tags in ancestor list. \"\"\" class",
"\"\"\" self.parser = markdown.Markdown().parser def testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\"",
"options, logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options, logging_level",
"tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as fp: fp.write(config) def testExtensionConfigOption(self): config",
"ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\" Test loading of",
"with an entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test",
"output_format='invalid') def testLoadExtensionFailure(self): \"\"\" Test failure of an extension to",
"Test State when empty. \"\"\" self.assertEqual(self.state, []) def testSetSate(self): \"\"\"",
"markdown.util.etree.SubElement(tree, 'p') p.text = 'some *text*' new = self.inlineprocessor.run(tree) self.assertEqual(",
"TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of tags in ancestor list. \"\"\"",
"self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) class TestErrors(unittest.TestCase): \"\"\" Test",
"= 'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el,",
"'<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>' )",
"def testQNameAttribute(self): \"\"\" Test serialization of QName attribute. \"\"\" div",
"self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as fp: fp.write(config) def",
"span3 = markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString('",
"self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\" Test that an extension",
"def testOutputFileOption(self): options, logging_level = parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html'",
"warnings.simplefilter(\"always\") r = markdown.util.Registry() # Add first item r.add('c', Item('c'),",
"'span') span2.text = markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2, 'span') span3.text",
"\"\"\" Test parsing of Command Line Interface Options. \"\"\" def",
"self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> ' '*to*</span> *test*</span>",
"\"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] ) def testLoadBadExtension(self): \"\"\" Test",
"= fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8'))",
"m, data): \"\"\" Handle match. \"\"\" el = markdown.util.etree.Element(self.tag) el.text",
"self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\" Test",
"xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>' '</math>' '</div>'",
"Test the html and xhtml serializers. \"\"\" def testHtml(self): \"\"\"",
"Test falure on non-unicode source text. \"\"\" if not PY3:",
"<NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown",
"\"\"\" Test that a regular string is parsed. \"\"\" tree",
"that an ElementTree Comment is prettified properly. \"\"\" pretty =",
"an extension to load. \"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext'] )",
"\"\"\" md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True) md2",
"def testDotNotationExtension(self): \"\"\" Test Extension loading with Name (`path.to.module`). \"\"\"",
"parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes',",
"\"\"\" Python Markdown A Python implementation of <NAME>'s Markdown. Documentation:",
"r.add('f', Item('f'), 'badlocation') # Check the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category,",
"self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True))",
"Tests of the State class for BlockParser. \"\"\" def setUp(self):",
"r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted =",
"tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some*",
"self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self): \"\"\"",
"tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some",
"= markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\"",
"\"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2')",
"'</div>' ) def testQNameAttribute(self): \"\"\" Test serialization of QName attribute.",
"options, logging_level = parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def",
"\"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el),",
"should certainly support any third party extensions which may. Therefore,",
"testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
"version is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause all",
"self.assertRaises(ValueError): # deregister non-existant item with strict=True r.deregister('e') self.assertEqual(list(r), ['a'])",
"def testNonUnicodeSource(self): \"\"\" Test falure on non-unicode source text. \"\"\"",
"data): self.data = data def __repr__(self): return repr(self.data) def __eq__(self,",
"self.default_options) def create_config_file(self, config): \"\"\" Helper to create temp config",
"utf-8 -*- \"\"\" Python Markdown A Python implementation of <NAME>'s",
"= 'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options, logging_level = parse_options(['-n'])",
"that version info is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: #",
"Test that a regular string is parsed. \"\"\" tree =",
"self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r = markdown.util.Registry()",
"logging_level = parse_options(['-o', 'html']) self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options) def",
"text' ) def testXhtml(self): \"\"\"\" Test XHTML serialization. \"\"\" el",
"handleMatch(self, m, data): \"\"\" Handle match. \"\"\" el = markdown.util.etree.Element(self.tag)",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'),",
"os.fdopen(fd, 'w') as fp: fp.write(config) def testExtensionConfigOption(self): config = {",
"class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES = ('a',) def",
"self.assertEqual('test' not in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion",
") class testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings are honored (not",
"Test that an ElementTree Comment serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment),",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c',",
"is removed. # with self.assertRaises(TypeError): # del r['a'] # TODO:",
"root = markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root),",
"\"\"\" def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r),",
"foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\" Test serialization of QName with",
"Add after non-last item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1',",
"\"\"\" from __future__ import unicode_literals import unittest import sys import",
"testBaseExtention(self): \"\"\" Test that the base Extension class will raise",
"\"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\"",
"True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self):",
"no tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError,",
"cElementTree with third party serializers (including markdown's (x)html serializer). While",
"that is already partially escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div')",
"markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\" Test that a",
"Extension loading with non-existant class name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError,",
"20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False) r['a']",
"\\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings",
"*text*</p></div>' ) def testNestedAtomicString(self): \"\"\" Test that a nested AtomicString",
"all warnings to always be triggered. warnings.simplefilter(\"always\") # Trigger a",
"class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash. \"\"\" def setUp(self): self.stash",
"{}, } self.tempfile = '' def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile)",
"sem = markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem, 'msup') mi =",
"['b', 'a']) def testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"hardcoded output return '<div><p>foo</p></div>' class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake']",
"BytesIO(bytes('foo', encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>')",
"def extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self):",
"'<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests of the BlockParser class. \"\"\"",
"'extension_configs': {}, } self.tempfile = '' def tearDown(self): if os.path.isfile(self.tempfile):",
"\"\"\" infd, infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as fp:",
"Regression Tests ================================ Tests of the various APIs with the",
"r['a'] # TODO: remove this when deprecated __del__ is removed.",
"result = \"\"\"<p>Some <strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test),",
"self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\" Test HtmlStash.store",
"party serializers (including markdown's (x)html serializer). While markdown doesn't use",
"doesn't use ElementTree.Comment itself, we should certainly support any third",
"'html']) self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options, logging_level",
"'b', 15) r.register(Item('c'), 'c', 10) del r['b'] self.assertEqual(list(r), ['a', 'c'])",
"markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True) md2 = markdown.Markdown() self.assertEqual('|'",
"self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"to always be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version_info",
"\"\"\" test = \"\"\" Some +test+ and a [+link+](http://test.com) \"\"\"",
"# Reset warning behavior back to default warnings.simplefilter('default') def testNonUnicodeSource(self):",
"= 'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self): options,",
"= markdown.version_info # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning))",
"'c']) # Add after non-last item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r),",
"party extensions which may. Therefore, these tests are included to",
"of Markdown. \"\"\" self.md = markdown.Markdown() def testBlankInput(self): \"\"\" Test",
"(https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown Project (v. 1.7 and",
"def testBlankState(self): \"\"\" Test State when empty. \"\"\" self.assertEqual(self.state, [])",
"self.assertEqual('|' not in md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests block",
"self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\" A dummy",
"source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self): \"\"\" Test",
"= markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some* ')",
"# TODO: restore this when deprecated __setitem__ is removed. #",
"'b']) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for",
"(v. 1.7 and later) Copyright 2004, 2005, 2006 <NAME> (v.",
"= md.treeprocessors['inline'] def testString(self): \"\"\" Test that a regular string",
"'<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\" Test that a simple",
"class registerFakeSerializer(markdown.extensions.Extension): def extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer return registerFakeSerializer()",
"('a',) def handleMatch(self, m, data): \"\"\" Handle match. \"\"\" el",
"r.deregister('c', strict=False) self.assertEqual(len(r), 1) # deregister non-existant item with strict=False",
"def testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual(",
"of tag case. \"\"\" el = markdown.util.etree.Element('MixedCase') el.text = 'not",
"False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError,",
"Title', 'anchorlink': True, 'permalink': True } } self.create_config_file(config) options, logging_level",
"'<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' )",
"when deprecated __del__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\")",
"= 'x' mn = markdown.util.etree.SubElement(msup, 'mn') mn.text = '2' ann",
"p = markdown.util.etree.SubElement(tree, 'p') p.text = 'some *text*' new =",
"{ 'markdown.extensions.toc': { 'title': 'Some Title', 'anchorlink': True, 'permalink': True",
"False) self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\" Test State.reset(). \"\"\" self.state.set('a_state')",
"tag. \"\"\" div = markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math",
"return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ),",
"= 'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self): options, logging_level = parse_options(['-f',",
"'.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } }",
"\"\"\" Test Error Reporting. \"\"\" def setUp(self): # Set warnings",
"CRITICAL) def testQuietOption(self): options, logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def",
"markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem =",
"\"\"\" Test BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\") text = 'foo'",
"r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r),",
"self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG)",
"\"\"\" Test HtmlStash.store with additional blocks. \"\"\" placeholder = self.stash.store('bar')",
"config = { 'markdown.extensions.toc': { 'title': 'Some Title', 'anchorlink': True,",
"markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\" Test",
"DeprecationWarning) for x in w)) def testRegistryDelItem(self): r = markdown.util.Registry()",
"'c', 'd', 'e']) with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') # Check",
"in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of tags",
"Markdown. \"\"\" self.md = markdown.Markdown() def testBlankInput(self): \"\"\" Test blank",
"markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'),",
"True) self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None',",
"md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def setUp(self): \"\"\"Setup markdown object.\"\"\" self.md",
"'test', }, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config) options,",
"\"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self): \"\"\" Test failure on",
"data def __repr__(self): return repr(self.data) def __eq__(self, other): return self.data",
"'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self): with",
"are included to ensure such support is maintained. \"\"\" def",
"ElementTree Comments work. These tests should only be a concern",
"self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def testBadQNameTag(self): \"\"\" Test serialization",
"def testReset(self): \"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks,",
"which registers fakeSerializer. \"\"\" def fakeSerializer(elem): # Ignore input and",
"class testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings are honored (not parsed).",
"baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()),",
"r['c'] self.assertEqual(list(r), []) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category,",
"beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c']) # Add before",
"self.assertEqual(len(r), 1) with self.assertRaises(ValueError): # deregister non-existant item with strict=True",
"<span>*text* <span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def",
"markdown.util.etree.Element(self.tag) el.text = m.group(2) return el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension):",
"= markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test that an ElementTree Comment",
"a [+link+](http://test.com) \"\"\" result = \"\"\"<p>Some <strong>test</strong> and a <a",
"markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\" lines",
"markdown.util.Registry() with self.assertRaises(TypeError): r[0] = 'a' # TODO: restore this",
"config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def",
"r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted = False repr(r) self.assertIs(r._is_sorted, True) def",
"by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright 2007-2018",
"markdown.__main__ import parse_options from logging import DEBUG, WARNING, CRITICAL import",
"an entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test Extension",
"match. \"\"\" el = markdown.util.etree.Element(self.tag) el.text = m.group(2) return el,",
"class TestBlockParser(unittest.TestCase): \"\"\" Tests of the BlockParser class. \"\"\" def",
"self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\"",
"simple AtomicString is not parsed. \"\"\" tree = markdown.util.etree.Element('div') p",
"self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character",
"of an Extension with no makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown,",
"Registry item object for testing. \"\"\" def __init__(self, data): self.data",
"tail \"\"\" root = markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail,",
"as w: warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r), ['a']) r['b'] =",
"30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3] def testRegistryGetItemByItem(self):",
"\"\"\" def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def",
"Create comment node self.comment = markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment",
"def test_ancestors(self): \"\"\" Test that an extension can exclude parent",
"<NAME> (http://www.freewisdom.org). Currently maintained by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and",
"pattern = r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def setUp(self): \"\"\"Setup",
"(https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright 2007-2018 The Python",
"self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options,",
"fakeSerializer. \"\"\" def fakeSerializer(elem): # Ignore input and return hardcoded",
"\"\"\" Test input of only whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '')",
"def setUp(self): self.state = markdown.blockparser.State() def testBlankState(self): \"\"\" Test State",
"\"\"\" Test failure on bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid')",
"'b']) r['a'] = Item('a1') self.assertEqual(list(r), ['a1', 'b']) # Check the",
"= self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> ' '*to*</span>",
"the processor registry. \"\"\" def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'),",
"self.assertEqual(self.state.isstate('missing'), False) def testReset(self): \"\"\" Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset()",
"Reporting. \"\"\" def setUp(self): # Set warnings to be raised",
"self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile = BytesIO(bytes('foo', encoding='utf-8')) outfile =",
"maintained by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright",
"\"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, []) class Item(object): \"\"\" A",
"= \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c',",
"def testBaseExtention(self): \"\"\" Test that the base Extension class will",
"'r') as fp: output = fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self):",
"new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> '",
"logging_level = parse_options(['-e', 'utf-8']) self.default_options['encoding'] = 'utf-8' self.assertEqual(options, self.default_options) def",
"r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c', 'a']) def",
"\"\"\"Test that version info is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w:",
"from io import BytesIO from xml.etree.ElementTree import ProcessingInstruction PY3 =",
"20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError):",
"self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' ) def testXHTMLOutput(self):",
"TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML append. \"\"\" def testBlockAppend(self): \"\"\"",
"with class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests",
"not in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of",
"infile, outfile, outfd = self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r')",
"self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test that an ElementTree Comment",
"def setUp(self): \"\"\"Setup markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self):",
"'a']) def testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1', 'b', 'c']) # Add",
"setUp(self): \"\"\"Setup markdown object.\"\"\" self.md = markdown.Markdown(extensions=[TestAncestorExclusion.AncestorExtension()]) def test_ancestors(self): \"\"\"",
"removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r),",
"import os import markdown import warnings from markdown.__main__ import parse_options",
"'a1', 'b', 'b1', 'c']) # Add after last item r.add('d',",
"encoding='utf-8')) outfile = BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def",
"Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def",
"self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config",
"testRegistrySetItem(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r[0] = 'a' #",
"testGetIndexForName(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
"r._is_sorted = False repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self): r =",
"Error Reporting. \"\"\" def setUp(self): # Set warnings to be",
"is prettified properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment),",
"serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el,",
"'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options, logging_level = parse_options(['-n']) self.default_options['lazy_ol']",
"logging_level = parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options) def testExtensionOption(self):",
"that appended escapes are only in the current instance. \"\"\"",
") class testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests \"\"\" def setUp(self):",
"testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests of",
"instance. \"\"\" md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True)",
"2004 <NAME> (the original version) License: BSD (see LICENSE.md for",
"fp: output = fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile =",
"encoding='utf-8')) sys.stdout = BytesIO() def tearDown(self): sys.stdin, sys.stdout = self.saved",
"r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted = False repr(r)",
"def testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError):",
"output = fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile = BytesIO(bytes('foo',",
"GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/). Maintained for",
"r.register(Item('b'), 'b', 21) r.register(Item('c'), 'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b',",
"HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self):",
"TODO: restore this when deprecated __del__ is removed. # with",
"\"\"\" Test that a nested AtomicString is not parsed. \"\"\"",
"self.assertEqual(options, self.default_options) def testOutputFormatOption(self): options, logging_level = parse_options(['-o', 'html']) self.default_options['output_format']",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'),",
"# Add to end r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1',",
"few years by <NAME> (http://www.freewisdom.org). Currently maintained by <NAME> (https://github.com/waylan),",
"def testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] =",
") def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' )",
"files. \"\"\" infd, infile = tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as",
"False) def testReset(self): \"\"\" Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state,",
"markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\" Test that the base",
"testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' ) def",
"[ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def create_config_file(self, config): \"\"\"",
"*with*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span>",
"setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test that last",
"text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>' 'non-element",
"\"\"\" Test State when empty. \"\"\" self.assertEqual(self.state, []) def testSetSate(self):",
"r[0] = 'a' # TODO: restore this when deprecated __setitem__",
"triggered. warnings.simplefilter(\"always\") # Trigger a warning. version_info = markdown.version_info #",
"'title': 'Some Title', 'anchorlink': True, 'permalink': True } } self.create_config_file(config)",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b')",
"testNonExtension(self): \"\"\" Test loading a non Extension object as an",
"def testBlankInput(self): \"\"\" Test blank input. \"\"\" self.assertEqual(self.md.convert(''), '') def",
"markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests \"\"\"",
"parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character append.",
") def testBaseExtention(self): \"\"\" Test that the base Extension class",
"'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with",
"ProcessingInstruction PY3 = sys.version_info[0] == 3 if not PY3: def",
"when deprecated __del__ is removed. # with self.assertRaises(TypeError): # del",
"removed. # with self.assertRaises(TypeError): # del r['a'] # TODO: remove",
"'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def",
"[***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class",
"def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading with non-existant class name",
"r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r), 1) # deregister non-existant",
"serialization of QName tag. \"\"\" div = markdown.util.etree.Element('div') qname =",
"this when deprecated __setitem__ is removed. # with self.assertRaises(TypeError): #",
"self.default_options['extensions'] = ['markdown.extensions.footnotes'] self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options, logging_level =",
"name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self):",
"self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class",
"r['c'] def testRegistrySetItem(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r[0] =",
"self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none', False) def testPreserveNone(self):",
"['a']) r['b'] = Item('b') self.assertEqual(list(r), ['a', 'b']) r['a'] = Item('a1')",
") def testQNameAttribute(self): \"\"\" Test serialization of QName attribute. \"\"\"",
"w: # Cause all warnings to always be triggered. warnings.simplefilter(\"always\")",
"self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash.",
"30) r.register(Item('c'), 'c', 40) slc = r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc,",
"version info is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause",
"escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual(",
"a concern when using cElementTree with third party serializers (including",
"os.fdopen(infd, 'w') as fp: fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html') return",
"href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\" Test that an",
"= { 'markdown.extensions.toc': { 'title': 'Some Title', 'anchorlink': True, 'permalink':",
"with no makeExtension function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self):",
"Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset()",
"tearDown(self): # Reset warning behavior back to default warnings.simplefilter('default') def",
"Tests basics of the Markdown class. \"\"\" def setUp(self): \"\"\"",
"test = \"\"\" Some +test+ and a [+link+](http://test.com) \"\"\" result",
"self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase):",
"= 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None)",
"\"\"\" Test that an extension can exclude parent tags. \"\"\"",
"registers fakeSerializer. \"\"\" def fakeSerializer(elem): # Ignore input and return",
"\"\"\" if not isinstance(config, markdown.util.string_type): # convert to string config",
"\"\"\" Test that an ElementTree Comment serializes properly. \"\"\" self.assertEqual(",
"def testBlockAppend(self): \"\"\" Test that appended escapes are only in",
"= 'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self): options, logging_level = parse_options(['-e',",
"markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\" Test QName escaping. \"\"\" qname",
"create temp config files. \"\"\" if not isinstance(config, markdown.util.string_type): #",
"Test Error Reporting. \"\"\" def setUp(self): # Set warnings to",
"return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of the Markdown",
"is removed. # with self.assertRaises(TypeError): # r['a'] = 'a' #",
"testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\") text =",
"'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None) non_element.text",
"def setUp(self): self.saved = sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8'))",
"behavior back to default warnings.simplefilter('default') def testNonUnicodeSource(self): \"\"\" Test falure",
"self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests escape character append. \"\"\" def",
"\"\"\" Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state',",
"markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>'",
"Test that an ElementTree Comment is prettified properly. \"\"\" pretty",
"['#foo', '', 'bar', '', ' baz'] tree = self.parser.parseDocument(lines) self.assertIsInstance(tree,",
"item r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a', 'b', 'c']) # Add",
"HtmlStash. \"\"\" def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo')",
"markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests",
"APIs with the python markdown lib. \"\"\" from __future__ import",
"warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'],",
"['b2', 'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r",
"\"\"\" def setUp(self): self.state = markdown.blockparser.State() def testBlankState(self): \"\"\" Test",
"ensure such support is maintained. \"\"\" def setUp(self): # Create",
"\"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el),",
"registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>'",
"an ElementTree Comment serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' )",
"r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b',",
"logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL) def testVerboseOption(self): options, logging_level =",
"blocks. \"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual(",
") def testParseDocument(self): \"\"\" Test BlockParser.parseDocument. \"\"\" lines = ['#foo',",
"r.register(Item('c'), 'c', 40) slc = r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry)",
"the module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__', dir_attr) self.assertNotIn('version_info',",
"the current instance. \"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in",
"markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True) md2 = markdown.Markdown() self.assertEqual('test'",
"Build an extension which registers fakeSerializer. \"\"\" def fakeSerializer(elem): #",
"'missing_file.yaml']) def testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\"",
"Copyright 2004, 2005, 2006 <NAME> (v. 0.2-1.6b) Copyright 2004 <NAME>",
"remove this when deprecated __del__ is removed. with warnings.catch_warnings(record=True) as",
"def testNoisyOption(self): options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self):",
"\"\"\" Handle match. \"\"\" el = markdown.util.etree.Element(self.tag) el.text = m.group(2)",
"config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc': {",
"TODO: remove this when deprecated __del__ is removed. with warnings.catch_warnings(record=True)",
"AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config = {} def",
"\"\"\" Tests basics of the Markdown class. \"\"\" def setUp(self):",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r), ['a',",
"when dealing with a tail. \"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com)",
"= markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment else: self.test_comment",
"with additional blocks. \"\"\" placeholder = self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter,",
"markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' )",
"markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self): \"\"\" Test that last <br> in tree",
"\"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile]) class TestEscapeAppend(unittest.TestCase): \"\"\" Tests",
"el) def testQNameEscaping(self): \"\"\" Test QName escaping. \"\"\" qname =",
"self.assertEqual('|' in md.ESCAPED_CHARS, True) md2 = markdown.Markdown() self.assertEqual('|' not in",
"self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\" Test Extension loading with a",
"testLoadBadExtension(self): \"\"\" Test loading of an Extension with no makeExtension",
"Test that an extension can exclude parent tags when dealing",
"with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') # Check the warnings self.assertEqual(len(w),",
"Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c']) # Add before first item",
"yaml import tempfile from io import BytesIO from xml.etree.ElementTree import",
"empty. \"\"\" self.assertEqual(self.state, []) def testSetSate(self): \"\"\" Test State.set(). \"\"\"",
"Python Markdown A Python implementation of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/",
"{ 'base_url': 'http://example.com/', 'end_url': '.html', 'html_class': 'test', }, 'markdown.extensions.footnotes:FootnotesExtension': {",
"= {} def extendMarkdown(self, md): \"\"\"Modify inline patterns.\"\"\" pattern =",
"= data def __repr__(self): return repr(self.data) def __eq__(self, other): return",
"exclusion of tags in ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\"",
"maintained. \"\"\" def setUp(self): # Create comment node self.comment =",
"self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\" Test that an ElementTree Comment",
"warnings from markdown.__main__ import parse_options from logging import DEBUG, WARNING,",
"\"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\" Tests of the State class",
"self.assertRaises(TypeError): del r['badname'] del r['c'] self.assertEqual(list(r), []) # Check the",
"pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual( markdown.serializers.to_xhtml_string(pi), '<?foo <&\"test\\nescaping\">?>'",
"State when empty. \"\"\" self.assertEqual(self.state, []) def testSetSate(self): \"\"\" Test",
"msup = markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup, 'mi') mi.text =",
"files. \"\"\" if not isinstance(config, markdown.util.string_type): # convert to string",
"a warning. version_info = markdown.version_info # Verify some things self.assertEqual(len(w),",
"markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname) self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el) def testQNameEscaping(self): \"\"\"",
"'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR /></MixedCase>' )",
"= markdown.Markdown() def testBlankInput(self): \"\"\" Test blank input. \"\"\" self.assertEqual(self.md.convert(''),",
"if not isinstance(config, markdown.util.string_type): # convert to string config =",
"input of only whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self):",
"True) def testDeregister(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text'",
"= parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self):",
"= m.group(2) return el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def __init__(self,",
"'c']) # Add before non-first item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r),",
"self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests of the BlockParser class.",
"Return the file names for two temp files. \"\"\" infd,",
"True) r._is_sorted = False repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self): r",
"partially escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname)",
"def fakeSerializer(elem): # Ignore input and return hardcoded output return",
"['a_state', 'state2']) def testIsSate(self): \"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False)",
"class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests of",
"self.assertIs(r._is_sorted, True) r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted =",
"\"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test loading a",
"= '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">'",
"\"\"\" el = markdown.util.etree.Element(self.tag) el.text = m.group(2) return el, m.start(0),",
"QName with no tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el =",
"markdown.util.etree.SubElement(el, 'p') p.text = 'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr')",
"markdown import warnings from markdown.__main__ import parse_options from logging import",
"ANCESTOR_EXCLUDES = ('a',) def handleMatch(self, m, data): \"\"\" Handle match.",
"def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests",
"= markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self): \"\"\" Test HtmlStash.store.",
"r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self):",
"warnings.catch_warnings(record=True) as w: # Cause all warnings to always be",
"r['a'] = Item('a') self.assertEqual(list(r), ['a']) r['b'] = Item('b') self.assertEqual(list(r), ['a',",
"object for testing. \"\"\" def __init__(self, data): self.data = data",
"self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options, logging_level = parse_options(['-q']) self.assertGreater(logging_level, CRITICAL)",
"'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options)",
"mi.text = 'x' mn = markdown.util.etree.SubElement(msup, 'mn') mn.text = '2'",
"it replaces the module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__',",
"\\nbar', output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar',",
"\"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\" Test",
"new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self):",
"years by <NAME> (http://www.freewisdom.org). Currently maintained by <NAME> (https://github.com/waylan), <NAME>",
"self.assertEqual(options, self.default_options) def testMultipleExtensionOptions(self): options, logging_level = parse_options([ '-x', 'markdown.extensions.footnotes',",
"preservation of tag case. \"\"\" el = markdown.util.etree.Element('MixedCase') el.text =",
"def testVerboseOption(self): options, logging_level = parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self):",
"of only whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self): \"\"\"",
"= BytesIO() def tearDown(self): sys.stdin, sys.stdout = self.saved def getTempFiles(self,",
"'anchorlink': True, 'permalink': True } } self.create_config_file(config) options, logging_level =",
"= markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more*",
"p.text = 'some *text*' new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some",
"markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text*",
"def testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url':",
"= 'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self):",
"parent tags when dealing with a tail. \"\"\" test =",
"markdown.util.Registry) def testRegisterWithoutPriority(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def",
"(http://www.freewisdom.org). Currently maintained by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME>",
"Currently maintained by <NAME> (https://github.com/waylan), <NAME> (https://github.com/mitya57) and <NAME> (https://github.com/facelessuser).",
"== other class RegistryTests(unittest.TestCase): \"\"\" Test the processor registry. \"\"\"",
"3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r), 1) # deregister",
"exclude parent tags when dealing with a tail. \"\"\" test",
"'msup') mi = markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x' mn =",
"markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*') span2.tail",
"markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that version info is deprecated.\"\"\" with",
"output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>')",
"html and xhtml serializers. \"\"\" def testHtml(self): \"\"\" Test HTML",
"Handle match. \"\"\" el = markdown.util.etree.Element(self.tag) el.text = m.group(2) return",
"= '' def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options,",
"such support is maintained. \"\"\" def setUp(self): # Create comment",
"'extensions': [], 'extension_configs': {}, } self.tempfile = '' def tearDown(self):",
"Item('b') self.assertEqual(list(r), ['a', 'b']) r['a'] = Item('a1') self.assertEqual(list(r), ['a1', 'b'])",
"\"\"\" def testAppend(self): \"\"\" Test that appended escapes are only",
"self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self): options, logging_level =",
"= markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r = markdown.util.Registry()",
"on bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self): \"\"\"",
"<strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self):",
"self.parser = markdown.Markdown().parser def testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\" root",
"self.assertEqual(options, self.default_options) def create_config_file(self, config): \"\"\" Helper to create temp",
"[+link+](http://test.com) \"\"\" result = \"\"\"<p>Some <strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\"",
"= markdown.Markdown() self.inlineprocessor = md.treeprocessors['inline'] def testString(self): \"\"\" Test that",
"self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\" Test",
"} import json self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs']",
"yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd, 'w') as fp:",
"r['a'] = 'a' # TODO: remove this when deprecated __setitem__",
"from markdown.__main__ import parse_options from logging import DEBUG, WARNING, CRITICAL",
") def testCommentPrettify(self): \"\"\" Test that an ElementTree Comment is",
"'-x', 'markdown.extensions.smarty' ]) self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options,",
"(https://github.com/mitya57) and <NAME> (https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown Project",
"'output_format': 'xhtml', 'lazy_ol': True, 'extensions': [], 'extension_configs': {}, } self.tempfile",
"del r['b'] self.assertEqual(list(r), ['a', 'c']) del r['a'] self.assertEqual(list(r), ['c']) with",
"by <NAME> (http://www.dwerg.net/). Maintained for a few years by <NAME>",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def",
"self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute of the",
"\"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1'])",
"self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False)",
"[]) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for",
"math = markdown.util.etree.SubElement(div, qname) math.set('display', 'block') sem = markdown.util.etree.SubElement(math, 'semantics')",
"self.default_options) def testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output']",
"15) r.register(Item('c'), 'c', 10) del r['b'] self.assertEqual(list(r), ['a', 'c']) del",
"= markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\" Test that an",
"r = markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r =",
"self.assertRaises(TypeError): del r[0] # TODO: restore this when deprecated __del__",
"testInstanceExtension(self): \"\"\" Test Extension loading with a class instance. \"\"\"",
"span3.text = markdown.util.AtomicString('*here*') span3.tail = markdown.util.AtomicString(' *to*') span2.tail = markdown.util.AtomicString('",
"tempfile.mkstemp(suffix='.html') return infile, outfile, outfd def testFileNames(self): infile, outfile, outfd",
"Test QName that is already partially escaped. \"\"\" qname =",
"non-last item r.add('b1', Item('b1'), '>b') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1',",
"class TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML append. \"\"\" def testBlockAppend(self):",
"of the class as it replaces the module's.\"\"\" dir_attr =",
"markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' )",
"'*to*</span> *test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def assertParses(self, value, result):",
"def testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b',",
"= self.stash.store('foo') def testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0))",
"parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options) def testExtensionOption(self): options, logging_level",
"Markdown Project (v. 1.7 and later) Copyright 2004, 2005, 2006",
"'c', 40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r),",
"Extension class will raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()]",
"\"\"\" Test serialization of QName tag. \"\"\" div = markdown.util.etree.Element('div')",
"Item('a') self.assertEqual(list(r), ['a']) r['b'] = Item('b') self.assertEqual(list(r), ['a', 'b']) r['a']",
"markdown.util.etree.Comment('foo') if hasattr(markdown.util.etree, 'test_comment'): self.test_comment = markdown.util.etree.test_comment else: self.test_comment =",
"and later) Copyright 2004, 2005, 2006 <NAME> (v. 0.2-1.6b) Copyright",
"0.2-1.6b) Copyright 2004 <NAME> (the original version) License: BSD (see",
"markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test loading a non Extension",
"\"\"\" Test Markdown's HtmlStash. \"\"\" def setUp(self): self.stash = markdown.util.HtmlStash()",
"False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted = False repr(r) self.assertIs(r._is_sorted, True)",
"in w)) def testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"with strict=False r.deregister('d', strict=False) self.assertEqual(len(r), 1) with self.assertRaises(ValueError): # deregister",
"DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that version info is",
"w: warnings.simplefilter(\"always\") r = markdown.util.Registry() # Add first item r.add('c',",
"'a1', 'b', 'b1', 'c', 'd', 'e']) with self.assertRaises(ValueError): r.add('f', Item('f'),",
"False) def testCommentSerialization(self): \"\"\" Test that an ElementTree Comment serializes",
"and <NAME> (https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown Project (v.",
"logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options, logging_level =",
"20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self): r",
"['c']) with self.assertRaises(TypeError): del r['badname'] del r['c'] self.assertEqual(list(r), []) #",
"that a regular string is parsed. \"\"\" tree = markdown.util.etree.Element('div')",
"= parse_options(['-f', 'foo.html']) self.default_options['output'] = 'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self):",
"m.end(0) class AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config =",
"testDeregister(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
"w)) class TestErrors(unittest.TestCase): \"\"\" Test Error Reporting. \"\"\" def setUp(self):",
"m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config",
"def testProsessingInstruction(self): \"\"\" Test serialization of ProcessignInstruction. \"\"\" pi =",
"for a few years by <NAME> (http://www.freewisdom.org). Currently maintained by",
"r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self):",
"Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd']) #",
"outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class",
"sys.stdout.seek(0) self.assertEqual(sys.stdout.read().decode('utf-8'), '<p>foo</p>') class TestBlockParser(unittest.TestCase): \"\"\" Tests of the BlockParser",
"= Item('a') self.assertEqual(list(r), ['a']) r['b'] = Item('b') self.assertEqual(list(r), ['a', 'b'])",
"testMixedCaseTags(self): \"\"\"\" Test preservation of tag case. \"\"\" el =",
"text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testXhtml(self): \"\"\"\" Test XHTML",
"testCommentPrettify(self): \"\"\" Test that an ElementTree Comment is prettified properly.",
"of ConvertFile. \"\"\" def setUp(self): self.saved = sys.stdin, sys.stdout sys.stdin",
"r'(\\+)([^\\+]+)\\1' md.inlinePatterns.register(TestAncestorExclusion.AncestorExample(pattern, 'strong'), 'ancestor-test', 0) def setUp(self): \"\"\"Setup markdown object.\"\"\"",
"= markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = 'some *text*'",
"Check the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in",
"= markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div foo=\"bar\"></div>' ) def",
"md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True) md2 = markdown.Markdown() self.assertEqual('|' not",
"self.parser.parseDocument(lines) self.assertIsInstance(tree, markdown.util.etree.ElementTree) self.assertIs(markdown.util.etree.iselement(tree.getroot()), True) self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class",
"not parsed. \"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p')",
"r.register(item, 'a', 20) self.assertIs('a' in r, True) self.assertIn(item, r) self.assertNotIn('b',",
"['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self): \"\"\" Test State.isstate().",
"fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual( markdown.markdown( 'baz', extensions=[self.buildExtension()], output_format='fake'",
"__setitem__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a'] =",
"2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a']) def testGetIndexForName(self): r =",
"https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/). Maintained for a few years",
"sys.stdout = self.saved def getTempFiles(self, src): \"\"\" Return the file",
"testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r,",
"'p') p.text = 'some *text*' new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new),",
"'b1', 'c', 'd']) # Add to end r.add('e', Item('e'), '_end')",
"is parsed. \"\"\" tree = markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p')",
"and a [+link+](http://test.com) \"\"\" result = \"\"\"<p>Some <strong>test</strong> and a",
"'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with",
"to string config = yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml') with",
"Test XHTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p",
"True) class TestAncestorExclusion(unittest.TestCase): \"\"\" Tests exclusion of tags in ancestor",
"}, 'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config) options, logging_level",
"2005, 2006 <NAME> (v. 0.2-1.6b) Copyright 2004 <NAME> (the original",
"def testCommentIsComment(self): \"\"\" Test that an ElementTree Comment passes the",
"'badlocation') # Check the warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for",
"# convert to string config = yaml.dump(config) fd, self.tempfile =",
"= ('a',) def handleMatch(self, m, data): \"\"\" Handle match. \"\"\"",
"sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO() def tearDown(self):",
"that version is deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause",
"self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30) self.assertEqual(len(r), 2)",
"Helper to create temp config files. \"\"\" if not isinstance(config,",
"def testNoOptions(self): options, logging_level = parse_options([]) self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL)",
"only be a concern when using cElementTree with third party",
"'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with",
"\"\"\" Build an extension which registers fakeSerializer. \"\"\" def fakeSerializer(elem):",
"self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r = markdown.util.Registry()",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b')",
"10) del r['b'] self.assertEqual(list(r), ['a', 'c']) del r['a'] self.assertEqual(list(r), ['c'])",
"Python Markdown Project (v. 1.7 and later) Copyright 2004, 2005,",
"def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase):",
"def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options, logging_level =",
"Therefore, these tests are included to ensure such support is",
"object as an extension. \"\"\" self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self):",
"deprecated __setitem__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r['a']",
"ElementTree.Comment itself, we should certainly support any third party extensions",
"True) md2 = markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS, True) class",
"other class RegistryTests(unittest.TestCase): \"\"\" Test the processor registry. \"\"\" def",
"that an ElementTree Comment serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->'",
"are only in the current instance. \"\"\" md = markdown.Markdown()",
"r.register(Item('a')) def testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"r = markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted,",
"= markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree)",
"self.default_options) def testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/',",
"= parse_options(['-n']) self.default_options['lazy_ol'] = False self.assertEqual(options, self.default_options) def testExtensionOption(self): options,",
"data): \"\"\" Handle match. \"\"\" el = markdown.util.etree.Element(self.tag) el.text =",
"this when deprecated __del__ is removed. with warnings.catch_warnings(record=True) as w:",
"'>c') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd']) # Add",
"with self.assertRaises(TypeError): r[0] = 'a' # TODO: restore this when",
"non-first item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1', 'b', 'c'])",
"= markdown.util.Registry() r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError): del r[0] #",
"encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics of the",
"\"\"\" Test BlockParser.parseDocument. \"\"\" lines = ['#foo', '', 'bar', '',",
"testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError): del",
"\"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div id=\"foo<&">\">' '<p hidden>foo <&escaped></p>' '<hr>'",
"r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd'])",
"def test_version_info_deprecation(self): \"\"\"Test that version info is deprecated.\"\"\" with warnings.catch_warnings(record=True)",
"failure on bad output_format. \"\"\" self.assertRaises(KeyError, markdown.Markdown, output_format='invalid') def testLoadExtensionFailure(self):",
"self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted,",
"text' script = markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">' el.tail =",
"= markdown.util.etree.Element(self.tag) el.text = m.group(2) return el, m.start(0), m.end(0) class",
"\"\"\" div = markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math =",
"test_ancestors(self): \"\"\" Test that an extension can exclude parent tags.",
"removed. # with self.assertRaises(TypeError): # r['a'] = 'a' # TODO:",
"self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistrySlice(self): r =",
"1) self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\" Test HtmlStash.store with additional",
"serializes properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self): \"\"\"",
"<&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testXhtml(self):",
"markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self): \"\"\" Test that an ElementTree",
"'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid",
"item with strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self): r =",
"module's.\"\"\" dir_attr = dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__', dir_attr) self.assertNotIn('version_info', dir_attr)",
"input. \"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self): \"\"\" Test input of",
"'span') span1.text = markdown.util.AtomicString('*more* ') span2 = markdown.util.etree.SubElement(span1, 'span') span2.text",
"self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config =",
"Test loading a non Extension object as an extension. \"\"\"",
"def testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20)",
"def setUp(self): self.default_options = { 'input': None, 'output': None, 'encoding':",
"original version) License: BSD (see LICENSE.md for details). Python-Markdown Regression",
"of BlockParser. \"\"\" self.parser = markdown.Markdown().parser def testParseChunk(self): \"\"\" Test",
"markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x' mn",
"'output': None, 'encoding': None, 'output_format': 'xhtml', 'lazy_ol': True, 'extensions': [],",
"'~~~footnotes~~~' } } import json self.create_config_file(json.dumps(config)) options, logging_level = parse_options(['-c',",
"r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a') with self.assertRaises(IndexError): r[3]",
"\"\"\" Test loading of an Extension with no makeExtension function.",
"test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute of the class as it",
"test_version_info_deprecation(self): \"\"\"Test that version info is deprecated.\"\"\" with warnings.catch_warnings(record=True) as",
"['b', 'c']) # Add before first item r.add('a', Item('a'), '<b')",
"certainly support any third party extensions which may. Therefore, these",
"in r, True) self.assertIn(item, r) self.assertNotIn('b', r) def testRegistryIter(self): r",
") def testQNameTag(self): \"\"\" Test serialization of QName tag. \"\"\"",
"'markdown.extensions.footnotes:FootnotesExtension': { 'PLACE_MARKER': '~~~footnotes~~~' } } self.create_config_file(config) options, logging_level =",
"result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test",
"Test Extension loading with non-existant class name (`path.to.module:Class`). \"\"\" self.assertRaises(",
"30) self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'),",
"el.text = 'not valid ' em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text",
"em.text = 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not valid <EMPHASIS>html</EMPHASIS><HR",
"'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self): options, logging_level = parse_options(['-f', 'foo.html'])",
"warnings self.assertEqual(len(w), 7) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) class",
"end r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c',",
"extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test loading a non Extension object",
"self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def testReset(self):",
"*test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value,",
"= config self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc':",
"} self.tempfile = '' def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def",
"markdown.util.Registry() # Add first item r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c'])",
"the file names for two temp files. \"\"\" infd, infile",
"\"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor): \"\"\" Ancestor Test. \"\"\" ANCESTOR_EXCLUDES = ('a',)",
"self.assertIs(r._is_sorted, True) r._is_sorted = False repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self):",
"<&\"test\\nescaping\">?>' ) def testQNameTag(self): \"\"\" Test serialization of QName tag.",
"properly. \"\"\" self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self): \"\"\" Test",
"Tests of ConvertFile. \"\"\" def setUp(self): self.saved = sys.stdin, sys.stdout",
"in w)) def testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"'a', 20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False)",
"https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/). Maintained for a",
"\"\"\" root = markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root, text) self.assertEqual(",
"p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some* ') span1 =",
"self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self): \"\"\" Test",
"self.assertEqual(len(r), 1) # deregister non-existant item with strict=False r.deregister('d', strict=False)",
"\"\"\"Tests the `__dir__` attribute of the class as it replaces",
"= markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment) self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\"",
"'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c'] def",
"Ancestor Test. \"\"\" ANCESTOR_EXCLUDES = ('a',) def handleMatch(self, m, data):",
"20) r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError):",
"= markdown.util.Registry() with self.assertRaises(TypeError): r[0] = 'a' # TODO: restore",
"Item('a1'), '<b') self.assertEqual(list(r), ['a', 'a1', 'b', 'c']) # Add after",
") def testBadQNameTag(self): \"\"\" Test serialization of QName with no",
"def testExtensionOption(self): options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions'] = ['markdown.extensions.footnotes']",
"options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options)",
"\"\"\" Tests escape character append. \"\"\" def testAppend(self): \"\"\" Test",
"extendMarkdown(self, md): md.output_formats['fake'] = fakeSerializer return registerFakeSerializer() def testRegisterSerializer(self): self.assertEqual(",
"slc = r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc), ['b', 'a'])",
"def handleMatch(self, m, data): \"\"\" Handle match. \"\"\" el =",
"self.assertEqual(self.state, ['a_state', 'state2']) def testIsSate(self): \"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'),",
"(http://www.dwerg.net/). Maintained for a few years by <NAME> (http://www.freewisdom.org). Currently",
"True) self.assertParses('novalue', None) self.assertParses('yES', True) self.assertParses('FALSE', False) self.assertParses(0., False) self.assertParses('none',",
"(v. 0.2-1.6b) Copyright 2004 <NAME> (the original version) License: BSD",
"Comment passes the `is Comment` test. \"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def",
"'</div>tail text' ) def testMixedCaseTags(self): \"\"\"\" Test preservation of tag",
"that a nested AtomicString is not parsed. \"\"\" tree =",
"in the current instance. \"\"\" md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test'",
"use ElementTree.Comment itself, we should certainly support any third party",
"'<b') self.assertEqual(list(r), ['a', 'a1', 'b', 'c']) # Add after non-last",
"= dir(markdown) self.assertNotIn('version', dir_attr) self.assertIn('__version__', dir_attr) self.assertNotIn('version_info', dir_attr) self.assertIn('__version_info__', dir_attr)",
"= { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html', 'html_class': 'test',",
"r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a', 'b', 'c']) # Add before",
"markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r') as fp: output = fp.read()",
"p.text = markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p, 'span') span1.text =",
"hidden>foo <&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def",
"Cause all warnings to always be triggered. warnings.simplefilter(\"always\") # Trigger",
"'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3)",
"= config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError, parse_options, ['-c', 'missing_file.yaml'])",
"testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'), '<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\"",
"'<div xmlns=\"<&"test escaping">\"></div>' ) def buildExtension(self): \"\"\" Build an extension which",
"with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"class TestBlockParserState(unittest.TestCase): \"\"\" Tests of the State class for BlockParser.",
"1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r = markdown.util.Registry() with self.assertRaises(TypeError):",
"base Extension class will raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown,",
"QName tag. \"\"\" div = markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math')",
"if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options, logging_level = parse_options([]) self.assertEqual(options,",
"'b', 10) self.assertEqual(list(r), ['a', 'b1']) self.assertEqual(len(r), 2) r.register(Item('b2'), 'b', 30)",
"that last <br> in tree has a new line tail",
"text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testMixedCaseTags(self): \"\"\"\" Test preservation",
"testReset(self): \"\"\" Test HtmlStash.reset. \"\"\" self.stash.reset() self.assertEqual(self.stash.html_counter, 0) self.assertEqual(self.stash.rawHtmlBlocks, [])",
"<EMPHASIS>html</EMPHASIS><HR /></MixedCase>' ) def testProsessingInstruction(self): \"\"\" Test serialization of ProcessignInstruction.",
"def testLoadBadExtension(self): \"\"\" Test loading of an Extension with no",
"['a', 'c']) del r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del r['badname']",
"# Add first item r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c']) #",
"\"\"\" Test the html and xhtml serializers. \"\"\" def testHtml(self):",
"class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that version",
"of an extension to load. \"\"\" self.assertRaises( ImportError, markdown.Markdown, extensions=['non_existant_ext']",
"= markdown.util.AtomicString('*some* ') span1 = markdown.util.etree.SubElement(p, 'span') span1.text = markdown.util.AtomicString('*more*",
"markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = markdown.util.AtomicString('*some* ') span1",
"testRegistryGetItemByIndex(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30)",
") def testLoadBadExtension(self): \"\"\" Test loading of an Extension with",
"= \"\"\" Some +test+ and a [+link+](http://test.com) \"\"\" result =",
"self.assertEqual(list(r), ['a', 'b']) r['a'] = Item('a1') self.assertEqual(list(r), ['a1', 'b']) #",
"= parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self):",
"BlockParser.parseDocument. \"\"\" lines = ['#foo', '', 'bar', '', ' baz']",
"testDotNotationExtensionWithClass(self): \"\"\" Test Extension loading with class name (`path.to.module:Class`). \"\"\"",
"= markdown.Markdown().parser def testParseChunk(self): \"\"\" Test BlockParser.parseChunk. \"\"\" root =",
"x in w)) def testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"self.assertEqual( markdown.serializers.to_xhtml_string(tree.getroot()), \"<div><h1>foo</h1><p>bar</p><pre><code>baz\\n</code></pre></div>\" ) class TestBlockParserState(unittest.TestCase): \"\"\" Tests of the",
"with self.assertRaises(TypeError): del r[0] # TODO: restore this when deprecated",
"self.default_options['extensions'] = [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def create_config_file(self,",
"1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that version",
"self.assertEqual(len(r), 2) self.assertEqual(list(r), ['b2', 'a']) def testRegistryDeprecatedAdd(self): with warnings.catch_warnings(record=True) as",
"'e']) with self.assertRaises(ValueError): r.add('f', Item('f'), 'badlocation') # Check the warnings",
"= markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr')",
"Comments work. These tests should only be a concern when",
"self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'), False) def",
"'a1', 'b', 'b1', 'c', 'd']) # Add to end r.add('e',",
"def testAppend(self): \"\"\" Test that appended escapes are only in",
"md.ESCAPED_CHARS, True) md2 = markdown.Markdown() self.assertEqual('|' not in md2.ESCAPED_CHARS, True)",
"[]) class Item(object): \"\"\" A dummy Registry item object for",
"on non-unicode source text. \"\"\" if not PY3: source =",
"to ensure such support is maintained. \"\"\" def setUp(self): #",
"self.assertEqual(options, self.default_options) def testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks': { 'base_url':",
"test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset()",
"# Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x",
"xml.etree.ElementTree import ProcessingInstruction PY3 = sys.version_info[0] == 3 if not",
"r.register(Item('b'), 'b', 30) self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c')",
"'<p>foo</p>') def testInstanceExtension(self): \"\"\" Test Extension loading with a class",
"testBlankInput(self): \"\"\" Test blank input. \"\"\" self.assertEqual(self.md.convert(''), '') def testWhitespaceOnly(self):",
"names for two temp files. \"\"\" infd, infile = tempfile.mkstemp(suffix='.txt')",
"A Python implementation of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/",
"Set warnings to be raised as errors warnings.simplefilter('error') def tearDown(self):",
"self.assertEqual(options, self.default_options) def textBoolExtensionConfigOption(self): config = { 'markdown.extensions.toc': { 'title':",
"def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1)",
"__eq__(self, other): return self.data == other class RegistryTests(unittest.TestCase): \"\"\" Test",
"self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testEncodingOption(self): options, logging_level =",
"'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def create_config_file(self, config): \"\"\" Helper to",
"Tests exclusion of tags in ancestor list. \"\"\" class AncestorExample(markdown.inlinepatterns.SimpleTagInlineProcessor):",
"# Add before non-first item r.add('a1', Item('a1'), '<b') self.assertEqual(list(r), ['a',",
"raise NotImplemented. \"\"\" self.assertRaises( NotImplementedError, markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase):",
"warnings.simplefilter(\"always\") r['a'] = Item('a') self.assertEqual(list(r), ['a']) r['b'] = Item('b') self.assertEqual(list(r),",
"warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r = markdown.util.Registry() # Add first",
"parent tags. \"\"\" test = \"\"\" Some +test+ and a",
"after last item r.add('d', Item('d'), '>c') self.assertEqual(list(r), ['a', 'a1', 'b',",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0],",
"self.saved def getTempFiles(self, src): \"\"\" Return the file names for",
"= self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar']",
"# Added to beginning r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c'])",
"testAppend(self): \"\"\" Test that appended escapes are only in the",
"\"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test that version is deprecated.\"\"\"",
"always be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version_info =",
"XHTML serialization. \"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p =",
"markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\")",
"DEBUG) def testInputFileOption(self): options, logging_level = parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt'",
"with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r = markdown.util.Registry() # Add",
"os import markdown import warnings from markdown.__main__ import parse_options from",
"r = markdown.util.Registry() item = Item('a') r.register(item, 'a', 20) self.assertIs('a'",
"non-existant item with strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self): r",
"self.assertEqual(options, self.default_options) def testOutputFileOption(self): options, logging_level = parse_options(['-f', 'foo.html']) self.default_options['output']",
"warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c', 10) del r['b'] self.assertEqual(list(r),",
"= markdown.util.etree.SubElement(el, None) non_element.text = 'non-element text' script = markdown.util.etree.SubElement(non_element,",
"testRegistryContains(self): r = markdown.util.Registry() item = Item('a') r.register(item, 'a', 20)",
"Test the processor registry. \"\"\" def testCreateRegistry(self): r = markdown.util.Registry()",
"'non-element text' script = markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">' el.tail",
"testQNameAttribute(self): \"\"\" Test serialization of QName attribute. \"\"\" div =",
"Add before first item r.add('a', Item('a'), '<b') self.assertEqual(list(r), ['a', 'b',",
"TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile. \"\"\" def setUp(self): self.saved =",
"'b', 'b1', 'c']) # Add after last item r.add('d', Item('d'),",
"various APIs with the python markdown lib. \"\"\" from __future__",
"['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash. \"\"\" def setUp(self):",
"md2 = markdown.Markdown() self.assertEqual('test' not in md2.block_level_elements, True) class TestAncestorExclusion(unittest.TestCase):",
"fp.write(src) outfd, outfile = tempfile.mkstemp(suffix='.html') return infile, outfile, outfd def",
"math.set('display', 'block') sem = markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem, 'msup')",
"self.assertIs('a' in r, True) self.assertIn(item, r) self.assertNotIn('b', r) def testRegistryIter(self):",
"'</div>tail text' ) def testXhtml(self): \"\"\"\" Test XHTML serialization. \"\"\"",
"'<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\" Test QName that is",
"= \"\"\"<p>Some <strong>test</strong> and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result)",
"def testRegistryContains(self): r = markdown.util.Registry() item = Item('a') r.register(item, 'a',",
"hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def",
"markdown.util.Registry() item = Item('a') r.register(item, 'a', 20) self.assertIs('a' in r,",
"def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config = {} def extendMarkdown(self,",
"simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self): \"\"\" Test Extension",
"testCommentIsBlockLevel(self): \"\"\" Test that an ElementTree Comment is recognized as",
"'state2']) def testIsSate(self): \"\"\" Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state')",
"'<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testXhtml(self): \"\"\"\" Test XHTML serialization.",
"PY3: source = \"foo\".encode('utf-16') self.assertRaises(UnicodeDecodeError, markdown.markdown, source) def testBadOutputFormat(self): \"\"\"",
"testBrTailNoNewline(self): \"\"\" Test that last <br> in tree has a",
"= 'foo.html' self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f',",
"Test that an extension can exclude parent tags. \"\"\" test",
"True } } self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs']",
"These tests should only be a concern when using cElementTree",
"= markdown.util.etree.test_comment else: self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test",
"'c', 40) slc = r[1:] self.assertEqual(len(slc), 2) self.assertIsInstance(slc, markdown.util.Registry) self.assertEqual(list(slc),",
"'mi') mi.text = 'x' mn = markdown.util.etree.SubElement(msup, 'mn') mn.text =",
"False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True) self.assertEqual(self.state.isstate('a_state'), False) self.assertEqual(self.state.isstate('missing'),",
"\"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config) self.assertRaises(yaml.YAMLError, parse_options, ['-c', self.tempfile])",
"markdown.serializers.to_html_string(new), '<div><p>*some* <span>*more* <span>*text* <span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>' )",
"r.register(Item('b'), 'b', 30) self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c']",
"'w') as fp: fp.write(config) def testExtensionConfigOption(self): config = { 'markdown.extensions.wikilinks':",
"testNoisyOption(self): options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level, DEBUG) def testInputFileOption(self): options,",
"el, m.start(0), m.end(0) class AncestorExtension(markdown.Extension): def __init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\"",
"'<p hidden>foo <&escaped></p>' '<hr>' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' )",
"testSerializers(unittest.TestCase): \"\"\" Test the html and xhtml serializers. \"\"\" def",
"only whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self): \"\"\" Test",
"__init__(self, *args, **kwargs): \"\"\"Initialize.\"\"\" self.config = {} def extendMarkdown(self, md):",
"================================ Tests of the various APIs with the python markdown",
"def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing",
"is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15)",
"'' def tearDown(self): if os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options, logging_level",
"and a <a href=\"http://test.com\">+link+</a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) def test_ancestors_tail(self): \"\"\"",
"State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state,",
"parsing of Command Line Interface Options. \"\"\" def setUp(self): self.default_options",
"with a class instance. \"\"\" from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()])",
"testInputFileOption(self): options, logging_level = parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options)",
"as errors warnings.simplefilter('error') def tearDown(self): # Reset warning behavior back",
"self.assertEqual(r['a'], 'a') self.assertEqual(r['b'], 'b') with self.assertRaises(KeyError): r['c'] def testRegistrySetItem(self): r",
"= BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO() def tearDown(self): sys.stdin, sys.stdout",
"always be triggered. warnings.simplefilter(\"always\") # Trigger a warning. version =",
"\"\"\" Helper to create temp config files. \"\"\" if not",
"Tests ================================ Tests of the various APIs with the python",
"\"\"\" Test QName that is already partially escaped. \"\"\" qname",
"= markdown.util.AtomicString('some *text*') new = self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>'",
"self.assertEqual(self.stash.rawHtmlBlocks, ['foo']) def testStoreMore(self): \"\"\" Test HtmlStash.store with additional blocks.",
"Test that a simple AtomicString is not parsed. \"\"\" tree",
"self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r = markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a'))",
"script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\" self.assertEqual( markdown.serializers.to_html_string(el), '<div",
"append. \"\"\" def testBlockAppend(self): \"\"\" Test that appended escapes are",
"Extension loading with Name (`path.to.module`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes']) def testDotNotationExtensionWithClass(self): \"\"\"",
") class testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree Comments work. These",
"self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self):",
"TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of Command Line Interface Options. \"\"\"",
"'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r =",
"deprecated __del__ is removed. with warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'),",
"class TestCliOptionParsing(unittest.TestCase): \"\"\" Test parsing of Command Line Interface Options.",
"self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general deprecations.\"\"\" def test_version_deprecation(self): \"\"\"Test",
"= markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail,",
"string config = yaml.dump(config) fd, self.tempfile = tempfile.mkstemp('.yml') with os.fdopen(fd,",
"3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistrySlice(self): r",
"self.assertEqual(options, self.default_options) def testInputAndOutputFileOptions(self): options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt'])",
"tag case. \"\"\" el = markdown.util.etree.Element('MixedCase') el.text = 'not valid",
"def testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b',",
"__setitem__ is removed. # with self.assertRaises(TypeError): # r['a'] = 'a'",
"r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r[0], 'b') self.assertEqual(r[1], 'a')",
"= markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*')",
"Test BlockParser.parseChunk. \"\"\" root = markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root,",
"self.assertRaises(TypeError, markdown.Markdown, extensions=[object]) def testDotNotationExtensionWithBadClass(self): \"\"\" Test Extension loading with",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(r['a'],",
"serialization of QName with no tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML')",
"testMultipleExtensionOptions(self): options, logging_level = parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ])",
"isinstance(config, markdown.util.string_type): # convert to string config = yaml.dump(config) fd,",
"def testReset(self): \"\"\" Test State.reset(). \"\"\" self.state.set('a_state') self.state.reset() self.assertEqual(self.state, [])",
"warnings.simplefilter(\"always\") # Trigger a warning. version_info = markdown.version_info # Verify",
"self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20)",
"class. \"\"\" def setUp(self): \"\"\" Create instance of Markdown. \"\"\"",
"deregister non-existant item with strict=True r.deregister('e') self.assertEqual(list(r), ['a']) def testRegistryContains(self):",
"markdown.serializers.to_xhtml_string(el), '<div xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\" Test QName that",
"config): \"\"\" Helper to create temp config files. \"\"\" if",
"Test that AtomicStrings are honored (not parsed). \"\"\" def setUp(self):",
"'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testXhtml(self): \"\"\"\" Test",
"processor registry. \"\"\" def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"with warnings.catch_warnings(record=True) as w: # Cause all warnings to always",
"== 3 if not PY3: def bytes(string, encoding): return string.encode(encoding)",
"options, logging_level = parse_options([ '-x', 'markdown.extensions.footnotes', '-x', 'markdown.extensions.smarty' ]) self.default_options['extensions']",
") def testNestedAtomicString(self): \"\"\" Test that a nested AtomicString is",
"as w: warnings.simplefilter(\"always\") r = markdown.util.Registry() # Add first item",
"<span>*more* <span>*text* <span>*here*</span> ' '*to*</span> *test*</span> *with*</p></div>' ) class TestConfigParsing(unittest.TestCase):",
"QName that is already partially escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">',",
"tempfile.mkstemp(suffix='.txt') with os.fdopen(infd, 'w') as fp: fp.write(src) outfd, outfile =",
"character append. \"\"\" def testAppend(self): \"\"\" Test that appended escapes",
"Tail Tests \"\"\" def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) def testBrTailNoNewline(self):",
"span2.tail = markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString(' *with*') new =",
"(the original version) License: BSD (see LICENSE.md for details). Python-Markdown",
"lines = ['#foo', '', 'bar', '', ' baz'] tree =",
"def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self): self.assertParses(True,",
"if not PY3: def bytes(string, encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase):",
"['a']) def testRegistryContains(self): r = markdown.util.Registry() item = Item('a') r.register(item,",
"setUp(self): \"\"\" Create instance of Markdown. \"\"\" self.md = markdown.Markdown()",
"\"\"\" Test that AtomicStrings are honored (not parsed). \"\"\" def",
"Add first item r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c']) # Added",
"\"\"\" from markdown.extensions.footnotes import FootnoteExtension markdown.Markdown(extensions=[FootnoteExtension()]) def testEntryPointExtension(self): \"\"\" Test",
"other): return self.data == other class RegistryTests(unittest.TestCase): \"\"\" Test the",
"with self.assertRaises(TypeError): # del r['a'] # TODO: remove this when",
"first item r.add('c', Item('c'), '_begin') self.assertEqual(list(r), ['c']) # Added to",
"= markdown.util.etree.Element('div') qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML', 'math') math = markdown.util.etree.SubElement(div, qname)",
"serializers. \"\"\" def testHtml(self): \"\"\" Test HTML serialization. \"\"\" el",
"\"\"\" Test that an ElementTree Comment is recognized as BlockLevel.",
"\"\"\" def setUp(self): \"\"\" Create instance of Markdown. \"\"\" self.md",
"['a', 'a1', 'b', 'b1', 'c', 'd']) # Add to end",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b1'), 'b', 10) self.assertEqual(list(r),",
"class TestConfigParsing(unittest.TestCase): def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def",
"self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self): \"\"\" Test simple input. \"\"\"",
"def testSimpleInput(self): \"\"\" Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def",
"*with*</p></div>' ) class TestConfigParsing(unittest.TestCase): def assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False),",
"'p') p.text = 'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element",
"self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that version info is deprecated.\"\"\"",
"r[3] def testRegistryGetItemByItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"'), '') def testSimpleInput(self): \"\"\" Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'),",
"lib. \"\"\" from __future__ import unicode_literals import unittest import sys",
"def testBadOutputFormat(self): \"\"\" Test failure on bad output_format. \"\"\" self.assertRaises(KeyError,",
"RegistryTests(unittest.TestCase): \"\"\" Test the processor registry. \"\"\" def testCreateRegistry(self): r",
"parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input'] = 'foo.txt' self.assertEqual(options,",
"the current instance. \"\"\" md = markdown.Markdown() md.block_level_elements.append('test') self.assertEqual('test' in",
"extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree Comments work.",
"self.test_comment = markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test that an ElementTree",
"markdown.util.Registry() with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'),",
"self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd', 'e']) with self.assertRaises(ValueError):",
"sys.stdout = BytesIO() def tearDown(self): sys.stdin, sys.stdout = self.saved def",
"\"\"\" Some +test+ and a [+link+](http://test.com) \"\"\" result = \"\"\"<p>Some",
"things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test",
"coding: utf-8 -*- \"\"\" Python Markdown A Python implementation of",
"markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2, 'span') span3.text = markdown.util.AtomicString('*here*') span3.tail",
"class for BlockParser. \"\"\" def setUp(self): self.state = markdown.blockparser.State() def",
"\"\"\" Element Tail Tests \"\"\" def setUp(self): self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())",
"} } self.create_config_file(config) options, logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] =",
"self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self): \"\"\"Tests the",
"self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w)) def testRegistrySlice(self):",
"\"\"\" self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self): \"\"\" Test simple input.",
"preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue, 'novalue') class TestCliOptionParsing(unittest.TestCase):",
"def testSetSate(self): \"\"\" Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2')",
"Create instance of BlockParser. \"\"\" self.parser = markdown.Markdown().parser def testParseChunk(self):",
"testExtensionConfigOptionAsJSON(self): config = { 'markdown.extensions.wikilinks': { 'base_url': 'http://example.com/', 'end_url': '.html',",
"self.assertEqual(self.state, ['state1']) class TestHtmlStash(unittest.TestCase): \"\"\" Test Markdown's HtmlStash. \"\"\" def",
"= \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test), result) class TestGeneralDeprecations(unittest.TestCase): \"\"\"Test general",
"deprecated.\"\"\" with warnings.catch_warnings(record=True) as w: # Cause all warnings to",
"testSetSate(self): \"\"\" Test State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state,",
"some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self):",
"output_format='xhtml'), '<p>foo<br />\\nbar</p>' ) def testHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='html'),",
"markdown.util.etree.Element(\"div\") text = 'foo' self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" )",
"class RegistryTests(unittest.TestCase): \"\"\" Test the processor registry. \"\"\" def testCreateRegistry(self):",
"= 'not valid ' em = markdown.util.etree.SubElement(el, 'EMPHASIS') em.text =",
"markdown.util.etree.SubElement(el, 'EMPHASIS') em.text = 'html' markdown.util.etree.SubElement(el, 'HR') self.assertEqual( markdown.serializers.to_xhtml_string(el), '<MixedCase>not",
"testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree Comments work. These tests should",
"class testSerializers(unittest.TestCase): \"\"\" Test the html and xhtml serializers. \"\"\"",
"CRITICAL import yaml import tempfile from io import BytesIO from",
"QName attribute. \"\"\" div = markdown.util.etree.Element('div') div.set(markdown.util.etree.QName('foo'), markdown.util.etree.QName('bar')) self.assertEqual( markdown.serializers.to_xhtml_string(div),",
"'a', 20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) slc =",
"Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in",
"\"\"\" Test QName escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el",
"entry point. \"\"\" markdown.Markdown(extensions=['footnotes']) def testDotNotationExtension(self): \"\"\" Test Extension loading",
"output_format='fake' ), '<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo \\nbar', output_format='xhtml'),",
"'Some Title', 'anchorlink': True, 'permalink': True } } self.create_config_file(config) options,",
"os.path.isfile(self.tempfile): os.remove(self.tempfile) def testNoOptions(self): options, logging_level = parse_options([]) self.assertEqual(options, self.default_options)",
"testIsSorted(self): r = markdown.util.Registry() self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20) list(r)",
"r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b', 'a']) def testRegistryGetItemByIndex(self): r =",
"nested AtomicString is not parsed. \"\"\" tree = markdown.util.etree.Element('div') p",
"2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] ) def testReset(self): \"\"\" Test",
"<br> in tree has a new line tail \"\"\" root",
"True) r._is_sorted = False r.get_index_for_name('a') self.assertIs(r._is_sorted, True) r._is_sorted = False",
"AtomicStrings are honored (not parsed). \"\"\" def setUp(self): md =",
"as fp: output = fp.read() self.assertEqual(output, '<p>foo</p>') def testFileObjects(self): infile",
"'d']) # Add to end r.add('e', Item('e'), '_end') self.assertEqual(list(r), ['a',",
"outfd, outfile = tempfile.mkstemp(suffix='.html') return infile, outfile, outfd def testFileNames(self):",
"testLoadExtensionFailure(self): \"\"\" Test failure of an extension to load. \"\"\"",
"BytesIO() markdown.markdownFromFile(input=infile, output=outfile) outfile.seek(0) self.assertEqual(outfile.read().decode('utf-8'), '<p>foo</p>') def testStdinStdout(self): markdown.markdownFromFile() sys.stdout.seek(0)",
"def testNonExtension(self): \"\"\" Test loading a non Extension object as",
"# Cause all warnings to always be triggered. warnings.simplefilter(\"always\") #",
"'baz', extensions=[self.buildExtension()], output_format='fake' ), '<p>foo</p>' ) def testXHTMLOutput(self): self.assertEqual( markdown.markdown('foo",
"can exclude parent tags. \"\"\" test = \"\"\" Some +test+",
"whitespace. \"\"\" self.assertEqual(self.md.convert(' '), '') def testSimpleInput(self): \"\"\" Test simple",
"and xhtml serializers. \"\"\" def testHtml(self): \"\"\" Test HTML serialization.",
"third party extensions which may. Therefore, these tests are included",
"'2' ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div),",
"'<p>foo<br>\\nbar</p>' ) class testAtomicString(unittest.TestCase): \"\"\" Test that AtomicStrings are honored",
"__future__ import unicode_literals import unittest import sys import os import",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) with self.assertRaises(TypeError): del r[0]",
"# Trigger a warning. version_info = markdown.version_info # Verify some",
"State.set(). \"\"\" self.state.set('a_state') self.assertEqual(self.state, ['a_state']) self.state.set('state2') self.assertEqual(self.state, ['a_state', 'state2']) def",
"['a', 'a1', 'b', 'b1', 'c']) # Add after last item",
"self.assertEqual(list(r), ['a', 'c']) del r['a'] self.assertEqual(list(r), ['c']) with self.assertRaises(TypeError): del",
"# Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__)",
"20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3) r.deregister('b')",
"self.assertEqual(list(r), []) # Check the warnings self.assertEqual(len(w), 3) self.assertTrue(all(issubclass(x.category, DeprecationWarning)",
"del r['c'] self.assertEqual(list(r), []) # Check the warnings self.assertEqual(len(w), 3)",
"self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version, markdown.__version__) def test_version_info_deprecation(self): \"\"\"Test that",
"qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div",
"= parse_options(['foo.txt']) self.default_options['input'] = 'foo.txt' self.assertEqual(options, self.default_options) def testOutputFileOption(self): options,",
"r.add('b', Item('b'), '_begin') self.assertEqual(list(r), ['b', 'c']) # Add before first",
"def test_deprecation_wrapper_dir(self): \"\"\"Tests the `__dir__` attribute of the class as",
"'<!--foo-->\\n' ) class testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests \"\"\" def",
"True, 'permalink': True } } self.create_config_file(config) options, logging_level = parse_options(['-c',",
"testBlankState(self): \"\"\" Test State when empty. \"\"\" self.assertEqual(self.state, []) def",
"list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b', 21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted,",
"be raised as errors warnings.simplefilter('error') def tearDown(self): # Reset warning",
"repr(r) self.assertIs(r._is_sorted, True) def testDeregister(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"False self.assertEqual(options, self.default_options) def testExtensionOption(self): options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes'])",
"self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r), 1) # deregister non-existant item",
"markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 30) self.assertEqual(list(r), ['b', 'a'])",
"logging_level = parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def",
"should only be a concern when using cElementTree with third",
"= markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x' mn = markdown.util.etree.SubElement(msup, 'mn')",
"of ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">') self.assertIs(pi.tag, ProcessingInstruction) self.assertEqual(",
"the html and xhtml serializers. \"\"\" def testHtml(self): \"\"\" Test",
"'a', 20) with self.assertRaises(TypeError): del r[0] # TODO: restore this",
"w)) def testRegistryDelItem(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) with",
"'foo<&\">') p = markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>' p.set('hidden', 'hidden')",
"'foo <&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element = markdown.util.etree.SubElement(el, None)",
"Markdown A Python implementation of <NAME>'s Markdown. Documentation: https://python-markdown.github.io/ GitHub:",
"DEBUG, WARNING, CRITICAL import yaml import tempfile from io import",
"logging import DEBUG, WARNING, CRITICAL import yaml import tempfile from",
"warnings.simplefilter('error') def tearDown(self): # Reset warning behavior back to default",
"Options. \"\"\" def setUp(self): self.default_options = { 'input': None, 'output':",
"testSimpleInput(self): \"\"\" Test simple input. \"\"\" self.assertEqual(self.md.convert('foo'), '<p>foo</p>') def testInstanceExtension(self):",
"\"\"\" def testHtml(self): \"\"\" Test HTML serialization. \"\"\" el =",
"markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\" Test that an ElementTree",
"self.assertParses('none', False) def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self):",
"= 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>' '<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>'",
"self.assertEqual(r.get_index_for_name('a'), 1) self.assertEqual(r.get_index_for_name('b'), 0) with self.assertRaises(ValueError): r.get_index_for_name('c') def testRegisterDupplicate(self): r",
"def bytes(string, encoding): return string.encode(encoding) class TestMarkdownBasics(unittest.TestCase): \"\"\" Tests basics",
"1) # deregister non-existant item with strict=False r.deregister('d', strict=False) self.assertEqual(len(r),",
"20) r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) slc = r[1:]",
"sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout = BytesIO() def",
"function. \"\"\" self.assertRaises(AttributeError, markdown.Markdown, extensions=['markdown.util']) def testNonExtension(self): \"\"\" Test loading",
"parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options, logging_level = parse_options(['--noisy']) self.assertEqual(logging_level,",
"self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False) self.assertEqual(len(r), 1) #",
"-*- coding: utf-8 -*- \"\"\" Python Markdown A Python implementation",
"'c', 10) del r['b'] self.assertEqual(list(r), ['a', 'c']) del r['a'] self.assertEqual(list(r),",
"falure on non-unicode source text. \"\"\" if not PY3: source",
"tests are included to ensure such support is maintained. \"\"\"",
"self.state.set('a_state') self.state.reset() self.assertEqual(self.state, []) self.state.set('state1') self.state.set('state2') self.state.reset() self.assertEqual(self.state, ['state1']) class",
"assertParses(self, value, result): self.assertIs(markdown.util.parseBoolValue(value, False), result) def testBooleansParsing(self): self.assertParses(True, True)",
"w)) def testRegistrySlice(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'),",
"markdown.version # Verify some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version,",
"= 'a' # TODO: remove this when deprecated __setitem__ is",
"'c', 20.5) self.assertEqual(len(r), 3) self.assertEqual(list(r), ['b', 'c', 'a']) def testIsSorted(self):",
"\"\"\" Test serialization of QName with no tag. \"\"\" qname",
"md.block_level_elements.append('test') self.assertEqual('test' in md.block_level_elements, True) md2 = markdown.Markdown() self.assertEqual('test' not",
"'b', 30) r.register(Item('c'), 'c', 40) slc = r[1:] self.assertEqual(len(slc), 2)",
"markdown.Markdown, extensions=[markdown.extensions.Extension()] ) class testETreeComments(unittest.TestCase): \"\"\" Test that ElementTree Comments",
"tail. \"\"\" test = \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a",
"with no tag. \"\"\" qname = markdown.util.etree.QName('http://www.w3.org/1998/Math/MathML') el = markdown.util.etree.Element(qname)",
"Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by <NAME> (http://www.dwerg.net/).",
"\"\"\" Test Extension loading with an entry point. \"\"\" markdown.Markdown(extensions=['footnotes'])",
"testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests \"\"\" def setUp(self): self.pretty =",
"self.assertEqual(br.tail, None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test the",
"\"\"\" Test serialization of ProcessignInstruction. \"\"\" pi = ProcessingInstruction('foo', text='<&\"test\\nescaping\">')",
"# Trigger a warning. version = markdown.version # Verify some",
"item object for testing. \"\"\" def __init__(self, data): self.data =",
"# Set warnings to be raised as errors warnings.simplefilter('error') def",
"= markdown.util.etree.SubElement(tree, 'p') p.text = 'some *text*' new = self.inlineprocessor.run(tree)",
"'encoding': None, 'output_format': 'xhtml', 'lazy_ol': True, 'extensions': [], 'extension_configs': {},",
"loading with non-existant class name (`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown,",
"\"\"\" def setUp(self): self.default_options = { 'input': None, 'output': None,",
"temp config files. \"\"\" if not isinstance(config, markdown.util.string_type): # convert",
"def test_version_deprecation(self): \"\"\"Test that version is deprecated.\"\"\" with warnings.catch_warnings(record=True) as",
"self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): r = markdown.util.Registry() with",
"= parse_options(['-v']) self.assertEqual(logging_level, WARNING) def testNoisyOption(self): options, logging_level = parse_options(['--noisy'])",
"r.register(Item('c'), 'c', 40) self.assertEqual(len(r), 3) r.deregister('b') self.assertEqual(len(r), 2) r.deregister('c', strict=False)",
"= [ 'markdown.extensions.footnotes', 'markdown.extensions.smarty' ] self.assertEqual(options, self.default_options) def create_config_file(self, config):",
"r.register(Item('b'), 'b', 30) r.register(Item('c'), 'c', 40) slc = r[1:] self.assertEqual(len(slc),",
"self.data = data def __repr__(self): return repr(self.data) def __eq__(self, other):",
"self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd']) # Add to",
"md2.ESCAPED_CHARS, True) class TestBlockAppend(unittest.TestCase): \"\"\" Tests block kHTML append. \"\"\"",
"markdown.util.AtomicString(' *test*') span1.tail = markdown.util.AtomicString(' *with*') new = self.inlineprocessor.run(tree) self.assertEqual(",
"self.saved = sys.stdin, sys.stdout sys.stdin = BytesIO(bytes('foo', encoding='utf-8')) sys.stdout =",
"testQNamePreEscaping(self): \"\"\" Test QName that is already partially escaped. \"\"\"",
"= self.getTempFiles('foo') markdown.markdownFromFile(input=infile, output=outfile) with os.fdopen(outfd, 'r') as fp: output",
"with self.assertRaises(TypeError): r.register(Item('a')) def testSortRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a',",
"self.parser.parseChunk(root, text) self.assertEqual( markdown.serializers.to_xhtml_string(root), \"<div><p>foo</p></div>\" ) def testParseDocument(self): \"\"\" Test",
"\"\"\" Test Extension loading with class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension'])",
"class testElementTailTests(unittest.TestCase): \"\"\" Element Tail Tests \"\"\" def setUp(self): self.pretty",
"self.assertEqual(options, self.default_options) def testExtensionOption(self): options, logging_level = parse_options(['-x', 'markdown.extensions.footnotes']) self.default_options['extensions']",
"from logging import DEBUG, WARNING, CRITICAL import yaml import tempfile",
"= Item('a') r.register(item, 'a', 20) self.assertIs('a' in r, True) self.assertIn(item,",
"ElementTree Comment is prettified properly. \"\"\" pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown()) pretty.run(self.comment)",
"name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase): \"\"\" Tests of ConvertFile.",
"'x' mn = markdown.util.etree.SubElement(msup, 'mn') mn.text = '2' ann =",
"None) self.pretty.run(root) self.assertEqual(br.tail, \"\\n\") class testSerializers(unittest.TestCase): \"\"\" Test the html",
"the State class for BlockParser. \"\"\" def setUp(self): self.state =",
"Test. \"\"\" ANCESTOR_EXCLUDES = ('a',) def handleMatch(self, m, data): \"\"\"",
"markdown.util.etree.SubElement(msup, 'mn') mn.text = '2' ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text",
"self.assertEqual(options, self.default_options) self.assertEqual(logging_level, CRITICAL) def testQuietOption(self): options, logging_level = parse_options(['-q'])",
"qname = markdown.util.etree.QName('<&\"test\\nescaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual( markdown.serializers.to_xhtml_string(el), '<div",
"self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\" Test that",
"\"\"\" root = markdown.util.etree.Element('root') br = markdown.util.etree.SubElement(root, 'br') self.assertEqual(br.tail, None)",
"Test State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'),",
"testSimpleStore(self): \"\"\" Test HtmlStash.store. \"\"\" self.assertEqual(self.placeholder, self.stash.get_placeholder(0)) self.assertEqual(self.stash.html_counter, 1) self.assertEqual(self.stash.rawHtmlBlocks,",
"r, True) self.assertIn(item, r) self.assertNotIn('b', r) def testRegistryIter(self): r =",
"warnings.catch_warnings(record=True) as w: warnings.simplefilter(\"always\") r.register(Item('b'), 'b', 15) r.register(Item('c'), 'c', 10)",
"markdown.util.etree.Comment def testCommentIsComment(self): \"\"\" Test that an ElementTree Comment passes",
") def testMixedCaseTags(self): \"\"\"\" Test preservation of tag case. \"\"\"",
"parse_options(['-c', self.tempfile]) self.default_options['extension_configs'] = config self.assertEqual(options, self.default_options) def testExtensionConfigOptionMissingFile(self): self.assertRaises(IOError,",
"= parse_options(['-o', 'html']) self.default_options['output_format'] = 'html' self.assertEqual(options, self.default_options) def testNoLazyOlOption(self):",
"def testQNameEscaping(self): \"\"\" Test QName escaping. \"\"\" qname = markdown.util.etree.QName('<&\"test\\nescaping\">',",
"options, logging_level = parse_options(['-f', 'foo.html', 'foo.txt']) self.default_options['output'] = 'foo.html' self.default_options['input']",
"some things self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertEqual(version_info, markdown.__version_info__) def test_deprecation_wrapper_dir(self):",
"# r['a'] = 'a' # TODO: remove this when deprecated",
"warning. version = markdown.version # Verify some things self.assertEqual(len(w), 1)",
"= markdown.util.etree.SubElement(math, 'semantics') msup = markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup,",
"r = markdown.util.Registry() r.register(Item('a'), 'a', 20) r.register(Item('b'), 'b', 21) r.register(Item('c'),",
"def testExtensionConfigOptionBadFormat(self): config = \"\"\" [footnotes] PLACE_MARKER= ~~~footnotes~~~ \"\"\" self.create_config_file(config)",
"file names for two temp files. \"\"\" infd, infile =",
"(`path.to.module:Class`). \"\"\" self.assertRaises( AttributeError, markdown.Markdown, extensions=['markdown.extensions.footnotes:MissingExtension'] ) def testBaseExtention(self): \"\"\"",
"State.isstate(). \"\"\" self.assertEqual(self.state.isstate('anything'), False) self.state.set('a_state') self.assertEqual(self.state.isstate('a_state'), True) self.state.set('state2') self.assertEqual(self.state.isstate('state2'), True)",
"in tree has a new line tail \"\"\" root =",
") class TestBlockParserState(unittest.TestCase): \"\"\" Tests of the State class for",
"'<math display=\"block\" xmlns=\"http://www.w3.org/1998/Math/MathML\">' '<semantics>' '<msup>' '<mi>x</mi>' '<mn>2</mn>' '</msup>' '<annotations>x^2</annotations>' '</semantics>'",
"extension can exclude parent tags. \"\"\" test = \"\"\" Some",
"= \"\"\" [***+em+*+strong+**](http://test.com) \"\"\" result = \"\"\"<p><a href=\"http://test.com\"><strong><em>+em+</em>+strong+</strong></a></p>\"\"\" self.md.reset() self.assertEqual(self.md.convert(test),",
"'<script><&\"test\\nescaping\"></script>' '</div>tail text' ) def testMixedCaseTags(self): \"\"\"\" Test preservation of",
"setUp(self): \"\"\" Create instance of BlockParser. \"\"\" self.parser = markdown.Markdown().parser",
"instance. \"\"\" md = markdown.Markdown() md.ESCAPED_CHARS.append('|') self.assertEqual('|' in md.ESCAPED_CHARS, True)",
"def testPreserveNone(self): self.assertIsNone(markdown.util.parseBoolValue('None', preserve_none=True)) self.assertIsNone(markdown.util.parseBoolValue(None, preserve_none=True)) def testInvalidBooleansParsing(self): self.assertRaises(ValueError, markdown.util.parseBoolValue,",
"self.stash.store('bar') self.assertEqual(placeholder, self.stash.get_placeholder(1)) self.assertEqual(self.stash.html_counter, 2) self.assertEqual( self.stash.rawHtmlBlocks, ['foo', 'bar'] )",
"BlockLevel. \"\"\" md = markdown.Markdown() self.assertIs(md.is_block_level(self.comment.tag), False) def testCommentSerialization(self): \"\"\"",
"markdown.serializers.to_html_string(new), '<div><p>some *text*</p></div>' ) def testNestedAtomicString(self): \"\"\" Test that a",
"markdown.util.etree.SubElement(span1, 'span') span2.text = markdown.util.AtomicString('*text* ') span3 = markdown.util.etree.SubElement(span2, 'span')",
"xmlns=\"<&"test escaping">\"></div>' ) def testQNamePreEscaping(self): \"\"\" Test QName that is already",
"self.assertEqual( markdown.serializers.to_html_string(self.comment), '<!--foo-->' ) def testCommentPrettify(self): \"\"\" Test that an",
"warnings.simplefilter(\"always\") # Trigger a warning. version = markdown.version # Verify",
"ann = markdown.util.etree.SubElement(sem, 'annotations') ann.text = 'x^2' self.assertEqual( markdown.serializers.to_xhtml_string(div), '<div>'",
"self.assertIs(r._is_sorted, False) r.register(Item('a'), 'a', 20) list(r) self.assertIs(r._is_sorted, True) r.register(Item('b'), 'b',",
"'b', 21) self.assertIs(r._is_sorted, False) r['a'] self.assertIs(r._is_sorted, True) r._is_sorted = False",
"markdown.util.etree.Element('div') p = markdown.util.etree.SubElement(tree, 'p') p.text = 'some *text*' new",
"\"\"\" Test that a simple AtomicString is not parsed. \"\"\"",
"self.inlineprocessor.run(tree) self.assertEqual( markdown.serializers.to_html_string(new), '<div><p>some <em>text</em></p></div>' ) def testSimpleAtomicString(self): \"\"\" Test",
"with the python markdown lib. \"\"\" from __future__ import unicode_literals",
"= markdown.util.etree.SubElement(sem, 'msup') mi = markdown.util.etree.SubElement(msup, 'mi') mi.text = 'x'",
"escaped. \"\"\" qname = markdown.util.etree.QName('<&\"test escaping\">', 'div') el = markdown.util.etree.Element(qname) self.assertEqual(",
"Test Extension loading with class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class",
"Extension loading with class name (`path.to.module:Class`). \"\"\" markdown.Markdown(extensions=['markdown.extensions.footnotes:FootnoteExtension']) class TestConvertFile(unittest.TestCase):",
"sys import os import markdown import warnings from markdown.__main__ import",
"import ProcessingInstruction PY3 = sys.version_info[0] == 3 if not PY3:",
"id=\"foo<&">\">' '<p hidden=\"hidden\">foo<&escaped></p>' '<hr />' 'non-element text' '<script><&\"test\\nescaping\"></script>' '</div>tail text'",
"\"\"\" el = markdown.util.etree.Element('div') el.set('id', 'foo<&\">') p = markdown.util.etree.SubElement(el, 'p')",
"\"\"\" self.assertIs(self.comment.tag, markdown.util.etree.test_comment) def testCommentIsBlockLevel(self): \"\"\" Test that an ElementTree",
"= ['#foo', '', 'bar', '', ' baz'] tree = self.parser.parseDocument(lines)",
"\"\"\"\" Test preservation of tag case. \"\"\" el = markdown.util.etree.Element('MixedCase')",
"\"\"\" Test the processor registry. \"\"\" def testCreateRegistry(self): r =",
"markdown.util.etree.SubElement(el, 'p') p.text = 'foo<&escaped>' p.set('hidden', 'hidden') markdown.util.etree.SubElement(el, 'hr') non_element",
"= markdown.util.etree.SubElement(non_element, 'script') script.text = '<&\"test\\nescaping\">' el.tail = \"tail text\""
] |
[
"value self._sanitize() @property def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self,",
"self._sanitize() def _sanitize(self): if 1. < self._group_environmental_constraint <= 0.: raise",
"1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint",
"constraint has to be in the range [0. - 1.)\")",
"return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value self._sanitize()",
"synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value self._sanitize() @property def group_environmental_constraint(self): return",
"- 1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return",
"os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value):",
"def save_folder(self, value): self._save_folder = value self._sanitize() def __getitem__(self, item):",
"def __getitem__(self, item): if item == \"self\": raise ValueError(\"Hahaha\") return",
"self._group_environmental_constraint = group_environmental_constraint self._stress_factor = stress_factor self._save_folder = save_folder self._sanitize()",
"raise ValueError(\"Stress factor has to be in the range [0.",
"self._stress_factor = value self._sanitize() @property def save_folder(self): return self._save_folder @save_folder.setter",
"raise ValueError(\"Group environmental constraint has to be in the range",
"to be in the range [0. - 1.)\") if not",
"self._synaptic_environmental_constraint = value self._sanitize() @property def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter",
"< self._group_environmental_constraint <= 0.: raise ValueError(\"Group environmental constraint has to",
"the range [0. - 1.)\") if 1. < self._synaptic_environmental_constraint <=",
"value): self._stress_factor = value self._sanitize() @property def save_folder(self): return self._save_folder",
"synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor = stress_factor self._save_folder = save_folder",
"@property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint",
"group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor",
"os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self,",
"the range [0. - 1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property",
"group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint = value",
"self._sanitize() @property def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value):",
"group_environmental_constraint(self, value): self._group_environmental_constraint = value self._sanitize() @property def stress_factor(self): return",
"= value self._sanitize() @property def stress_factor(self): return self._stress_factor @stress_factor.setter def",
"= stress_factor self._save_folder = save_folder self._sanitize() def _sanitize(self): if 1.",
"1.)\") if 1. < self._stress_factor <= 0.: raise ValueError(\"Stress factor",
"self._sanitize() @property def stress_factor(self): return self._stress_factor @stress_factor.setter def stress_factor(self, value):",
"not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def",
"factor has to be in the range [0. - 1.)\")",
"def group_environmental_constraint(self, value): self._group_environmental_constraint = value self._sanitize() @property def stress_factor(self):",
"in the range [0. - 1.)\") if 1. < self._synaptic_environmental_constraint",
"= value self._sanitize() @property def save_folder(self): return self._save_folder @save_folder.setter def",
"in the range [0. - 1.)\") if 1. < self._stress_factor",
"value): self._save_folder = value self._sanitize() def __getitem__(self, item): if item",
"to be in the range [0. - 1.)\") if 1.",
"be in the range [0. - 1.)\") if not os.path.exists(self._save_folder):",
"return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint = value self._sanitize()",
"def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint",
"self._group_environmental_constraint <= 0.: raise ValueError(\"Group environmental constraint has to be",
"self._stress_factor <= 0.: raise ValueError(\"Stress factor has to be in",
"[0. - 1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self):",
"self._sanitize() def __getitem__(self, item): if item == \"self\": raise ValueError(\"Hahaha\")",
"in the range [0. - 1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder)",
"return self._stress_factor @stress_factor.setter def stress_factor(self, value): self._stress_factor = value self._sanitize()",
"__getitem__(self, item): if item == \"self\": raise ValueError(\"Hahaha\") return self.__dict__[item]",
"def _sanitize(self): if 1. < self._group_environmental_constraint <= 0.: raise ValueError(\"Group",
"if 1. < self._stress_factor <= 0.: raise ValueError(\"Stress factor has",
"def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint =",
"value): self._group_environmental_constraint = value self._sanitize() @property def stress_factor(self): return self._stress_factor",
"@stress_factor.setter def stress_factor(self, value): self._stress_factor = value self._sanitize() @property def",
"self._save_folder = value self._sanitize() def __getitem__(self, item): if item ==",
"ValueError(\"Group environmental constraint has to be in the range [0.",
"synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint",
"< self._stress_factor <= 0.: raise ValueError(\"Stress factor has to be",
"self._save_folder @save_folder.setter def save_folder(self, value): self._save_folder = value self._sanitize() def",
"[0. - 1.)\") if 1. < self._synaptic_environmental_constraint <= 0.: raise",
"range [0. - 1.)\") if 1. < self._synaptic_environmental_constraint <= 0.:",
"range [0. - 1.)\") if 1. < self._stress_factor <= 0.:",
"= group_environmental_constraint self._stress_factor = stress_factor self._save_folder = save_folder self._sanitize() def",
"if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter",
"self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint = value self._sanitize() @property",
"def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value self._sanitize() @property def group_environmental_constraint(self):",
"be in the range [0. - 1.)\") if 1. <",
"@synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value self._sanitize() @property def",
"self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor = stress_factor self._save_folder",
"value self._sanitize() def __getitem__(self, item): if item == \"self\": raise",
"synaptic_environmental_constraint(self): return self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value",
"0.: raise ValueError(\"Stress factor has to be in the range",
"= save_folder self._sanitize() def _sanitize(self): if 1. < self._group_environmental_constraint <=",
"self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic environmental constraint has to be",
"< self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic environmental constraint has to",
"StressedNetConfig: def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint",
"@save_folder.setter def save_folder(self, value): self._save_folder = value self._sanitize() def __getitem__(self,",
"value self._sanitize() @property def save_folder(self): return self._save_folder @save_folder.setter def save_folder(self,",
"value): self._synaptic_environmental_constraint = value self._sanitize() @property def group_environmental_constraint(self): return self._group_environmental_constraint",
"save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor = stress_factor",
"the range [0. - 1.)\") if 1. < self._stress_factor <=",
"@group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint = value self._sanitize() @property def",
"if 1. < self._group_environmental_constraint <= 0.: raise ValueError(\"Group environmental constraint",
"self._synaptic_environmental_constraint @synaptic_environmental_constraint.setter def synaptic_environmental_constraint(self, value): self._synaptic_environmental_constraint = value self._sanitize() @property",
"0.: raise ValueError(\"Group environmental constraint has to be in the",
"1. < self._stress_factor <= 0.: raise ValueError(\"Stress factor has to",
"self._save_folder = save_folder self._sanitize() def _sanitize(self): if 1. < self._group_environmental_constraint",
"= value self._sanitize() @property def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def",
"class StressedNetConfig: def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint =",
"def stress_factor(self): return self._stress_factor @stress_factor.setter def stress_factor(self, value): self._stress_factor =",
"def stress_factor(self, value): self._stress_factor = value self._sanitize() @property def save_folder(self):",
"raise ValueError(\"Synaptic environmental constraint has to be in the range",
"os class StressedNetConfig: def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint",
"if 1. < self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic environmental constraint",
"stress_factor(self, value): self._stress_factor = value self._sanitize() @property def save_folder(self): return",
"stress_factor(self): return self._stress_factor @stress_factor.setter def stress_factor(self, value): self._stress_factor = value",
"self._stress_factor @stress_factor.setter def stress_factor(self, value): self._stress_factor = value self._sanitize() @property",
"<= 0.: raise ValueError(\"Stress factor has to be in the",
"<= 0.: raise ValueError(\"Synaptic environmental constraint has to be in",
"@property def save_folder(self): return self._save_folder @save_folder.setter def save_folder(self, value): self._save_folder",
"save_folder(self): return self._save_folder @save_folder.setter def save_folder(self, value): self._save_folder = value",
"= value self._sanitize() def __getitem__(self, item): if item == \"self\":",
"- 1.)\") if 1. < self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic",
"_sanitize(self): if 1. < self._group_environmental_constraint <= 0.: raise ValueError(\"Group environmental",
"@property def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint",
"has to be in the range [0. - 1.)\") if",
"= synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor = stress_factor self._save_folder =",
"[0. - 1.)\") if 1. < self._stress_factor <= 0.: raise",
"ValueError(\"Stress factor has to be in the range [0. -",
"value self._sanitize() @property def stress_factor(self): return self._stress_factor @stress_factor.setter def stress_factor(self,",
"1. < self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic environmental constraint has",
"return self._save_folder @save_folder.setter def save_folder(self, value): self._save_folder = value self._sanitize()",
"save_folder(self, value): self._save_folder = value self._sanitize() def __getitem__(self, item): if",
"self._sanitize() @property def save_folder(self): return self._save_folder @save_folder.setter def save_folder(self, value):",
"self._stress_factor = stress_factor self._save_folder = save_folder self._sanitize() def _sanitize(self): if",
"- 1.)\") if 1. < self._stress_factor <= 0.: raise ValueError(\"Stress",
"1.)\") if 1. < self._synaptic_environmental_constraint <= 0.: raise ValueError(\"Synaptic environmental",
"@property def stress_factor(self): return self._stress_factor @stress_factor.setter def stress_factor(self, value): self._stress_factor",
"def save_folder(self): return self._save_folder @save_folder.setter def save_folder(self, value): self._save_folder =",
"stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint = group_environmental_constraint self._stress_factor =",
"self._group_environmental_constraint = value self._sanitize() @property def stress_factor(self): return self._stress_factor @stress_factor.setter",
"group_environmental_constraint self._stress_factor = stress_factor self._save_folder = save_folder self._sanitize() def _sanitize(self):",
"save_folder self._sanitize() def _sanitize(self): if 1. < self._group_environmental_constraint <= 0.:",
"<= 0.: raise ValueError(\"Group environmental constraint has to be in",
"0.: raise ValueError(\"Synaptic environmental constraint has to be in the",
"def group_environmental_constraint(self): return self._group_environmental_constraint @group_environmental_constraint.setter def group_environmental_constraint(self, value): self._group_environmental_constraint =",
"1. < self._group_environmental_constraint <= 0.: raise ValueError(\"Group environmental constraint has",
"range [0. - 1.)\") if not os.path.exists(self._save_folder): os.makedirs(self._save_folder) @property def",
"import os class StressedNetConfig: def __init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")):",
"stress_factor self._save_folder = save_folder self._sanitize() def _sanitize(self): if 1. <",
"__init__(self, synaptic_environmental_constraint=0.8, group_environmental_constraint=0.6, stress_factor=0.8, save_folder=os.path.expanduser(\"~/.nervous/models/\")): self._synaptic_environmental_constraint = synaptic_environmental_constraint self._group_environmental_constraint =",
"environmental constraint has to be in the range [0. -",
"ValueError(\"Synaptic environmental constraint has to be in the range [0."
] |
[
"2.0 (the \"License\"); # you may not use this file",
"lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum,",
"as validator from mindspore._checkparam import Rel from .optimizer import Optimizer,",
"============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import functional as F, composite as",
"self.weight_decay > 0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads)",
"0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\", l1, 0.0,",
"weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros')",
"validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\",",
"learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power,",
"= weight_decay self.decay_tf = tuple((lambda: True)() for x in self.parameters)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"_check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check",
"validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\",",
"0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float],",
"= lr_power self.reciprocal_scale = 1.0 / loss_scale self.weight_decay = weight_decay",
"Parameter from mindspore.common import Tensor import mindspore.common.dtype as mstype from",
"weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum,",
"use locks for update operation. Default: False. loss_scale (float): Value",
"l1, l2, lr_power)) return success def _check_param(initial_accum, learning_rate, lr_power, l1,",
"self.reciprocal_scale), grads) lr = self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr,",
"(tuple[Tensor]) - The gradients of `params` in optimizer, the shape",
"Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args: params (list[Parameter]): A list",
"be zero or positive value. Default: 0.0. Inputs: - **grads**",
"\"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate, l1,",
"[float], prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float],",
"loss_scale, weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\",",
"is zero. Default: -0.5. l1 (float): l1 regularization strength, must",
"l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale,",
"to zero. Default: 0.0. use_locking (bool): If True use locks",
"Inputs: - **grads** (tuple[Tensor]) - The gradients of `params` in",
"Optimization for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad",
"must be zero or positive values. Default: 0.1. learning_rate (float):",
"View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args: params",
"to zero. Default: 0.0. l2 (float): l2 regularization strength, must",
"use this file except in compliance with the License. #",
"Value for the loss scale. It should be equal to",
"or positive value. Default: 0.0. Inputs: - **grads** (tuple[Tensor]) -",
"Rel.GE, prim_name) class FTRL(Optimizer): \"\"\" Implement the FTRL algorithm with",
"0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0,",
"<https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click Prediction: a View from",
"if self.weight_decay > 0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params,",
"less than or equal to zero. Use fixed learning rate",
"prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name) class FTRL(Optimizer): \"\"\" Implement",
"self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr = self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"`params` should be Parameter. initial_accum (float): The starting value for",
"import functional as F, composite as C, operations as P",
"l2 (float): l2 regularization strength, must be greater than or",
"License. # You may obtain a copy of the License",
"def _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None):",
"shape is as same as the `params` in optimizer. Outputs:",
"import mindspore.common.dtype as mstype from mindspore._checkparam import Validator as validator",
"under the License is distributed on an \"AS IS\" BASIS,",
"Parameter. initial_accum (float): The starting value for accumulators, must be",
"License for the specific language governing permissions and # limitations",
"zero. Default: 0.0. use_locking (bool): If True use locks for",
"will be updated. The element in `params` should be Parameter.",
"# limitations under the License. # ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops",
"FTRL is an online convex optimization algorithm that adaptively chooses",
"= self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1 self.l2 = l2 self.lr_power",
"be Parameter. initial_accum (float): The starting value for accumulators, must",
"True)() for x in self.parameters) self.hyper_map = C.HyperMap() self.opt =",
"the shape is as same as the `params` in optimizer.",
"self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2, self.lr_power), linear, grads, params, moments)",
"decay value to multiply weight, must be zero or positive",
"Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE,",
"learning rate value, should be positive. Default: 0.001. lr_power (float):",
"= nn.FTRL(net.trainable_params()) >>> model = Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\"",
"1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0,",
"zero. Default: -0.5. l1 (float): l1 regularization strength, must be",
"return success def _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale=1.0,",
"learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power,",
"l2, lr_power)) return success def _check_param(initial_accum, learning_rate, lr_power, l1, l2,",
"success def _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0,",
"the `params` in optimizer. Outputs: tuple[Parameter], the updated parameters, the",
"(bool): If True use locks for update operation. Default: False.",
"mindspore.common.dtype as mstype from mindspore._checkparam import Validator as validator from",
"prim_name) class FTRL(Optimizer): \"\"\" Implement the FTRL algorithm with ApplyFtrl",
"if self.reciprocal_scale != 1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr",
"should be equal to or greater than 1.0. Default: 1.0.",
"and # limitations under the License. # ============================================================================ \"\"\"FTRL\"\"\" from",
"in compliance with the License. # You may obtain a",
"value for accumulators, must be zero or positive values. Default:",
"self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1 self.l2",
"software # distributed under the License is distributed on an",
"zero or positive value. Default: 0.0. Inputs: - **grads** (tuple[Tensor])",
"validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\",",
"prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name)",
"l2, use_locking, loss_scale, weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear",
"the weight parameter.\"\"\" success = True success = F.depend(success, opt(weight,",
"for update operation. Default: False. loss_scale (float): Value for the",
"\"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate, l1, l2, lr_power,",
"Huawei Technologies Co., Ltd # # Licensed under the Apache",
"as P from mindspore.common.parameter import Parameter from mindspore.common import Tensor",
"as the `params` in optimizer. Outputs: tuple[Parameter], the updated parameters,",
"validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\",",
"self.decay_tf = tuple((lambda: True)() for x in self.parameters) self.hyper_map =",
"validator from mindspore._checkparam import Rel from .optimizer import Optimizer, apply_decay,",
"mstype.int32) def construct(self, grads): params = self.parameters moments = self.moments",
"power controls how the learning rate decreases during training, must",
"mindspore._checkparam import Validator as validator from mindspore._checkparam import Rel from",
"the same as `params`. Examples: >>> net = Net() >>>",
"Co., Ltd # # Licensed under the Apache License, Version",
"learning_rate, l1, l2, lr_power, linear, gradient, weight, moment): \"\"\"Apply ftrl",
"self.linear if self.weight_decay > 0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf,",
"self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1 self.l2 = l2 self.lr_power =",
"1.0. wegith_decay (float): Weight decay value to multiply weight, must",
"= self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr = self.learning_rate success = self.hyper_map(F.partial(ftrl_opt,",
"validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name) class",
"`params` in optimizer, the shape is as same as the",
"chooses its regularization function based on the loss functions. Refer",
"for the loss scale. It should be equal to or",
"[float], prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool],",
"loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5,",
"ApplyFtrl Operator. FTRL is an online convex optimization algorithm that",
"Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name)",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"if lr_power is zero. Default: -0.5. l1 (float): l1 regularization",
"Default: 0.0. l2 (float): l2 regularization strength, must be greater",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\", l2,",
"# See the License for the specific language governing permissions",
"under the License. # ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import functional",
"greater than or equal to zero. Default: 0.0. l2 (float):",
"lr_power)) return success def _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking,",
"language governing permissions and # limitations under the License. #",
"should be Parameter. initial_accum (float): The starting value for accumulators,",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"Use fixed learning rate if lr_power is zero. Default: -0.5.",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"zero. Default: 0.0. l2 (float): l2 regularization strength, must be",
"nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params()) >>> model = Model(net, loss_fn=loss,",
"with the License. # You may obtain a copy of",
"[float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float],",
"self.lr_power = lr_power self.reciprocal_scale = 1.0 / loss_scale self.weight_decay =",
"params = self.parameters moments = self.moments linear = self.linear if",
"be updated. The element in `params` should be Parameter. initial_accum",
"rate power controls how the learning rate decreases during training,",
"linear, gradient, weight, moment): \"\"\"Apply ftrl optimizer to the weight",
"to paper `Ad Click Prediction: a View from the Trenches",
"locks for update operation. Default: False. loss_scale (float): Value for",
"(float): l1 regularization strength, must be greater than or equal",
"Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE,",
"a View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args:",
"compliance with the License. # You may obtain a copy",
"(float): The learning rate value, should be positive. Default: 0.001.",
"agreed to in writing, software # distributed under the License",
"paper `Ad Click Prediction: a View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_",
"must be less than or equal to zero. Use fixed",
"= nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params()) >>> model = Model(net,",
"must be zero or positive value. Default: 0.0. Inputs: -",
"distributed under the License is distributed on an \"AS IS\"",
"use_locking (bool): If True use locks for update operation. Default:",
"self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1 self.l2 = l2",
"mindspore.common import Tensor import mindspore.common.dtype as mstype from mindspore._checkparam import",
"loss_scale self.weight_decay = weight_decay self.decay_tf = tuple((lambda: True)() for x",
"express or implied. # See the License for the specific",
"[bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE,",
"[float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float],",
"except in compliance with the License. # You may obtain",
"prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name)",
"Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT,",
"in optimizer, the shape is as same as the `params`",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"to the weight parameter.\"\"\" success = True success = F.depend(success,",
"not use this file except in compliance with the License.",
"weight, moment): \"\"\"Apply ftrl optimizer to the weight parameter.\"\"\" success",
"Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click Prediction: a",
"equal to zero. Use fixed learning rate if lr_power is",
"1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr = self.learning_rate success",
"0.0, Rel.GE, prim_name) class FTRL(Optimizer): \"\"\" Implement the FTRL algorithm",
"Outputs: tuple[Parameter], the updated parameters, the shape is the same",
"writing, software # distributed under the License is distributed on",
"Default: 0.1. learning_rate (float): The learning rate value, should be",
"same as `params`. Examples: >>> net = Net() >>> loss",
"= P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32) def construct(self, grads): params",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click",
"construct(self, grads): params = self.parameters moments = self.moments linear =",
"(float): Value for the loss scale. It should be equal",
"C, operations as P from mindspore.common.parameter import Parameter from mindspore.common",
"/ loss_scale self.weight_decay = weight_decay self.decay_tf = tuple((lambda: True)() for",
"controls how the learning rate decreases during training, must be",
"initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate,",
"moment): \"\"\"Apply ftrl optimizer to the weight parameter.\"\"\" success =",
"= tuple((lambda: True)() for x in self.parameters) self.hyper_map = C.HyperMap()",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"permissions and # limitations under the License. # ============================================================================ \"\"\"FTRL\"\"\"",
"Ltd # # Licensed under the Apache License, Version 2.0",
"**grads** (tuple[Tensor]) - The gradients of `params` in optimizer, the",
"= Tensor(1, mstype.int32) def construct(self, grads): params = self.parameters moments",
"Operator. FTRL is an online convex optimization algorithm that adaptively",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\",",
"Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click Prediction: a View",
"l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power,",
"than or equal to zero. Default: 0.0. use_locking (bool): If",
"\"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt,",
"positive value. Default: 0.0. Inputs: - **grads** (tuple[Tensor]) - The",
"self.l2 = l2 self.lr_power = lr_power self.reciprocal_scale = 1.0 /",
"- The gradients of `params` in optimizer, the shape is",
"validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name) class FTRL(Optimizer): \"\"\" Implement the",
"strength, must be greater than or equal to zero. Default:",
"= self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2, self.lr_power), linear, grads, params,",
"validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\",",
"of `params` in optimizer, the shape is as same as",
"as F, composite as C, operations as P from mindspore.common.parameter",
"l1, l2, use_locking, loss_scale, weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum)",
"rate if lr_power is zero. Default: -0.5. l1 (float): l1",
"self.weight_decay), self.decay_tf, params, grads) if self.reciprocal_scale != 1.0: grads =",
"opt(weight, moment, linear, gradient, learning_rate, l1, l2, lr_power)) return success",
"validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale,",
"optimizer. Outputs: tuple[Parameter], the updated parameters, the shape is the",
"True use locks for update operation. Default: False. loss_scale (float):",
"F, composite as C, operations as P from mindspore.common.parameter import",
"model = Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def __init__(self, params,",
"learning rate decreases during training, must be less than or",
"init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1 self.l2 =",
"The gradients of `params` in optimizer, the shape is as",
"the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args: params (list[Parameter]): A",
"linear, gradient, learning_rate, l1, l2, lr_power)) return success def _check_param(initial_accum,",
"= self.moments linear = self.linear if self.weight_decay > 0.0: grads",
"(float): Weight decay value to multiply weight, must be zero",
"initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate,",
"from mindspore.common.parameter import Parameter from mindspore.common import Tensor import mindspore.common.dtype",
"\"\"\" Implement the FTRL algorithm with ApplyFtrl Operator. FTRL is",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"The element in `params` should be Parameter. initial_accum (float): The",
"= l2 self.lr_power = lr_power self.reciprocal_scale = 1.0 / loss_scale",
"rate decreases during training, must be less than or equal",
"Default: 0.001. lr_power (float): Learning rate power controls how the",
"the License is distributed on an \"AS IS\" BASIS, #",
"\"Tensor\") def _tensor_run_opt(opt, learning_rate, l1, l2, lr_power, linear, gradient, weight,",
"gradient, weight, moment): \"\"\"Apply ftrl optimizer to the weight parameter.\"\"\"",
"Optimizer, apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\",",
"l2 self.lr_power = lr_power self.reciprocal_scale = 1.0 / loss_scale self.weight_decay",
"(list[Parameter]): A list of parameter, which will be updated. The",
"positive values. Default: 0.1. learning_rate (float): The learning rate value,",
"Refer to paper `Adaptive Bound Optimization for Online Convex Optimization",
"loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params()) >>> model =",
"operation. Default: False. loss_scale (float): Value for the loss scale.",
"wegith_decay (float): Weight decay value to multiply weight, must be",
"nn.FTRL(net.trainable_params()) >>> model = Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def",
"than or equal to zero. Use fixed learning rate if",
"success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2, self.lr_power), linear, grads,",
"x in self.parameters) self.hyper_map = C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one",
"training, must be less than or equal to zero. Use",
"self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 =",
"!= 1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr = self.learning_rate",
"as C, operations as P from mindspore.common.parameter import Parameter from",
"\"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate, l1, l2, lr_power, linear,",
"its regularization function based on the loss functions. Refer to",
"_tensor_run_opt(opt, learning_rate, l1, l2, lr_power, linear, gradient, weight, moment): \"\"\"Apply",
"prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name)",
"value. Default: 0.0. Inputs: - **grads** (tuple[Tensor]) - The gradients",
"Default: 0.0. Inputs: - **grads** (tuple[Tensor]) - The gradients of",
"self.opt = P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32) def construct(self, grads):",
"law or agreed to in writing, software # distributed under",
"Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE,",
"parameters, the shape is the same as `params`. Examples: >>>",
"or equal to zero. Default: 0.0. use_locking (bool): If True",
"\"\"\"FTRL\"\"\" from mindspore.ops import functional as F, composite as C,",
"loss functions. Refer to paper `Adaptive Bound Optimization for Online",
"Refer to paper `Ad Click Prediction: a View from the",
"to zero. Use fixed learning rate if lr_power is zero.",
"functional as F, composite as C, operations as P from",
"\"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate,",
"`params` in optimizer. Outputs: tuple[Parameter], the updated parameters, the shape",
"initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate,",
"optimizer=opt, metrics=None) \"\"\" def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0,",
"be greater than or equal to zero. Default: 0.0. l2",
"with ApplyFtrl Operator. FTRL is an online convex optimization algorithm",
"the loss functions. Refer to paper `Adaptive Bound Optimization for",
"validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\",",
"loss_scale (float): Value for the loss scale. It should be",
"_check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale, weight_decay, self.cls_name) self.moments",
"lr = self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2,",
"may obtain a copy of the License at # #",
"Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under",
"rate value, should be positive. Default: 0.001. lr_power (float): Learning",
"from mindspore.ops import functional as F, composite as C, operations",
"updated. The element in `params` should be Parameter. initial_accum (float):",
"validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\",",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"may not use this file except in compliance with the",
"value to multiply weight, must be zero or positive value.",
"same as the `params` in optimizer. Outputs: tuple[Parameter], the updated",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL,",
"lr_power, l1, l2, use_locking, loss_scale, weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\",",
"regularization function based on the loss functions. Refer to paper",
"this file except in compliance with the License. # You",
"be equal to or greater than 1.0. Default: 1.0. wegith_decay",
"= self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2, self.lr_power),",
"online convex optimization algorithm that adaptively chooses its regularization function",
"operations as P from mindspore.common.parameter import Parameter from mindspore.common import",
"0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads) if self.reciprocal_scale",
"self.reciprocal_scale = 1.0 / loss_scale self.weight_decay = weight_decay self.decay_tf =",
"params, grads) if self.reciprocal_scale != 1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale),",
"0.1. learning_rate (float): The learning rate value, should be positive.",
"grads) lr = self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1,",
"l1, l2, lr_power, linear, gradient, weight, moment): \"\"\"Apply ftrl optimizer",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"0.0. use_locking (bool): If True use locks for update operation.",
"= l1 self.l2 = l2 self.lr_power = lr_power self.reciprocal_scale =",
"# # Licensed under the Apache License, Version 2.0 (the",
"functions. Refer to paper `Adaptive Bound Optimization for Online Convex",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"grads) if self.reciprocal_scale != 1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads)",
"> 0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads) if",
"lr_power, linear, gradient, weight, moment): \"\"\"Apply ftrl optimizer to the",
"parameter.\"\"\" success = True success = F.depend(success, opt(weight, moment, linear,",
"Implement the FTRL algorithm with ApplyFtrl Operator. FTRL is an",
"P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32) def construct(self, grads): params =",
"adaptively chooses its regularization function based on the loss functions.",
"learning rate if lr_power is zero. Default: -0.5. l1 (float):",
"The learning rate value, should be positive. Default: 0.001. lr_power",
"Learning rate power controls how the learning rate decreases during",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"Default: -0.5. l1 (float): l1 regularization strength, must be greater",
"lr_power is zero. Default: -0.5. l1 (float): l1 regularization strength,",
"def construct(self, grads): params = self.parameters moments = self.moments linear",
"[float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name) class FTRL(Optimizer): \"\"\"",
">>> model = Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def __init__(self,",
"(float): Learning rate power controls how the learning rate decreases",
"mindspore.common.parameter import Parameter from mindspore.common import Tensor import mindspore.common.dtype as",
"Tensor import mindspore.common.dtype as mstype from mindspore._checkparam import Validator as",
"validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\",",
"weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name) class FTRL(Optimizer):",
"value, should be positive. Default: 0.001. lr_power (float): Learning rate",
"optimizer, the shape is as same as the `params` in",
"= Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def __init__(self, params, initial_accum=0.1,",
"import Parameter from mindspore.common import Tensor import mindspore.common.dtype as mstype",
"P from mindspore.common.parameter import Parameter from mindspore.common import Tensor import",
"<https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args: params (list[Parameter]): A list of",
"self.parameters moments = self.moments linear = self.linear if self.weight_decay >",
"Args: params (list[Parameter]): A list of parameter, which will be",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"mindspore.ops import functional as F, composite as C, operations as",
"an online convex optimization algorithm that adaptively chooses its regularization",
"the License. # ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import functional as",
"prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name)",
"use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power, l1,",
"self.one = Tensor(1, mstype.int32) def construct(self, grads): params = self.parameters",
"import Tensor import mindspore.common.dtype as mstype from mindspore._checkparam import Validator",
"from .optimizer import Optimizer, apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\",",
"class FTRL(Optimizer): \"\"\" Implement the FTRL algorithm with ApplyFtrl Operator.",
"from mindspore._checkparam import Rel from .optimizer import Optimizer, apply_decay, grad_scale",
"fixed learning rate if lr_power is zero. Default: -0.5. l1",
"must be greater than or equal to zero. Default: 0.0.",
".optimizer import Optimizer, apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\",",
"validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\",",
"`Ad Click Prediction: a View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for",
"or implied. # See the License for the specific language",
"Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE,",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"optimization algorithm that adaptively chooses its regularization function based on",
"is the same as `params`. Examples: >>> net = Net()",
"self.learning_rate success = self.hyper_map(F.partial(ftrl_opt, self.opt, lr, self.l1, self.l2, self.lr_power), linear,",
"self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale, weight_decay,",
"positive. Default: 0.001. lr_power (float): Learning rate power controls how",
"Model(net, loss_fn=loss, optimizer=opt, metrics=None) \"\"\" def __init__(self, params, initial_accum=0.1, learning_rate=0.001,",
"C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32) def construct(self,",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"in `params` should be Parameter. initial_accum (float): The starting value",
"prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name)",
"parameter, which will be updated. The element in `params` should",
"grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\",",
"or equal to zero. Use fixed learning rate if lr_power",
"regularization strength, must be greater than or equal to zero.",
"apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\",",
"success = F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1, l2,",
"It should be equal to or greater than 1.0. Default:",
"Default: 1.0. wegith_decay (float): Weight decay value to multiply weight,",
"Rel from .optimizer import Optimizer, apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\")",
"loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay,",
"(the \"License\"); # you may not use this file except",
"the FTRL algorithm with ApplyFtrl Operator. FTRL is an online",
"greater than 1.0. Default: 1.0. wegith_decay (float): Weight decay value",
"# you may not use this file except in compliance",
"self.parameters) self.hyper_map = C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1,",
"engineering document. Args: params (list[Parameter]): A list of parameter, which",
"lr_power (float): Learning rate power controls how the learning rate",
"0.0. l2 (float): l2 regularization strength, must be greater than",
"accumulators, must be zero or positive values. Default: 0.1. learning_rate",
"l1 self.l2 = l2 self.lr_power = lr_power self.reciprocal_scale = 1.0",
"grads): params = self.parameters moments = self.moments linear = self.linear",
"param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name)",
"FTRL(Optimizer): \"\"\" Implement the FTRL algorithm with ApplyFtrl Operator. FTRL",
"as same as the `params` in optimizer. Outputs: tuple[Parameter], the",
"l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate,",
"# # Unless required by applicable law or agreed to",
"(float): The starting value for accumulators, must be zero or",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"self.weight_decay = weight_decay self.decay_tf = tuple((lambda: True)() for x in",
"Click Prediction: a View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering",
"= self.parameters moments = self.moments linear = self.linear if self.weight_decay",
"moments = self.moments linear = self.linear if self.weight_decay > 0.0:",
"self.reciprocal_scale != 1.0: grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr =",
"Version 2.0 (the \"License\"); # you may not use this",
"prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0, Rel.GE, prim_name)",
"net = Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt =",
"= True success = F.depend(success, opt(weight, moment, linear, gradient, learning_rate,",
"weight parameter.\"\"\" success = True success = F.depend(success, opt(weight, moment,",
"ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\",",
"import Rel from .optimizer import Optimizer, apply_decay, grad_scale ftrl_opt =",
"lr_power self.reciprocal_scale = 1.0 / loss_scale self.weight_decay = weight_decay self.decay_tf",
"weight_decay self.decay_tf = tuple((lambda: True)() for x in self.parameters) self.hyper_map",
"If True use locks for update operation. Default: False. loss_scale",
"lr, self.l1, self.l2, self.lr_power), linear, grads, params, moments) return success",
"implied. # See the License for the specific language governing",
"\"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate, l1, l2,",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"learning_rate, lr_power, l1, l2, use_locking, loss_scale, weight_decay, self.cls_name) self.moments =",
"should be positive. Default: 0.001. lr_power (float): Learning rate power",
"document. Args: params (list[Parameter]): A list of parameter, which will",
"zero. Use fixed learning rate if lr_power is zero. Default:",
"Bound Optimization for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper",
"Validator as validator from mindspore._checkparam import Rel from .optimizer import",
"weight_decay, 0.0, Rel.GE, prim_name) class FTRL(Optimizer): \"\"\" Implement the FTRL",
"by applicable law or agreed to in writing, software #",
"mstype from mindspore._checkparam import Validator as validator from mindspore._checkparam import",
"l1 regularization strength, must be greater than or equal to",
"init='zeros') self.l1 = l1 self.l2 = l2 self.lr_power = lr_power",
"2020 Huawei Technologies Co., Ltd # # Licensed under the",
"l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float],",
"algorithm with ApplyFtrl Operator. FTRL is an online convex optimization",
"opt = nn.FTRL(net.trainable_params()) >>> model = Model(net, loss_fn=loss, optimizer=opt, metrics=None)",
"updated parameters, the shape is the same as `params`. Examples:",
"function based on the loss functions. Refer to paper `Adaptive",
"based on the loss functions. Refer to paper `Adaptive Bound",
"be less than or equal to zero. Use fixed learning",
"prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name)",
"learning_rate, lr_power, l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\"",
"mindspore._checkparam import Rel from .optimizer import Optimizer, apply_decay, grad_scale ftrl_opt",
"is an online convex optimization algorithm that adaptively chooses its",
"prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0,",
"or equal to zero. Default: 0.0. l2 (float): l2 regularization",
"prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name)",
">>> opt = nn.FTRL(net.trainable_params()) >>> model = Model(net, loss_fn=loss, optimizer=opt,",
"use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\", loss_scale, 1.0,",
"0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0,",
"loss_scale, 1.0, Rel.GE, prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay,",
"ftrl optimizer to the weight parameter.\"\"\" success = True success",
"\"Tensor\", \"Tensor\") def _tensor_run_opt(opt, learning_rate, l1, l2, lr_power, linear, gradient,",
"self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1",
"lr_power, [float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1,",
"# ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import functional as F, composite",
"be greater than or equal to zero. Default: 0.0. use_locking",
"loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power, l1, l2,",
"list of parameter, which will be updated. The element in",
"loss scale. It should be equal to or greater than",
"that adaptively chooses its regularization function based on the loss",
"or greater than 1.0. Default: 1.0. wegith_decay (float): Weight decay",
"use_locking, loss_scale, weight_decay, self.cls_name) self.moments = self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear =",
"tuple((lambda: True)() for x in self.parameters) self.hyper_map = C.HyperMap() self.opt",
"\"\"\" def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False,",
"metrics=None) \"\"\" def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0,",
"= 1.0 / loss_scale self.weight_decay = weight_decay self.decay_tf = tuple((lambda:",
"= C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32) def",
"tuple[Parameter], the updated parameters, the shape is the same as",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"linear = self.linear if self.weight_decay > 0.0: grads = self.hyper_map(F.partial(apply_decay,",
"from mindspore._checkparam import Validator as validator from mindspore._checkparam import Rel",
"than 1.0. Default: 1.0. wegith_decay (float): Weight decay value to",
"Unless required by applicable law or agreed to in writing,",
"equal to or greater than 1.0. Default: 1.0. wegith_decay (float):",
"= self.linear if self.weight_decay > 0.0: grads = self.hyper_map(F.partial(apply_decay, self.weight_decay),",
"convex optimization algorithm that adaptively chooses its regularization function based",
"prim_name) validator.check_value_type(\"weight_decay\", weight_decay, [float], prim_name) validator.check_number(\"weight_decay\", weight_decay, 0.0, Rel.GE, prim_name)",
"initial_accum (float): The starting value for accumulators, must be zero",
"the learning rate decreases during training, must be less than",
"in optimizer. Outputs: tuple[Parameter], the updated parameters, the shape is",
"equal to zero. Default: 0.0. use_locking (bool): If True use",
"l2, [float], prim_name) validator.check_number(\"l2\", l2, 0.0, Rel.GE, prim_name) validator.check_value_type(\"use_locking\", use_locking,",
"Technologies Co., Ltd # # Licensed under the Apache License,",
"the specific language governing permissions and # limitations under the",
"Examples: >>> net = Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits() >>>",
"values. Default: 0.1. learning_rate (float): The learning rate value, should",
"paper `Adaptive Bound Optimization for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer",
"as `params`. Examples: >>> net = Net() >>> loss =",
"__init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0):",
"applicable law or agreed to in writing, software # distributed",
"= C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\",",
"lr_power, l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\",",
"use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name)",
"gradient, learning_rate, l1, l2, lr_power)) return success def _check_param(initial_accum, learning_rate,",
"Weight decay value to multiply weight, must be zero or",
"Default: False. loss_scale (float): Value for the loss scale. It",
"in writing, software # distributed under the License is distributed",
"l2 regularization strength, must be greater than or equal to",
"to or greater than 1.0. Default: 1.0. wegith_decay (float): Weight",
"validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\",",
"params) _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale, weight_decay, self.cls_name)",
"update operation. Default: False. loss_scale (float): Value for the loss",
"shape is the same as `params`. Examples: >>> net =",
"l1 (float): l1 regularization strength, must be greater than or",
"starting value for accumulators, must be zero or positive values.",
"0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\", l2, 0.0,",
"prim_name) validator.check_value_type(\"use_locking\", use_locking, [bool], prim_name) validator.check_value_type(\"loss_scale\", loss_scale, [float], prim_name) validator.check_number(\"loss_scale\",",
"prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float], prim_name)",
"for engineering document. Args: params (list[Parameter]): A list of parameter,",
"moment, linear, gradient, learning_rate, l1, l2, lr_power)) return success def",
"decreases during training, must be less than or equal to",
"0.0. Inputs: - **grads** (tuple[Tensor]) - The gradients of `params`",
"\"\"\"Apply ftrl optimizer to the weight parameter.\"\"\" success = True",
"@ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\") def",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float], prim_name) validator.check_number(\"l1\", l1,",
"License, Version 2.0 (the \"License\"); # you may not use",
"F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1, l2, lr_power)) return",
"the loss scale. It should be equal to or greater",
"import Optimizer, apply_decay, grad_scale ftrl_opt = C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\",",
"The starting value for accumulators, must be zero or positive",
"Tensor(1, mstype.int32) def construct(self, grads): params = self.parameters moments =",
"# You may obtain a copy of the License at",
"# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed",
"prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name)",
"be zero or positive values. Default: 0.1. learning_rate (float): The",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"C.MultitypeFuncGraph(\"ftrl_opt\") @ftrl_opt.register(\"Function\", \"Tensor\", \"Number\", \"Number\", \"Number\", \"Tensor\", \"Tensor\", \"Tensor\", \"Tensor\")",
"success = True success = F.depend(success, opt(weight, moment, linear, gradient,",
"in self.parameters) self.hyper_map = C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one =",
"def _tensor_run_opt(opt, learning_rate, l1, l2, lr_power, linear, gradient, weight, moment):",
"than or equal to zero. Default: 0.0. l2 (float): l2",
"is as same as the `params` in optimizer. Outputs: tuple[Parameter],",
"super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking, loss_scale,",
"algorithm that adaptively chooses its regularization function based on the",
"[float], prim_name) validator.check_number(\"lr_power\", lr_power, 0.0, Rel.LE, prim_name) validator.check_value_type(\"l1\", l1, [float],",
"how the learning rate decreases during training, must be less",
">>> net = Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt",
"weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params) _check_param(initial_accum, learning_rate, lr_power, l1, l2, use_locking,",
"grads = self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads) if self.reciprocal_scale !=",
"to multiply weight, must be zero or positive value. Default:",
"the License for the specific language governing permissions and #",
"zero or positive values. Default: 0.1. learning_rate (float): The learning",
"1.0. Default: 1.0. wegith_decay (float): Weight decay value to multiply",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"for accumulators, must be zero or positive values. Default: 0.1.",
"def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0,",
"of parameter, which will be updated. The element in `params`",
"either express or implied. # See the License for the",
"as mstype from mindspore._checkparam import Validator as validator from mindspore._checkparam",
"validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE, prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\",",
"\"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum, [float], prim_name) validator.check_number(\"initial_accum\", initial_accum, 0.0, Rel.GE,",
"from mindspore.common import Tensor import mindspore.common.dtype as mstype from mindspore._checkparam",
"for x in self.parameters) self.hyper_map = C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking)",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"-0.5. l1 (float): l1 regularization strength, must be greater than",
"self.decay_tf, params, grads) if self.reciprocal_scale != 1.0: grads = self.hyper_map(F.partial(grad_scale,",
"grads = self.hyper_map(F.partial(grad_scale, self.reciprocal_scale), grads) lr = self.learning_rate success =",
"`params`. Examples: >>> net = Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits()",
"self.l1 = l1 self.l2 = l2 self.lr_power = lr_power self.reciprocal_scale",
"the updated parameters, the shape is the same as `params`.",
"l2, lr_power, linear, gradient, weight, moment): \"\"\"Apply ftrl optimizer to",
"l1, l2, use_locking, loss_scale=1.0, weight_decay=0.0, prim_name=None): \"\"\"Check param.\"\"\" validator.check_value_type(\"initial_accum\", initial_accum,",
"during training, must be less than or equal to zero.",
"the shape is the same as `params`. Examples: >>> net",
">>> loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params()) >>> model",
"FTRL algorithm with ApplyFtrl Operator. FTRL is an online convex",
"on the loss functions. Refer to paper `Adaptive Bound Optimization",
"composite as C, operations as P from mindspore.common.parameter import Parameter",
"element in `params` should be Parameter. initial_accum (float): The starting",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"License. # ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import functional as F,",
"params (list[Parameter]): A list of parameter, which will be updated.",
"or positive values. Default: 0.1. learning_rate (float): The learning rate",
"weight, must be zero or positive value. Default: 0.0. Inputs:",
"self.moments linear = self.linear if self.weight_decay > 0.0: grads =",
"greater than or equal to zero. Default: 0.0. use_locking (bool):",
"learning_rate (float): The learning rate value, should be positive. Default:",
"to paper `Adaptive Bound Optimization for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_.",
"limitations under the License. # ============================================================================ \"\"\"FTRL\"\"\" from mindspore.ops import",
"validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2, [float], prim_name) validator.check_number(\"l2\",",
"self.hyper_map = C.HyperMap() self.opt = P.ApplyFtrl(use_locking=use_locking) self.one = Tensor(1, mstype.int32)",
"= F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1, l2, lr_power))",
"\"License\"); # you may not use this file except in",
"1.0 / loss_scale self.weight_decay = weight_decay self.decay_tf = tuple((lambda: True)()",
"self.opt, lr, self.l1, self.l2, self.lr_power), linear, grads, params, moments) return",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"`Adaptive Bound Optimization for Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to",
"False. loss_scale (float): Value for the loss scale. It should",
"which will be updated. The element in `params` should be",
"be positive. Default: 0.001. lr_power (float): Learning rate power controls",
"[float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name) validator.check_value_type(\"lr_power\", lr_power, [float],",
"# distributed under the License is distributed on an \"AS",
"True success = F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1,",
"equal to zero. Default: 0.0. l2 (float): l2 regularization strength,",
"# Unless required by applicable law or agreed to in",
"Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params()) >>>",
"= self.parameters.clone(prefix=\"moments\", init=initial_accum) self.linear = self.parameters.clone(prefix=\"linear\", init='zeros') self.l1 = l1",
"A list of parameter, which will be updated. The element",
"= self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads) if self.reciprocal_scale != 1.0:",
"self.hyper_map(F.partial(apply_decay, self.weight_decay), self.decay_tf, params, grads) if self.reciprocal_scale != 1.0: grads",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= Net() >>> loss = nn.SoftmaxCrossEntropyWithLogits() >>> opt = nn.FTRL(net.trainable_params())",
"learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0, use_locking=False, loss_scale=1.0, weight_decay=0.0): super(FTRL, self).__init__(learning_rate, params)",
"gradients of `params` in optimizer, the shape is as same",
"(float): l2 regularization strength, must be greater than or equal",
"You may obtain a copy of the License at #",
"optimizer to the weight parameter.\"\"\" success = True success =",
"l1, [float], prim_name) validator.check_number(\"l1\", l1, 0.0, Rel.GE, prim_name) validator.check_value_type(\"l2\", l2,",
"Online Convex Optimization <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click Prediction:",
"prim_name) validator.check_value_type(\"learning_rate\", learning_rate, [float], prim_name) validator.check_number(\"learning_rate\", learning_rate, 0.0, Rel.GT, prim_name)",
"Default: 0.0. use_locking (bool): If True use locks for update",
"scale. It should be equal to or greater than 1.0.",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document. Args: params (list[Parameter]):",
"learning_rate, l1, l2, lr_power)) return success def _check_param(initial_accum, learning_rate, lr_power,",
"import Validator as validator from mindspore._checkparam import Rel from .optimizer",
"- **grads** (tuple[Tensor]) - The gradients of `params` in optimizer,",
"governing permissions and # limitations under the License. # ============================================================================",
"Prediction: a View from the Trenches <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document.",
"multiply weight, must be zero or positive value. Default: 0.0.",
"0.001. lr_power (float): Learning rate power controls how the learning"
] |
[
"ProductDescriptions=[instance_version], NextToken=token) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token",
"aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg'] + x[1]['latest'])",
"price if the availability zone is in this list Returns:",
"\"m2.4xlarge\" search_regions ({str}): Set of regions we want to look",
"fetch_spot_prices(region, start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region = {}",
"'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions, str): search_regions = {search_regions}",
"EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice'])",
"missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time, end_time,",
"for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken']",
"= boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for",
"'latest price + average price' over the duration that the",
"filter_availability_zones=filter_availability_zones) if not len(result_stats): raise Exception(\"No valid avialability zones found",
"only return a price if the availability zone is in",
"avialability zones found for region %s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone,",
"run this is used as the amount of time to",
"for the average Returns: (str, {}) : e.g. ('us-east-1b': {'min':",
"for region in search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length,",
"that the boto3 response is empty. \"\"\" conn = boto3.client('ec2',",
"ValueError, raised in the event that the boto3 response is",
"instance_type (str): Type of aws instance e.g. \"m2.4xlarge\" search_regions ({str}):",
"for zone, prices in by_zone.iteritems(): if filter_availability_zones is None or",
"'avg': sum(prices) / float(len(prices)), 'latest': prices[0]} prices_per_region[zone] = region_prices return",
"list Returns: dict, {'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\"",
"is expected to run for Args: filter_availability_zones ({str}): We only",
"{search_regions} aggregated_prices = {} for region in search_regions: result_stats =",
"over for the average Returns: (str, {}) : e.g. ('us-east-1b':",
"search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability zone from a",
"(datetime.datetime): end_time (datetime.datetime): instance_type (str): instance_version (str): the types of",
"str, float: yields tuple of avialability_zone and price over the",
"want to look for availability zones in. expected_job_length (datetime.timedelta): The",
"({str}): We only return results for zones in this set",
"(datetime.datetime): instance_type (str): instance_version (str): the types of instances that",
"= res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups",
"3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone = {} for zone, price in",
"Returns: (str, {}) : e.g. ('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8,",
"instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices by region, returns min,",
"e.g. \"m2.4xlarge\" search_regions ({str}): Set of regions we want to",
"by 'latest price + average price' over the duration that",
"None or zone in filter_availability_zones: region_prices = {'min': min(prices), 'max':",
"regions. Cheapest is determined by 'latest price + average price'",
"if isinstance(search_regions, str): search_regions = {search_regions} aggregated_prices = {} for",
"not len(result_stats): raise Exception(\"No valid avialability zones found for region",
"Cheapest is determined by 'latest price + average price' over",
"= conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']: yield",
"from a set of regions. Cheapest is determined by 'latest",
"while token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for",
"2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions, str): search_regions =",
"= min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg'] + x[1]['latest']) return cheapest_availability_zone, stats",
"price + average price' over the duration that the job",
"cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg'] + x[1]['latest']) return",
"of regions we want to look for availability zones in.",
"datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats): raise",
"'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches",
"conn = boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version])",
"{'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone = {} for",
"max and avg price. Args: region (str): region to look",
"to return prices for. Returns: yield str, float: yields tuple",
"wish to return prices for. Returns: yield str, float: yields",
"a price if the availability zone is in this list",
"for zones in this set instance_type (str): Type of aws",
"str): search_regions = {search_regions} aggregated_prices = {} for region in",
"set instance_type (str): Type of aws instance e.g. \"m2.4xlarge\" search_regions",
"in start_time (datetime.datetime): end_time (datetime.datetime): instance_type (str): instance_version (str): the",
"in search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type,",
"this is used as the amount of time to look",
"determined by 'latest price + average price' over the duration",
"by region, returns min, max and avg price. Args: region",
"then we only return a price if the availability zone",
"price over the period Raises: ValueError, raised in the event",
"for instances in start_time (datetime.datetime): end_time (datetime.datetime): instance_type (str): instance_version",
"result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if",
"only return results for zones in this set instance_type (str):",
"boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item",
"of avialability_zone and price over the period Raises: ValueError, raised",
"search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones)",
"we expect the job to run this is used as",
"res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']:",
"zone, price in fetch_spot_prices(region, start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price)",
"(str, {}) : e.g. ('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0})",
"region_prices return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the",
"({str}): Set of regions we want to look for availability",
"availability zones in. expected_job_length (datetime.timedelta): The period we expect the",
"\"\"\"Groups raw prices by region, returns min, max and avg",
"Raises: ValueError, raised in the event that the boto3 response",
"filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability zone from a set",
"InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice'])",
"(str): Type of aws instance e.g. \"m2.4xlarge\" search_regions ({str}): Set",
"min(prices), 'max': max(prices), 'avg': sum(prices) / float(len(prices)), 'latest': prices[0]} prices_per_region[zone]",
"prices of EC2 spot instances from AWS. Args: region (str):",
"and price over the period Raises: ValueError, raised in the",
"filter_availability_zones ({str}): We only return results for zones in this",
"instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region = {} for zone, prices in",
"('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions, str):",
"Set of regions we want to look for availability zones",
"item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] while",
"instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats): raise Exception(\"No valid avialability zones",
"prices for. filter_availability_zones ({str}): if set then we only return",
"conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item in res['SpotPriceHistory']: yield",
"for zone, price in fetch_spot_prices(region, start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone,",
"average price' over the duration that the job is expected",
"+ average price' over the duration that the job is",
"res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time,",
"and avg price. Args: region (str): region to look for",
"float(item['SpotPrice']) token = res['NextToken'] while token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time,",
"we wish to return prices for. filter_availability_zones ({str}): if set",
"Args: filter_availability_zones ({str}): We only return results for zones in",
"start_time (datetime.datetime): end_time (datetime.datetime): instance_type (str): instance_version (str): the types",
"if the availability zone is in this list Returns: dict,",
"region_prices = {'min': min(prices), 'max': max(prices), 'avg': sum(prices) / float(len(prices)),",
"'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone = {} for zone, price",
"def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices",
"item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type,",
"<gh_stars>0 import datetime import boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES =",
"instance_version (str): the types of instances that we wish to",
"item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] while token: res = conn.describe_spot_price_history(StartTime=start_time,",
"used as the amount of time to look back over",
"= fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not",
"expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability zone from a set of",
"instances that we wish to return prices for. Returns: yield",
"AWS. Args: region (str): region to look for instances in",
"the job is expected to run for Args: filter_availability_zones ({str}):",
"Returns: dict, {'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone",
"= 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION):",
"region in search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(),",
"region to look for instances in start_time (datetime.datetime): end_time (datetime.datetime):",
"min, max and avg price. Args: region (str): region to",
"return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest",
"for. Returns: yield str, float: yields tuple of avialability_zone and",
"for. filter_availability_zones ({str}): if set then we only return a",
"set then we only return a price if the availability",
"expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats): raise Exception(\"No valid",
"token = res['NextToken'] while token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type],",
"Exception(\"No valid avialability zones found for region %s\" % (region,))",
"the amount of time to look back over for the",
"over the duration that the job is expected to run",
"instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices by region, returns min, max",
"def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2",
"prices in by_zone.iteritems(): if filter_availability_zones is None or zone in",
"if not len(result_stats): raise Exception(\"No valid avialability zones found for",
"response is empty. \"\"\" conn = boto3.client('ec2', region_name=region) res =",
"filter_availability_zones ({str}): if set then we only return a price",
"\"\"\" by_zone = {} for zone, price in fetch_spot_prices(region, start_time,",
"instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2 spot instances from AWS. Args:",
"return prices for. Returns: yield str, float: yields tuple of",
"raise Exception(\"No valid avialability zones found for region %s\" %",
"that we wish to return prices for. filter_availability_zones ({str}): if",
"region %s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda",
"datetime import boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b',",
"prices for. Returns: yield str, float: yields tuple of avialability_zone",
"= {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note",
"filter_availability_zones is None or zone in filter_availability_zones: region_prices = {'min':",
"types of instances that we wish to return prices for.",
"in the event that the boto3 response is empty. \"\"\"",
"is None or zone in filter_availability_zones: region_prices = {'min': min(prices),",
"instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region = {} for zone, prices",
"zones found for region %s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats",
"of instances that we wish to return prices for. filter_availability_zones",
"job is expected to run for Args: filter_availability_zones ({str}): We",
"to look back over for the average Returns: (str, {})",
"\"\"\" if isinstance(search_regions, str): search_regions = {search_regions} aggregated_prices = {}",
"= {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d is missing",
"'us-east-1c', 'us-east-1e'} # note d is missing INSTANCE_VERSION = 'Linux/UNIX",
"price in fetch_spot_prices(region, start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region",
"'latest':3.0}} \"\"\" by_zone = {} for zone, price in fetch_spot_prices(region,",
"= {} for zone, price in fetch_spot_prices(region, start_time, end_time, instance_type,",
"instances from AWS. Args: region (str): region to look for",
"by_zone = {} for zone, price in fetch_spot_prices(region, start_time, end_time,",
"is in this list Returns: dict, {'us-east-1b': {'min': 2.01, 'max':",
"/ float(len(prices)), 'latest': prices[0]} prices_per_region[zone] = region_prices return prices_per_region def",
"a set of regions. Cheapest is determined by 'latest price",
"aws instance e.g. \"m2.4xlarge\" search_regions ({str}): Set of regions we",
"{'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone = {}",
"if set then we only return a price if the",
"d is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region,",
"over the period Raises: ValueError, raised in the event that",
"instances that we wish to return prices for. filter_availability_zones ({str}):",
"end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2 spot instances from",
"the boto3 response is empty. \"\"\" conn = boto3.client('ec2', region_name=region)",
"in this set instance_type (str): Type of aws instance e.g.",
"stats = min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg'] + x[1]['latest']) return cheapest_availability_zone,",
"raised in the event that the boto3 response is empty.",
"sum(prices) / float(len(prices)), 'latest': prices[0]} prices_per_region[zone] = region_prices return prices_per_region",
"end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region = {} for zone,",
"regions we want to look for availability zones in. expected_job_length",
"availability zone is in this list Returns: dict, {'us-east-1b': {'min':",
"instance_type (str): instance_version (str): the types of instances that we",
"note d is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def",
"= conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item in res['SpotPriceHistory']:",
"{'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d is missing INSTANCE_VERSION",
"float(len(prices)), 'latest': prices[0]} prices_per_region[zone] = region_prices return prices_per_region def get_cheapest_availability_zone(instance_type,",
"instances in start_time (datetime.datetime): end_time (datetime.datetime): instance_type (str): instance_version (str):",
"boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'}",
"\"\"\"Get the cheapest availability zone from a set of regions.",
"(region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg'] +",
"empty. \"\"\" conn = boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time,",
"cheapest availability zone from a set of regions. Cheapest is",
"in filter_availability_zones: region_prices = {'min': min(prices), 'max': max(prices), 'avg': sum(prices)",
"end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices by region, returns",
"fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() - expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats):",
"period Raises: ValueError, raised in the event that the boto3",
"expect the job to run this is used as the",
"= {} for region in search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow()",
"3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions, str): search_regions = {search_regions} aggregated_prices",
"'latest':3.0}) \"\"\" if isinstance(search_regions, str): search_regions = {search_regions} aggregated_prices =",
"the types of instances that we wish to return prices",
"'latest': prices[0]} prices_per_region[zone] = region_prices return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION,",
"zones in this set instance_type (str): Type of aws instance",
"back over for the average Returns: (str, {}) : e.g.",
"ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token =",
"conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'],",
"for Args: filter_availability_zones ({str}): We only return results for zones",
"as the amount of time to look back over for",
"in fetch_spot_prices(region, start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region =",
"returns min, max and avg price. Args: region (str): region",
"prices_per_region[zone] = region_prices return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)):",
"if filter_availability_zones is None or zone in filter_availability_zones: region_prices =",
"spot instances from AWS. Args: region (str): region to look",
"{'min': min(prices), 'max': max(prices), 'avg': sum(prices) / float(len(prices)), 'latest': prices[0]}",
"run for Args: filter_availability_zones ({str}): We only return results for",
"is used as the amount of time to look back",
"look back over for the average Returns: (str, {}) :",
"US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d is",
"of regions. Cheapest is determined by 'latest price + average",
"zone is in this list Returns: dict, {'us-east-1b': {'min': 2.01,",
"'us-east-1e'} # note d is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon",
"in this list Returns: dict, {'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8,",
"get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability zone from",
"Type of aws instance e.g. \"m2.4xlarge\" search_regions ({str}): Set of",
"yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] while token: res =",
"raw prices by region, returns min, max and avg price.",
"the duration that the job is expected to run for",
"start_time, end_time, instance_type, instance_version): by_zone.setdefault(zone, []).append(price) prices_per_region = {} for",
"item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] def",
"of instances that we wish to return prices for. Returns:",
"expected to run for Args: filter_availability_zones ({str}): We only return",
"filter_availability_zones=None): \"\"\"Groups raw prices by region, returns min, max and",
"res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw",
"avialability_zone and price over the period Raises: ValueError, raised in",
"from AWS. Args: region (str): region to look for instances",
"# note d is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)'",
"return a price if the availability zone is in this",
"\"\"\"Fetches prices of EC2 spot instances from AWS. Args: region",
"Args: region (str): region to look for instances in start_time",
"the job to run this is used as the amount",
"that the job is expected to run for Args: filter_availability_zones",
"availability zone from a set of regions. Cheapest is determined",
"{'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions, str): search_regions",
"'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d is missing INSTANCE_VERSION =",
"zone from a set of regions. Cheapest is determined by",
"e.g. ('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if isinstance(search_regions,",
"in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] def fetch_price_stats_per_availability_zone(region,",
"avg price. Args: region (str): region to look for instances",
"end_time (datetime.datetime): instance_type (str): instance_version (str): the types of instances",
"results for zones in this set instance_type (str): Type of",
"instance e.g. \"m2.4xlarge\" search_regions ({str}): Set of regions we want",
"(str): the types of instances that we wish to return",
"search_regions ({str}): Set of regions we want to look for",
"{}) : e.g. ('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\"",
"in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] while token:",
"'max': max(prices), 'avg': sum(prices) / float(len(prices)), 'latest': prices[0]} prices_per_region[zone] =",
"job to run this is used as the amount of",
"the cheapest availability zone from a set of regions. Cheapest",
"zone, prices in by_zone.iteritems(): if filter_availability_zones is None or zone",
"average Returns: (str, {}) : e.g. ('us-east-1b': {'min': 2.01, 'max':",
"yield str, float: yields tuple of avialability_zone and price over",
"to look for instances in start_time (datetime.datetime): end_time (datetime.datetime): instance_type",
"to run this is used as the amount of time",
"for availability zones in. expected_job_length (datetime.timedelta): The period we expect",
"res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] while token: res",
"- expected_job_length, datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats): raise Exception(\"No",
"return prices for. filter_availability_zones ({str}): if set then we only",
"search_regions = {search_regions} aggregated_prices = {} for region in search_regions:",
"prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability",
"len(result_stats): raise Exception(\"No valid avialability zones found for region %s\"",
"period we expect the job to run this is used",
"\"\"\" conn = boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type],",
"we want to look for availability zones in. expected_job_length (datetime.timedelta):",
"{'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} # note d",
"by_zone.iteritems(): if filter_availability_zones is None or zone in filter_availability_zones: region_prices",
"aggregated_prices = {} for region in search_regions: result_stats = fetch_price_stats_per_availability_zone(region,",
"the period Raises: ValueError, raised in the event that the",
"The period we expect the job to run this is",
"this list Returns: dict, {'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}}",
"2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone = {} for zone,",
"valid avialability zones found for region %s\" % (region,)) aggregated_prices.update(result_stats)",
"to run for Args: filter_availability_zones ({str}): We only return results",
"(str): instance_version (str): the types of instances that we wish",
"%s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda x:",
"for region %s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(),",
"found for region %s\" % (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats =",
"return results for zones in this set instance_type (str): Type",
"by_zone.setdefault(zone, []).append(price) prices_per_region = {} for zone, prices in by_zone.iteritems():",
"res['NextToken'] while token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token)",
"prices_per_region = {} for zone, prices in by_zone.iteritems(): if filter_availability_zones",
"{} for zone, prices in by_zone.iteritems(): if filter_availability_zones is None",
"float(item['SpotPrice']) token = res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION,",
"= {} for zone, prices in by_zone.iteritems(): if filter_availability_zones is",
"fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices by",
"max(prices), 'avg': sum(prices) / float(len(prices)), 'latest': prices[0]} prices_per_region[zone] = region_prices",
"import datetime import boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a',",
": e.g. ('us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}) \"\"\" if",
"region_name=region) res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in",
"the availability zone is in this list Returns: dict, {'us-east-1b':",
"We only return results for zones in this set instance_type",
"expected_job_length (datetime.timedelta): The period we expect the job to run",
"duration that the job is expected to run for Args:",
"token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item",
"in. expected_job_length (datetime.timedelta): The period we expect the job to",
"price. Args: region (str): region to look for instances in",
"{} for zone, price in fetch_spot_prices(region, start_time, end_time, instance_type, instance_version):",
"% (region,)) aggregated_prices.update(result_stats) cheapest_availability_zone, stats = min(aggregated_prices.iteritems(), key=lambda x: x[1]['avg']",
"fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2 spot",
"of aws instance e.g. \"m2.4xlarge\" search_regions ({str}): Set of regions",
"InstanceTypes=[instance_type], ProductDescriptions=[instance_version]) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token",
"this set instance_type (str): Type of aws instance e.g. \"m2.4xlarge\"",
"the event that the boto3 response is empty. \"\"\" conn",
"EC2 spot instances from AWS. Args: region (str): region to",
"of EC2 spot instances from AWS. Args: region (str): region",
"{} for region in search_regions: result_stats = fetch_price_stats_per_availability_zone(region, datetime.datetime.utcnow() -",
"= {search_regions} aggregated_prices = {} for region in search_regions: result_stats",
"to look for availability zones in. expected_job_length (datetime.timedelta): The period",
"we wish to return prices for. Returns: yield str, float:",
"({str}): if set then we only return a price if",
"datetime.datetime.utcnow(), instance_type, filter_availability_zones=filter_availability_zones) if not len(result_stats): raise Exception(\"No valid avialability",
"in by_zone.iteritems(): if filter_availability_zones is None or zone in filter_availability_zones:",
"instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2 spot instances from AWS.",
"yield item['AvailabilityZone'], float(item['SpotPrice']) token = res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time,",
"(Amazon VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices",
"prices[0]} prices_per_region[zone] = region_prices return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES,",
"is empty. \"\"\" conn = boto3.client('ec2', region_name=region) res = conn.describe_spot_price_history(StartTime=start_time,",
"event that the boto3 response is empty. \"\"\" conn =",
"zone in filter_availability_zones: region_prices = {'min': min(prices), 'max': max(prices), 'avg':",
"(datetime.timedelta): The period we expect the job to run this",
"region (str): region to look for instances in start_time (datetime.datetime):",
"is missing INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time,",
"isinstance(search_regions, str): search_regions = {search_regions} aggregated_prices = {} for region",
"look for availability zones in. expected_job_length (datetime.timedelta): The period we",
"filter_availability_zones: region_prices = {'min': min(prices), 'max': max(prices), 'avg': sum(prices) /",
"set of regions. Cheapest is determined by 'latest price +",
"tuple of avialability_zone and price over the period Raises: ValueError,",
"NextToken=token) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'], float(item['SpotPrice']) token =",
"(str): region to look for instances in start_time (datetime.datetime): end_time",
"that we wish to return prices for. Returns: yield str,",
"= res['NextToken'] while token: res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version],",
"prices by region, returns min, max and avg price. Args:",
"res = conn.describe_spot_price_history(StartTime=start_time, EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item in",
"region, returns min, max and avg price. Args: region (str):",
"or zone in filter_availability_zones: region_prices = {'min': min(prices), 'max': max(prices),",
"def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get the cheapest availability zone",
"the average Returns: (str, {}) : e.g. ('us-east-1b': {'min': 2.01,",
"[]).append(price) prices_per_region = {} for zone, prices in by_zone.iteritems(): if",
"VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of",
"wish to return prices for. filter_availability_zones ({str}): if set then",
"yields tuple of avialability_zone and price over the period Raises:",
"start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): \"\"\"Fetches prices of EC2 spot instances",
"INSTANCE_VERSION = 'Linux/UNIX (Amazon VPC)' def fetch_spot_prices(region, start_time, end_time, instance_type,",
"import boto3 US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c',",
"start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None): \"\"\"Groups raw prices by region,",
"look for instances in start_time (datetime.datetime): end_time (datetime.datetime): instance_type (str):",
"EndTime=end_time, InstanceTypes=[instance_type], ProductDescriptions=[instance_version], NextToken=token) for item in res['SpotPriceHistory']: yield item['AvailabilityZone'],",
"token = res['NextToken'] def fetch_price_stats_per_availability_zone(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION, filter_availability_zones=None):",
"dict, {'us-east-1b': {'min': 2.01, 'max': 3.53,'avg':2.8, 'latest':3.0}} \"\"\" by_zone =",
"of time to look back over for the average Returns:",
"zones in. expected_job_length (datetime.timedelta): The period we expect the job",
"price' over the duration that the job is expected to",
"= region_prices return prices_per_region def get_cheapest_availability_zone(instance_type, search_regions=US_EAST_REGION, filter_availability_zones=US_EAST_AVAILABILITY_ZONES, expected_job_length=datetime.timedelta(days=1)): \"\"\"Get",
"float: yields tuple of avialability_zone and price over the period",
"is determined by 'latest price + average price' over the",
"boto3 response is empty. \"\"\" conn = boto3.client('ec2', region_name=region) res",
"time to look back over for the average Returns: (str,",
"= {'min': min(prices), 'max': max(prices), 'avg': sum(prices) / float(len(prices)), 'latest':",
"Returns: yield str, float: yields tuple of avialability_zone and price",
"we only return a price if the availability zone is",
"to return prices for. filter_availability_zones ({str}): if set then we",
"amount of time to look back over for the average",
"US_EAST_REGION = {'us-east-1'} US_EAST_AVAILABILITY_ZONES = {'us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1e'} #"
] |
[] |
[
"x: x / 0) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert",
"by zero'), 1)\\ .flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'),",
"''' Author: huangbaochen<<EMAIL>> Date: 2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors:",
"2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY ''' import",
"==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by'), 1) !=\\",
"def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2)) == Success(2) assert Fail(ZeroDivisionError('division",
"1) with pytest.raises(TypeError): Success(1).flat_map(lambda x: x + 1) @pytest.mark.try_monad def",
"zero'), 0) !=\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_get():",
"assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division by zero').args",
"Fail(ZeroDivisionError('division by zero'), 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert",
"+ 1) == Success(2) assert Success(1).map(lambda x: x / 0)",
"x: x + 1) == Success(2) assert Success(1).map(lambda x: x",
"1)\\ .map(lambda x: x + 1) ==\\ Fail(ZeroDivisionError('division by zero'),",
"Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(),",
"zero').args assert Success(1).get() == 1 # pylint: disable=no-member assert Try(\"s\").get()",
"zero'), 1)\\ .flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'), 1)",
"Fail from fppy.option import Just, Nothing @pytest.mark.try_monad def test_try_apply(): assert",
"Success(1).map(lambda x: x + 1) == Success(2) assert Success(1).map(lambda x:",
"2 assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division",
"Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda x:",
"Success(1) @pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(),",
"import Just, Nothing @pytest.mark.try_monad def test_try_apply(): assert Try.apply(1) == Success(1)",
"1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert",
"assert Fail(ZeroDivisionError('division by zero'), 0) !=\\ Fail(ZeroDivisionError('division by zero'), 1)",
"ZeroDivisionError('division by zero').args assert Success(1).get() == 1 # pylint: disable=no-member",
"Success(2) assert Success(1).map(lambda x: x / 0) ==\\ Fail(ZeroDivisionError('division by",
"1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by'), 1)",
"assert Try(1) == Success(1) @pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1)) ==",
"x + 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def",
"Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 0) !=\\",
"assert Fail(ZeroDivisionError('division by zero'), 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1)",
"by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 0) !=\\ Fail(ZeroDivisionError('division",
"Fail(ZeroDivisionError('division by zero'), 0) !=\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad",
"zero'), 1) assert Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division by zero'),",
"Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division by zero').args assert",
"assert Success(1).get() == 1 # pylint: disable=no-member assert Try(\"s\").get() ==",
"fppy.try_monad import Try, Success, Fail from fppy.option import Just, Nothing",
"assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2) == 2 assert Success(1).get_or_else(2)",
"zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda x: x + 1) @pytest.mark.try_monad",
"def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2) == 2",
"== Success(1) @pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1)) == Just(1) assert",
"1)\\ .get().args ==\\ ZeroDivisionError('division by zero').args assert Success(1).get() == 1",
"assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by",
"def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_error_input() == 1",
"Nothing @pytest.mark.try_monad def test_try_apply(): assert Try.apply(1) == Success(1) assert Try(1)",
"1)) def test_try_monad_map(): assert Success(1).map(lambda x: x + 1) ==",
"Success(2) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda x: Success(1)) ==\\",
"zero'), 1) @pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'), 1)\\",
"assert Success(1).map(lambda x: x / 0) ==\\ Fail(ZeroDivisionError('division by zero'),",
"== Success(2) assert Success(1).map(lambda x: x / 0) ==\\ Fail(ZeroDivisionError('division",
"x + 1) @pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'),",
"x: Success(2)) == Success(2) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda",
"x / 0) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division",
"from fppy.try_monad import Try, Success, Fail from fppy.option import Just,",
"zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 0) !=\\ Fail(ZeroDivisionError('division by",
"Just, Nothing @pytest.mark.try_monad def test_try_apply(): assert Try.apply(1) == Success(1) assert",
"with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert",
"pytest.raises(TypeError): Success(1).flat_map(lambda x: x + 1) @pytest.mark.try_monad def test_try_monad_eq(): assert",
"pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert Success(1).map(lambda x: x +",
"Success(1).map(lambda x: x / 0) ==\\ Fail(ZeroDivisionError('division by zero'), 1)",
"21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY ''' import pytest",
"x: Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda",
"test_try_apply(): assert Try.apply(1) == Success(1) assert Try(1) == Success(1) @pytest.mark.try_monad",
"Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2) == 2 assert Success(1).get_or_else(2) ==",
"Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division by",
"assert Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division by zero'), 1) assert",
"1) @pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'), 1) ==\\",
"by zero'), 1) assert Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division by",
"by'), 1) !=\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by",
"+ 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map():",
"zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda x: x",
"Date: 2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子",
"by zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division by zero').args assert Success(1).get()",
"''' import pytest from fppy.try_monad import Try, Success, Fail from",
"def test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division",
"== \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'), 1)\\",
"LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY ''' import pytest from",
"==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 1)\\",
"def test_try_apply(): assert Try.apply(1) == Success(1) assert Try(1) == Success(1)",
"No MERCY ''' import pytest from fppy.try_monad import Try, Success,",
"Fail.unapply(Fail(TypeError(), 1)) == Nothing() with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1))",
"1) assert Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division by zero'), 1)",
"1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2)) == Success(2)",
"zero'), 1)\\ .get_or_else(2) == 2 assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad",
".map(lambda x: x + 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1)",
"# pylint: disable=no-member assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else():",
"x: x + 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad",
"Success(1).flat_map(lambda x: Success(2)) == Success(2) assert Fail(ZeroDivisionError('division by zero'), 1)\\",
"x: x + 1) @pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by",
"==\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda",
"Try(\"s\").get() == \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'),",
"1) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda x: x +",
"== Success(2) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda x: Success(1))",
".flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'), 1) with pytest.raises(TypeError):",
"== 2 assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert",
"Success(1) assert Try(1) == Success(1) @pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1))",
"by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda x:",
"Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda",
"import pytest from fppy.try_monad import Try, Success, Fail from fppy.option",
"with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert Success(1).map(lambda x: x",
"zero'), 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by'),",
"@pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args ==\\",
"def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'), 1) ==\\ Fail(ZeroDivisionError('division by",
"== Success(1) assert Try(1) == Success(1) @pytest.mark.try_monad def test_try_unapply(): assert",
"def test_try_unapply(): assert Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(), 1)) ==",
"with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1))",
"Try(1) == Success(1) @pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1)) == Just(1)",
"Just(1) assert Fail.unapply(Fail(TypeError(), 1)) == Nothing() with pytest.raises(TypeError): Fail.unapply(1) with",
"\"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2)",
"assert Fail.unapply(Fail(TypeError(), 1)) == Nothing() with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError):",
"@pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2) ==",
"pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def",
"test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_or_else(2) == 2 assert",
".get().args ==\\ ZeroDivisionError('division by zero').args assert Success(1).get() == 1 #",
"@pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2)) == Success(2) assert",
"zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division by zero').args assert Success(1).get() ==",
"1 # pylint: disable=no-member assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad def",
"1)\\ .get_or_else(2) == 2 assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def",
"assert Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda x: x + 1)",
"== Just(1) assert Fail.unapply(Fail(TypeError(), 1)) == Nothing() with pytest.raises(TypeError): Fail.unapply(1)",
"/ 0) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by",
"by zero'), 1) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division",
"Try.apply(1) == Success(1) assert Try(1) == Success(1) @pytest.mark.try_monad def test_try_unapply():",
"Success(1).flat_map(lambda x: x + 1) @pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division",
"1) @pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args",
"1)\\ .flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division by zero'), 1) with",
"2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No",
"def test_try_monad_map(): assert Success(1).map(lambda x: x + 1) == Success(2)",
"huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY ''' import pytest from fppy.try_monad",
"+ 1) @pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'), 1)",
"from fppy.option import Just, Nothing @pytest.mark.try_monad def test_try_apply(): assert Try.apply(1)",
".get_or_else(2) == 2 assert Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def test_try_monad_get_error_input():",
"test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2)) == Success(2) assert Fail(ZeroDivisionError('division by",
"assert Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division",
"Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division",
"1) assert Fail(ZeroDivisionError('division by zero'), 0) !=\\ Fail(ZeroDivisionError('division by zero'),",
"@pytest.mark.try_monad def test_try_unapply(): assert Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(), 1))",
"1) == Success(2) assert Success(1).map(lambda x: x / 0) ==\\",
"by zero').args assert Success(1).get() == 1 # pylint: disable=no-member assert",
"== 1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by zero'), 1)\\",
"assert Success(1).flat_map(lambda x: Success(2)) == Success(2) assert Fail(ZeroDivisionError('division by zero'),",
"Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert Success(1).map(lambda x:",
"!=\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division",
"==\\ ZeroDivisionError('division by zero').args assert Success(1).get() == 1 # pylint:",
"==\\ Fail(ZeroDivisionError('division by zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda x: x",
"Success, Fail from fppy.option import Just, Nothing @pytest.mark.try_monad def test_try_apply():",
"Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(), 1)) == Nothing() with pytest.raises(TypeError):",
"by zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda x: x + 1)",
"Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda x: Success(1)) ==\\ Fail(ZeroDivisionError('division by",
"pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert Success(1).map(lambda",
"test_try_unapply(): assert Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(), 1)) == Nothing()",
"Success(1).get_or_else(2) == 1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by zero'),",
"MERCY ''' import pytest from fppy.try_monad import Try, Success, Fail",
"1)) == Nothing() with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with",
"Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError): Success.unapply(Fail(Exception(), 1)) def test_try_monad_map():",
"assert Success.unapply(Success(1)) == Just(1) assert Fail.unapply(Fail(TypeError(), 1)) == Nothing() with",
"x + 1) == Success(2) assert Success(1).map(lambda x: x /",
"20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY",
"huangbaochen<<EMAIL>> Date: 2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description:",
"zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2)) ==",
"@pytest.mark.try_monad def test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'), 1) ==\\ Fail(ZeroDivisionError('division",
"Fail(ZeroDivisionError('division by'), 1) !=\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division",
"assert Success(1).map(lambda x: x + 1) == Success(2) assert Success(1).map(lambda",
"Nothing() with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1)",
"by zero'), 1)\\ .get_or_else(2) == 2 assert Success(1).get_or_else(2) == 1",
"Success.unapply(Fail(Exception(), 1)) def test_try_monad_map(): assert Success(1).map(lambda x: x + 1)",
"== 1 # pylint: disable=no-member assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad",
"assert Try.apply(1) == Success(1) assert Try(1) == Success(1) @pytest.mark.try_monad def",
"with pytest.raises(TypeError): Success(1).flat_map(lambda x: x + 1) @pytest.mark.try_monad def test_try_monad_eq():",
"1 @pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_error_input()",
"!=\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'), 0)",
"pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with pytest.raises(TypeError):",
"fppy.option import Just, Nothing @pytest.mark.try_monad def test_try_apply(): assert Try.apply(1) ==",
"by zero'), 0) !=\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def",
"import Try, Success, Fail from fppy.option import Just, Nothing @pytest.mark.try_monad",
"with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError): Success.unapply(1) with",
"zero'), 1)\\ .map(lambda x: x + 1) ==\\ Fail(ZeroDivisionError('division by",
"pytest from fppy.try_monad import Try, Success, Fail from fppy.option import",
"assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division by",
"Fail(ZeroDivisionError('division by zero'), 1)\\ .map(lambda x: x + 1) ==\\",
"0) !=\\ Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_get(): assert",
"@pytest.mark.try_monad def test_try_monad_get_error_input(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get_error_input() ==",
"== Nothing() with pytest.raises(TypeError): Fail.unapply(1) with pytest.raises(TypeError): Fail.unapply(Success(1)) with pytest.raises(TypeError):",
"1) !=\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'),",
"LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>> Description: 测试Try单子 No MERCY '''",
"test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'), 1)\\ .get().args ==\\ ZeroDivisionError('division by",
"by zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x: Success(2))",
"0) ==\\ Fail(ZeroDivisionError('division by zero'), 1) assert Fail(ZeroDivisionError('division by zero'),",
"测试Try单子 No MERCY ''' import pytest from fppy.try_monad import Try,",
"pylint: disable=no-member assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert",
"test_try_monad_eq(): assert Fail(ZeroDivisionError('division by zero'), 1) ==\\ Fail(ZeroDivisionError('division by zero'),",
"Description: 测试Try单子 No MERCY ''' import pytest from fppy.try_monad import",
"disable=no-member assert Try(\"s\").get() == \"s\" @pytest.mark.try_monad def test_try_monad_get_or_else(): assert Fail(ZeroDivisionError('division",
"test_try_monad_map(): assert Success(1).map(lambda x: x + 1) == Success(2) assert",
"Author: huangbaochen<<EMAIL>> Date: 2021-12-11 20:04:19 LastEditTime: 2021-12-11 21:46:16 LastEditors: huangbaochen<<EMAIL>>",
"Fail(ZeroDivisionError('division by zero'), 1) with pytest.raises(TypeError): Success(1).flat_map(lambda x: x +",
"Success(1).get() == 1 # pylint: disable=no-member assert Try(\"s\").get() == \"s\"",
"Fail(ZeroDivisionError('division by zero'), 1) @pytest.mark.try_monad def test_try_monad_flat_map(): assert Success(1).flat_map(lambda x:",
"Success(2)) == Success(2) assert Fail(ZeroDivisionError('division by zero'), 1)\\ .flat_map(lambda x:",
"by zero'), 1) @pytest.mark.try_monad def test_try_monad_get(): assert Fail(ZeroDivisionError('division by zero'),",
"@pytest.mark.try_monad def test_try_apply(): assert Try.apply(1) == Success(1) assert Try(1) ==",
"by zero'), 1)\\ .map(lambda x: x + 1) ==\\ Fail(ZeroDivisionError('division",
"Try, Success, Fail from fppy.option import Just, Nothing @pytest.mark.try_monad def"
] |
[
"given day\"\"\" day_num = date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id %",
"\"\"\"This function create a quote object from given fields dictionary.",
"import date from typing import Dict, Optional from sqlalchemy.orm import",
"Optional from sqlalchemy.orm import Session from sqlalchemy.sql.expression import func from",
"app.database.models import Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]])",
"func from app.database.models import Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields:",
"year. The quote is randomally selected from a set of",
"quote_per_day( session: Session, date: date = date.today() ) -> Optional[Quote]:",
"<reponame>yammesicka/calendar<filename>app/internal/daily_quotes.py from datetime import date from typing import Dict, Optional",
"of the year. The quote is randomally selected from a",
"to the given day\"\"\" day_num = date.timetuple().tm_yday quote = session.query(Quote).filter(",
"from datetime import date from typing import Dict, Optional from",
"text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day( session: Session, date: date =",
"import Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) ->",
"date from typing import Dict, Optional from sqlalchemy.orm import Session",
"sqlalchemy.sql.expression import func from app.database.models import Quote TOTAL_DAYS = 366",
"to the current day of the year. The quote is",
"matching to the given day\"\"\" day_num = date.timetuple().tm_yday quote =",
"-> Optional[Quote]: \"\"\"This function provides a daily quote, relevant to",
"the db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day( session:",
"date.today() ) -> Optional[Quote]: \"\"\"This function provides a daily quote,",
"quote, relevant to the current day of the year. The",
"day_num = date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id % TOTAL_DAYS ==",
"adding the data from the json into the db\"\"\" return",
"typing import Dict, Optional from sqlalchemy.orm import Session from sqlalchemy.sql.expression",
"Session, date: date = date.today() ) -> Optional[Quote]: \"\"\"This function",
"a set of quotes matching to the given day\"\"\" day_num",
"It is used for adding the data from the json",
"The quote is randomally selected from a set of quotes",
"Session from sqlalchemy.sql.expression import func from app.database.models import Quote TOTAL_DAYS",
"a daily quote, relevant to the current day of the",
"def quote_per_day( session: Session, date: date = date.today() ) ->",
"Dict[str, Optional[str]]) -> Quote: \"\"\"This function create a quote object",
"a quote object from given fields dictionary. It is used",
"provides a daily quote, relevant to the current day of",
"create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: \"\"\"This function create a quote",
"is randomally selected from a set of quotes matching to",
"Optional[str]]) -> Quote: \"\"\"This function create a quote object from",
"import Session from sqlalchemy.sql.expression import func from app.database.models import Quote",
"json into the db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def",
"-> Quote: \"\"\"This function create a quote object from given",
"author=quotes_fields['author'] ) def quote_per_day( session: Session, date: date = date.today()",
"the json into the db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author'] )",
"session: Session, date: date = date.today() ) -> Optional[Quote]: \"\"\"This",
"date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first() return",
"data from the json into the db\"\"\" return Quote( text=quotes_fields['text'],",
"= date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first()",
"Optional[Quote]: \"\"\"This function provides a daily quote, relevant to the",
"date = date.today() ) -> Optional[Quote]: \"\"\"This function provides a",
") def quote_per_day( session: Session, date: date = date.today() )",
"= date.today() ) -> Optional[Quote]: \"\"\"This function provides a daily",
"quote = session.query(Quote).filter( Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first() return quote",
"create a quote object from given fields dictionary. It is",
"is used for adding the data from the json into",
"= 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: \"\"\"This function",
"quote object from given fields dictionary. It is used for",
"the current day of the year. The quote is randomally",
"the year. The quote is randomally selected from a set",
"quote is randomally selected from a set of quotes matching",
"from typing import Dict, Optional from sqlalchemy.orm import Session from",
"the given day\"\"\" day_num = date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id",
"day of the year. The quote is randomally selected from",
"of quotes matching to the given day\"\"\" day_num = date.timetuple().tm_yday",
"Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote:",
"into the db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day(",
"current day of the year. The quote is randomally selected",
"from given fields dictionary. It is used for adding the",
"function create a quote object from given fields dictionary. It",
"from sqlalchemy.orm import Session from sqlalchemy.sql.expression import func from app.database.models",
"object from given fields dictionary. It is used for adding",
"fields dictionary. It is used for adding the data from",
"used for adding the data from the json into the",
"return Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day( session: Session, date:",
"dictionary. It is used for adding the data from the",
"def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: \"\"\"This function create a",
"the data from the json into the db\"\"\" return Quote(",
"datetime import date from typing import Dict, Optional from sqlalchemy.orm",
"from a set of quotes matching to the given day\"\"\"",
"from the json into the db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author']",
"daily quote, relevant to the current day of the year.",
"from app.database.models import Quote TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str,",
"date: date = date.today() ) -> Optional[Quote]: \"\"\"This function provides",
"randomally selected from a set of quotes matching to the",
"import func from app.database.models import Quote TOTAL_DAYS = 366 def",
"Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day( session: Session, date: date",
"from sqlalchemy.sql.expression import func from app.database.models import Quote TOTAL_DAYS =",
"given fields dictionary. It is used for adding the data",
"function provides a daily quote, relevant to the current day",
"366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: \"\"\"This function create",
"quotes matching to the given day\"\"\" day_num = date.timetuple().tm_yday quote",
"import Dict, Optional from sqlalchemy.orm import Session from sqlalchemy.sql.expression import",
"relevant to the current day of the year. The quote",
"for adding the data from the json into the db\"\"\"",
"TOTAL_DAYS = 366 def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote: \"\"\"This",
"day\"\"\" day_num = date.timetuple().tm_yday quote = session.query(Quote).filter( Quote.id % TOTAL_DAYS",
"selected from a set of quotes matching to the given",
"sqlalchemy.orm import Session from sqlalchemy.sql.expression import func from app.database.models import",
") -> Optional[Quote]: \"\"\"This function provides a daily quote, relevant",
"\"\"\"This function provides a daily quote, relevant to the current",
"Quote: \"\"\"This function create a quote object from given fields",
"Dict, Optional from sqlalchemy.orm import Session from sqlalchemy.sql.expression import func",
"db\"\"\" return Quote( text=quotes_fields['text'], author=quotes_fields['author'] ) def quote_per_day( session: Session,",
"set of quotes matching to the given day\"\"\" day_num ="
] |
[
"map(int, input().split()) w = list(map(int, input().split())) r = sum(map(lambda x:",
"k = map(int, input().split()) w = list(map(int, input().split())) r =",
"input().split()) w = list(map(int, input().split())) r = sum(map(lambda x: (x+k-1)//k,",
"= map(int, input().split()) w = list(map(int, input().split())) r = sum(map(lambda",
"w = list(map(int, input().split())) r = sum(map(lambda x: (x+k-1)//k, w))",
"= list(map(int, input().split())) r = sum(map(lambda x: (x+k-1)//k, w)) print((r+1)//2)",
"n, k = map(int, input().split()) w = list(map(int, input().split())) r"
] |
[
"elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD! if",
"('builtin_zlib', 'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\"",
"def get_opts(): return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits",
"import sys def is_active(): return True def get_name(): return \"Server\"",
"(env[\"tools\"]==\"no\"): # #no tools suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] #",
"bits binary','no') ] def get_flags(): return [ ('builtin_zlib', 'no'), ]",
"(env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize",
"def get_flags(): return [ ('builtin_zlib', 'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server'])",
"tools suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX']",
"'-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD! if (env[\"CXX\"]==\"clang++\"): env.Append(CPPFLAGS=['-DTYPED_METHOD_BIND']) env[\"CC\"]=\"clang\"",
"env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty():",
"env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else:",
"binary','no') ] def get_flags(): return [ ('builtin_zlib', 'no'), ] def",
"2**32 if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"):",
"enabled def get_opts(): return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32",
"can_build(): if (os.name!=\"posix\"): return False return True # enabled def",
"env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD! if (env[\"CXX\"]==\"clang++\"): env.Append(CPPFLAGS=['-DTYPED_METHOD_BIND']) env[\"CC\"]=\"clang\" env[\"LD\"]=\"clang++\"",
"os import sys def is_active(): return True def get_name(): return",
"sys def is_active(): return True def get_name(): return \"Server\" def",
"configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if",
"env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no tools suffix #",
"('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no') ] def get_flags():",
"return [ ('builtin_zlib', 'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"):",
"False return True # enabled def get_opts(): return [ ('use_llvm','Use",
"def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"):",
"#if (env[\"tools\"]==\"no\"): # #no tools suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX']",
"env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no tools suffix # env['OBJSUFFIX'] =",
"env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize >",
"return True # enabled def get_opts(): return [ ('use_llvm','Use llvm",
"if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"):",
"def can_build(): if (os.name!=\"posix\"): return False return True # enabled",
"suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if",
"def is_active(): return True def get_name(): return \"Server\" def can_build():",
"#no tools suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] =",
"env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32",
"env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD!",
"elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO",
"<reponame>leyyin/godot<gh_stars>10-100 import os import sys def is_active(): return True def",
"= \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif",
"env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if",
"if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED'])",
"return \"Server\" def can_build(): if (os.name!=\"posix\"): return False return True",
"(env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no",
"sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\"",
"import os import sys def is_active(): return True def get_name():",
"is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\"",
"env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z'])",
"(env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD! if (env[\"CXX\"]==\"clang++\"):",
"compiler','no'), ('force_32_bits','Force 32 bits binary','no') ] def get_flags(): return [",
"env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif",
"(env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED'])",
"is_active(): return True def get_name(): return \"Server\" def can_build(): if",
"(is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no tools suffix",
"if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): #",
"\".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2',",
"get_opts(): return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no')",
"return True def get_name(): return \"Server\" def can_build(): if (os.name!=\"posix\"):",
"if (os.name!=\"posix\"): return False return True # enabled def get_opts():",
"# enabled def get_opts(): return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force",
"[ ('builtin_zlib', 'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\"",
"32 bits binary','no') ] def get_flags(): return [ ('builtin_zlib', 'no'),",
"(os.name!=\"posix\"): return False return True # enabled def get_opts(): return",
"# env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED'])",
"True # enabled def get_opts(): return [ ('use_llvm','Use llvm compiler','no'),",
"> 2**32 if (env[\"bits\"]==\"default\"): if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if",
"return False return True # enabled def get_opts(): return [",
"\"Server\" def can_build(): if (os.name!=\"posix\"): return False return True #",
"get_flags(): return [ ('builtin_zlib', 'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server']) if",
"'no'), ] def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\"",
"env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer'])",
"if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if (env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"])",
"('force_32_bits','Force 32 bits binary','no') ] def get_flags(): return [ ('builtin_zlib',",
"def get_name(): return \"Server\" def can_build(): if (os.name!=\"posix\"): return False",
"else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no tools suffix # env['OBJSUFFIX']",
"\".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"):",
"if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"): if (is64):",
"# env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX'] = \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"):",
"# #no tools suffix # env['OBJSUFFIX'] = \".nt\"+env['OBJSUFFIX'] # env['LIBSUFFIX']",
"llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no') ] def get_flags(): return",
"(env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"): env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect",
"] def get_flags(): return [ ('builtin_zlib', 'no'), ] def configure(env):",
"= \".nt\"+env['LIBSUFFIX'] if (env[\"target\"]==\"release\"): env.Append(CCFLAGS=['-O2','-ffast-math','-fomit-frame-pointer']) elif (env[\"target\"]==\"release_debug\"): env.Append(CCFLAGS=['-O2','-ffast-math','-DDEBUG_ENABLED']) elif (env[\"target\"]==\"debug\"):",
"return [ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no') ]",
"(env[\"colored\"]==\"yes\"): if sys.stdout.isatty(): env.Append(CXXFLAGS=[\"-fcolor-diagnostics\"]) is64=sys.maxsize > 2**32 if (env[\"bits\"]==\"default\"): if",
"env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED']) env.Append(CPPFLAGS=['-DSERVER_ENABLED','-DUNIX_ENABLED']) env.Append(LIBS=['pthread','z']) #TODO detect linux/BSD! if (env[\"CXX\"]==\"clang++\"): env.Append(CPPFLAGS=['-DTYPED_METHOD_BIND'])",
"True def get_name(): return \"Server\" def can_build(): if (os.name!=\"posix\"): return",
"[ ('use_llvm','Use llvm compiler','no'), ('force_32_bits','Force 32 bits binary','no') ] def",
"get_name(): return \"Server\" def can_build(): if (os.name!=\"posix\"): return False return",
"] def configure(env): env.Append(CPPPATH=['#platform/server']) if (env[\"use_llvm\"]==\"yes\"): env[\"CC\"]=\"clang\" env[\"CXX\"]=\"clang++\" env[\"LD\"]=\"clang++\" if",
"if (is64): env[\"bits\"]=\"64\" else: env[\"bits\"]=\"32\" #if (env[\"tools\"]==\"no\"): # #no tools"
] |
[
"telemetry.TruckPositioning import Positioning class TruckValues: constant_values = None current_values =",
"class TruckValues: constant_values = None current_values = None positioning =",
"current_values = None positioning = None def __init__(self): self.current_values =",
"ConstantValues from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import Positioning class",
"telemetry.TruckConstants import ConstantValues from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import",
"__init__(self): self.current_values = CurrentValues() self.constant_values = ConstantValues() self.positioning = Positioning()",
"from telemetry.TruckPositioning import Positioning class TruckValues: constant_values = None current_values",
"CurrentValues from telemetry.TruckPositioning import Positioning class TruckValues: constant_values = None",
"telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import Positioning class TruckValues: constant_values",
"import Positioning class TruckValues: constant_values = None current_values = None",
"from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import Positioning class TruckValues:",
"import ConstantValues from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning import Positioning",
"from telemetry.TruckConstants import ConstantValues from telemetry.TruckCurrent import CurrentValues from telemetry.TruckPositioning",
"<reponame>SnipsMine/ETS2-Speedrun-Tool<filename>telemetry/Truck.py from telemetry.TruckConstants import ConstantValues from telemetry.TruckCurrent import CurrentValues from",
"import CurrentValues from telemetry.TruckPositioning import Positioning class TruckValues: constant_values =",
"Positioning class TruckValues: constant_values = None current_values = None positioning",
"None positioning = None def __init__(self): self.current_values = CurrentValues() self.constant_values",
"positioning = None def __init__(self): self.current_values = CurrentValues() self.constant_values =",
"= None def __init__(self): self.current_values = CurrentValues() self.constant_values = ConstantValues()",
"None current_values = None positioning = None def __init__(self): self.current_values",
"= None positioning = None def __init__(self): self.current_values = CurrentValues()",
"constant_values = None current_values = None positioning = None def",
"def __init__(self): self.current_values = CurrentValues() self.constant_values = ConstantValues() self.positioning =",
"TruckValues: constant_values = None current_values = None positioning = None",
"= None current_values = None positioning = None def __init__(self):",
"None def __init__(self): self.current_values = CurrentValues() self.constant_values = ConstantValues() self.positioning"
] |
[
"v[1] == 'United States of America').sortBy(lambda x: x[4], ascending =",
"an integer df = df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1 print('*'",
"# Question 4 print('*' * 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v:",
"csv from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType spark",
"> 100000).filter(lambda v: v[7] == 'FALSE').count()) print('\\n\\n') # Question 4",
"3 print('*' * 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4] >",
"== 'United States of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x)",
"df = spark.read.format('csv').option('header','true').load(path) # cast income as an integer df",
"data to dataframe path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) #",
"v: v[1] == 'United States of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda",
"import SparkSession from pyspark.sql.types import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc",
"False).map(lambda x: (x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n') # Question 5",
"# load data to dataframe path = 'fake_data.csv' df =",
"(x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()) print('\\n\\n') # Question 3",
"of America').sortBy(lambda x: x[4], ascending = False).map(lambda x: (x[3], x[6],",
"1 print('*' * 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda",
"* 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1] == 'United States",
"v[7] == 'FALSE').count()) print('\\n\\n') # Question 4 print('*' * 30)",
"a: a[1], ascending = False).take(1)) print('\\n\\n') # Question 2 print('*'",
"x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()) print('\\n\\n') # Question",
"# Question 6 print('*' * 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v:",
"x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1], ascending = False).take(1))",
"2\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of America').map(lambda x:",
"sum(x) / len(x)).collect()) print('\\n\\n') # Question 3 print('*' * 30)",
"of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()) print('\\n\\n')",
"print(df.rdd.filter(lambda v: v[1] == 'United States of America').sortBy(lambda x: x[4],",
"from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType spark =",
"= False).map(lambda x: (x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n') # Question",
"len(x)).collect()) print('\\n\\n') # Question 3 print('*' * 30) print('\\nQuestion 3\\n')",
"* 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda v:",
"x: x[4], ascending = False).map(lambda x: (x[3], x[6], x[4], x[5])).take(10))",
"print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') # Question 6 print('*' * 30)",
"= spark.sparkContext # load data to dataframe path = 'fake_data.csv'",
"America').sortBy(lambda x: x[4], ascending = False).map(lambda x: (x[3], x[6], x[4],",
"a[1], ascending = False).take(1)) print('\\n\\n') # Question 2 print('*' *",
"100000).filter(lambda v: v[7] == 'FALSE').count()) print('\\n\\n') # Question 4 print('*'",
"import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext # load",
"v: v[1] == 'United States of America').sortBy(lambda x: x[4], ascending",
"v: v[7] == 'FALSE').count()) print('\\n\\n') # Question 4 print('*' *",
"x[4], x[5])).take(10)) print('\\n\\n') # Question 5 print('*' * 30) print('\\nQuestion",
"5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') # Question 6 print('*' *",
"False).take(1)) print('\\n\\n') # Question 2 print('*' * 30) print('\\nQuestion 2\\n')",
"30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of",
"* 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') # Question",
"spark.read.format('csv').option('header','true').load(path) # cast income as an integer df = df.withColumn('Income',",
"# cast income as an integer df = df.withColumn('Income', df['Income'].cast(IntegerType()))",
"print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda x: x[4] <",
"Question 6 print('*' * 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5]",
"Question 2 print('*' * 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1]",
"# Question 5 print('*' * 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x:",
"x[4], ascending = False).map(lambda x: (x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n')",
"load data to dataframe path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path)",
"* 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda x:",
"30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') # Question 6",
"# Question 3 print('*' * 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v:",
"print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1], ascending =",
"print('*' * 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1] == 'United",
"income as an integer df = df.withColumn('Income', df['Income'].cast(IntegerType())) # Question",
"dataframe path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast income",
"x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()) print('\\n\\n') # Question 3 print('*'",
"30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda x: x[4]",
"spark.sparkContext # load data to dataframe path = 'fake_data.csv' df",
"SparkSession from pyspark.sql.types import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc =",
"1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1], ascending",
"# Question 1 print('*' * 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x:",
"print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda v: v[7] ==",
"print('*' * 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda",
"America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect()) print('\\n\\n') #",
"v[4] > 100000).filter(lambda v: v[7] == 'FALSE').count()) print('\\n\\n') # Question",
"sc = spark.sparkContext # load data to dataframe path =",
"import csv from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType",
"'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast income as an integer",
"df['Income'].cast(IntegerType())) # Question 1 print('*' * 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda",
"print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda v: v[7] == 'FALSE').count()) print('\\n\\n')",
"Question 5 print('*' * 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count())",
"= False).take(1)) print('\\n\\n') # Question 2 print('*' * 30) print('\\nQuestion",
"print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1],",
"Question 1 print('*' * 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1],",
"6\\n') print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda x: x[4] < 100000).count())",
"v[1] == 'United States of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x:",
"as an integer df = df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1",
"print('*' * 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda",
"x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1], ascending = False).take(1)) print('\\n\\n') #",
"print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of America').map(lambda",
"print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of America').sortBy(lambda",
"5 print('*' * 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n')",
"'United States of America').sortBy(lambda x: x[4], ascending = False).map(lambda x:",
"IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext # load data",
"(x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n') # Question 5 print('*' *",
"print('*' * 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals:",
"30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda v: v[7]",
"== 'FALSE').count()) print('\\n\\n') # Question 4 print('*' * 30) print('\\nQuestion",
"States of America').sortBy(lambda x: x[4], ascending = False).map(lambda x: (x[3],",
"States of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) / len(x)).collect())",
"ascending = False).take(1)) print('\\n\\n') # Question 2 print('*' * 30)",
"vals: len(set(vals))).sortBy(lambda a: a[1], ascending = False).take(1)) print('\\n\\n') # Question",
"print('*' * 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') #",
"30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of",
"df = df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1 print('*' * 30)",
"len(set(vals))).sortBy(lambda a: a[1], ascending = False).take(1)) print('\\n\\n') # Question 2",
"v: v[4] > 100000).filter(lambda v: v[7] == 'FALSE').count()) print('\\n\\n') #",
"3\\n') print(df.rdd.filter(lambda v: v[4] > 100000).filter(lambda v: v[7] == 'FALSE').count())",
"x[5])).take(10)) print('\\n\\n') # Question 5 print('*' * 30) print('\\nQuestion 5\\n')",
"pyspark.sql import SparkSession from pyspark.sql.types import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate()",
"= df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1 print('*' * 30) print('\\nQuestion",
"df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1 print('*' * 30) print('\\nQuestion 1\\n')",
"SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext # load data to dataframe path",
"to dataframe path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast",
"Question 4 print('*' * 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1]",
"* 30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda",
"print('\\n\\n') # Question 3 print('*' * 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda",
"Question 3 print('*' * 30) print('\\nQuestion 3\\n') print(df.rdd.filter(lambda v: v[4]",
"path = 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast income as",
"print('\\n\\n') # Question 2 print('*' * 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda",
"'United States of America').map(lambda x: (x[1], x[4])).groupByKey().mapValues(lambda x: sum(x) /",
"integer df = df.withColumn('Income', df['Income'].cast(IntegerType())) # Question 1 print('*' *",
"print('\\n\\n') # Question 6 print('*' * 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda",
"spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext # load data to",
"'FALSE').count()) print('\\n\\n') # Question 4 print('*' * 30) print('\\nQuestion 4\\n')",
"= SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext # load data to dataframe",
"print('*' * 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1] == 'United",
"x: (x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n') # Question 5 print('*'",
"30) print('\\nQuestion 1\\n') print(df.rdd.map(lambda x: (x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a:",
"/ len(x)).collect()) print('\\n\\n') # Question 3 print('*' * 30) print('\\nQuestion",
"4\\n') print(df.rdd.filter(lambda v: v[1] == 'United States of America').sortBy(lambda x:",
"== 'United States of America').sortBy(lambda x: x[4], ascending = False).map(lambda",
"ascending = False).map(lambda x: (x[3], x[6], x[4], x[5])).take(10)) print('\\n\\n') #",
"print(df.rdd.filter(lambda v: v[1] == 'United States of America').map(lambda x: (x[1],",
"print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda x: x[5]).count()) print('\\n\\n') # Question 6 print('*'",
"pyspark.sql.types import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext #",
"x: sum(x) / len(x)).collect()) print('\\n\\n') # Question 3 print('*' *",
"x[5]).count()) print('\\n\\n') # Question 6 print('*' * 30) print('\\nQuestion 6\\n')",
"* 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1] == 'United States",
"6 print('*' * 30) print('\\nQuestion 6\\n') print(df.rdd.filter(lambda v: v[5] ==",
"# Question 2 print('*' * 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v:",
"= 'fake_data.csv' df = spark.read.format('csv').option('header','true').load(path) # cast income as an",
"2 print('*' * 30) print('\\nQuestion 2\\n') print(df.rdd.filter(lambda v: v[1] ==",
"= spark.read.format('csv').option('header','true').load(path) # cast income as an integer df =",
"x: x[5]).count()) print('\\n\\n') # Question 6 print('*' * 30) print('\\nQuestion",
"cast income as an integer df = df.withColumn('Income', df['Income'].cast(IntegerType())) #",
"from pyspark.sql.types import IntegerType spark = SparkSession.builder.appName(\"Assignment4\").getOrCreate() sc = spark.sparkContext",
"x[6], x[4], x[5])).take(10)) print('\\n\\n') # Question 5 print('*' * 30)",
"print('\\n\\n') # Question 4 print('*' * 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda",
"4 print('*' * 30) print('\\nQuestion 4\\n') print(df.rdd.filter(lambda v: v[1] ==",
"print('\\n\\n') # Question 5 print('*' * 30) print('\\nQuestion 5\\n') print(df.rdd.groupBy(lambda",
"(x[1], x[0])).groupByKey().mapValues(lambda vals: len(set(vals))).sortBy(lambda a: a[1], ascending = False).take(1)) print('\\n\\n')",
"print(df.rdd.filter(lambda v: v[5] == 'Writer').filter(lambda x: x[4] < 100000).count()) print('\\n\\n')"
] |
[
"class Meta: model = get_user_model() first_name = factory.Faker('name') last_name =",
"get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name =",
"get_user_model() first_name = factory.Faker('name') last_name = factory.Faker('name') email = factory.Faker('email')",
"= get_user_model() first_name = factory.Faker('name') last_name = factory.Faker('name') email =",
"UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name = factory.Faker('name') last_name",
"Meta: model = get_user_model() first_name = factory.Faker('name') last_name = factory.Faker('name')",
"class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name = factory.Faker('name')",
"factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model",
"<reponame>zipmex/fire<gh_stars>10-100 import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class",
"import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() first_name",
"import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta:",
"from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model =",
"django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model()",
"model = get_user_model() first_name = factory.Faker('name') last_name = factory.Faker('name') email"
] |
[
"Bpm Object is stored in binary file .ojn \"\"\" _tail:",
"The O2Jam Bpm Object is stored in binary file .ojn",
"O2JHoldTail = field(init=False) def _upcastTail(self, **kwargs) -> O2JHoldTail: return O2JHoldTail(**kwargs)",
"O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta):",
"O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the O2Jam Bpm Object The O2Jam",
"Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta):",
"from reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass",
"pass @dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the O2Jam Bpm",
"field from reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta",
"import dataclass, field from reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta",
"class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the O2Jam Bpm Object The",
"from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass",
"import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold,",
"<filename>reamber/o2jam/O2JHold.py from dataclasses import dataclass, field from reamber.base.Hold import Hold,",
"Bpm Object The O2Jam Bpm Object is stored in binary",
"from dataclasses import dataclass, field from reamber.base.Hold import Hold, HoldTail",
"O2JNoteMeta): \"\"\" Defines the O2Jam Bpm Object The O2Jam Bpm",
"binary file .ojn \"\"\" _tail: O2JHoldTail = field(init=False) def _upcastTail(self,",
"reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class",
"dataclasses import dataclass, field from reamber.base.Hold import Hold, HoldTail from",
"O2Jam Bpm Object is stored in binary file .ojn \"\"\"",
"O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the O2Jam",
"file .ojn \"\"\" _tail: O2JHoldTail = field(init=False) def _upcastTail(self, **kwargs)",
"dataclass, field from reamber.base.Hold import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import",
"\"\"\" Defines the O2Jam Bpm Object The O2Jam Bpm Object",
"_tail: O2JHoldTail = field(init=False) def _upcastTail(self, **kwargs) -> O2JHoldTail: return",
"O2Jam Bpm Object The O2Jam Bpm Object is stored in",
"the O2Jam Bpm Object The O2Jam Bpm Object is stored",
"in binary file .ojn \"\"\" _tail: O2JHoldTail = field(init=False) def",
"\"\"\" _tail: O2JHoldTail = field(init=False) def _upcastTail(self, **kwargs) -> O2JHoldTail:",
"@dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the O2Jam Bpm Object",
"Object The O2Jam Bpm Object is stored in binary file",
".ojn \"\"\" _tail: O2JHoldTail = field(init=False) def _upcastTail(self, **kwargs) ->",
"class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines",
"import Hold, HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail,",
"HoldTail from reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass",
"reamber.o2jam.O2JNoteMeta import O2JNoteMeta @dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class",
"O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\" Defines the",
"stored in binary file .ojn \"\"\" _tail: O2JHoldTail = field(init=False)",
"Object is stored in binary file .ojn \"\"\" _tail: O2JHoldTail",
"is stored in binary file .ojn \"\"\" _tail: O2JHoldTail =",
"Defines the O2Jam Bpm Object The O2Jam Bpm Object is",
"@dataclass class O2JHoldTail(HoldTail, O2JNoteMeta): pass @dataclass class O2JHold(Hold, O2JNoteMeta): \"\"\""
] |
[
"seconds = await TimeConverter.convert(TimeConverter, ctx, time) return seconds async def",
"convert_time(ctx: lightbulb.Context, time: str) -> float: seconds = await TimeConverter.convert(TimeConverter,",
"def send_remainder(ctx: lightbulb.Context, text: str) -> None: await ctx.respond( f\"{ctx.author.mention}",
"from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx:",
"async def convert_time(ctx: lightbulb.Context, time: str) -> float: seconds =",
"send_remainder(ctx: lightbulb.Context, text: str) -> None: await ctx.respond( f\"{ctx.author.mention} Remainder:",
"apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context)",
"seconds async def send_remainder(ctx: lightbulb.Context, text: str) -> None: await",
"async def send_remainder(ctx: lightbulb.Context, text: str) -> None: await ctx.respond(",
"TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async def",
"return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time: str) -> float:",
"time: str) -> float: seconds = await TimeConverter.convert(TimeConverter, ctx, time)",
"-> AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time: str)",
"lightbulb from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def",
"str) -> float: seconds = await TimeConverter.convert(TimeConverter, ctx, time) return",
"AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time: str) ->",
"from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return",
"ctx, time) return seconds async def send_remainder(ctx: lightbulb.Context, text: str)",
"lightbulb.Context, time: str) -> float: seconds = await TimeConverter.convert(TimeConverter, ctx,",
"fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context,",
"AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler:",
"return seconds async def send_remainder(ctx: lightbulb.Context, text: str) -> None:",
"ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time: str) -> float: seconds",
"str) -> None: await ctx.respond( f\"{ctx.author.mention} Remainder: `{text}`\", user_mentions=True, )",
"= await TimeConverter.convert(TimeConverter, ctx, time) return seconds async def send_remainder(ctx:",
"-> float: seconds = await TimeConverter.convert(TimeConverter, ctx, time) return seconds",
"import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async",
"import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) ->",
"lightbulb.Context, text: str) -> None: await ctx.respond( f\"{ctx.author.mention} Remainder: `{text}`\",",
"def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx:",
"def convert_time(ctx: lightbulb.Context, time: str) -> float: seconds = await",
"float: seconds = await TimeConverter.convert(TimeConverter, ctx, time) return seconds async",
"import lightbulb from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter",
"await TimeConverter.convert(TimeConverter, ctx, time) return seconds async def send_remainder(ctx: lightbulb.Context,",
"time) return seconds async def send_remainder(ctx: lightbulb.Context, text: str) ->",
"lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler async def convert_time(ctx: lightbulb.Context, time:",
"TimeConverter.convert(TimeConverter, ctx, time) return seconds async def send_remainder(ctx: lightbulb.Context, text:",
"peacebot.core.utils.time import TimeConverter def fetch_scheduler(ctx: lightbulb.Context) -> AsyncIOScheduler: return ctx.bot.d.scheduler",
"text: str) -> None: await ctx.respond( f\"{ctx.author.mention} Remainder: `{text}`\", user_mentions=True,",
"<filename>peacebot/core/plugins/Miscellaneous/__init__.py<gh_stars>1-10 import lightbulb from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import"
] |
[
"} self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self):",
"test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if __name__ == '__main__': suite",
"'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self):",
"browser does not exist for android >= 6.0 desired_caps =",
"exist for android >= 6.0 desired_caps = { 'platformName': 'Android',",
"self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if __name__ == '__main__': suite =",
"def setUp(self): # Default browser does not exist for android",
"appium import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser",
"'Android', 'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0'",
"# Default browser does not exist for android >= 6.0",
"'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver",
"'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',",
"desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if __name__ ==",
"webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser does not",
"'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd':",
"not exist for android >= 6.0 desired_caps = { 'platformName':",
"Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver =",
"= { 'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity':",
"def tearDown(self): self.driver.quit() if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(MSiteDefaultBrowserAndroidUITests)",
"desired_caps = { 'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser',",
"'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def",
"= webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if",
"setUp(self): # Default browser does not exist for android >=",
"for android >= 6.0 desired_caps = { 'platformName': 'Android', 'deviceName':",
"{ 'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity',",
"self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit()",
">= 6.0 desired_caps = { 'platformName': 'Android', 'deviceName': 'Android Emulator',",
"'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def",
"'deviceName': 'Android Emulator', 'appPackage': 'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' }",
"unittest from appium import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): #",
"webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if __name__",
"android >= 6.0 desired_caps = { 'platformName': 'Android', 'deviceName': 'Android",
"def test_open_url(self): self.driver.get('http://targeturl.com') def tearDown(self): self.driver.quit() if __name__ == '__main__':",
"6.0 desired_caps = { 'platformName': 'Android', 'deviceName': 'Android Emulator', 'appPackage':",
"tearDown(self): self.driver.quit() if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(MSiteDefaultBrowserAndroidUITests) unittest.TextTestRunner(verbosity=2).run(suite)",
"MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser does not exist for",
"class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser does not exist",
"does not exist for android >= 6.0 desired_caps = {",
"import unittest from appium import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self):",
"Default browser does not exist for android >= 6.0 desired_caps",
"from appium import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default",
"import webdriver class MSiteDefaultBrowserAndroidUITests(unittest.TestCase): def setUp(self): # Default browser does",
"'com.android.browser', 'appActivity': 'com.android.browser.BrowserActivity', 'avd': 'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)",
"'avd': 'samsung_galaxy_s6_6.0' } self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) def test_open_url(self): self.driver.get('http://targeturl.com')"
] |
[
"<class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them to --> ndarray,",
"\"\"\" import re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str)",
"look something like --> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change",
"something like --> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them",
"import re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str) ->",
"during runtime usually look something like --> <class 'numpy.ndarray'> or",
")|_|(type)') def process_types(tp: str) -> str: cleaned_type = remove_chars.sub('', tp)",
"--> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them to -->",
"= re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str) -> str: cleaned_type =",
"extracted during runtime usually look something like --> <class 'numpy.ndarray'>",
"ColorPalette \"\"\" import re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp:",
"str) -> str: cleaned_type = remove_chars.sub('', tp) cleaned_type = cleaned_type.split('.')[-1].strip()",
"re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str) -> str:",
"<class 'seaborn.palettes._ColorPalette'> change them to --> ndarray, ColorPalette \"\"\" import",
"The types extracted during runtime usually look something like -->",
"-> str: cleaned_type = remove_chars.sub('', tp) cleaned_type = cleaned_type.split('.')[-1].strip() return",
"usually look something like --> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'>",
"like --> <class 'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them to",
"change them to --> ndarray, ColorPalette \"\"\" import re remove_chars",
"ndarray, ColorPalette \"\"\" import re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def",
"them to --> ndarray, ColorPalette \"\"\" import re remove_chars =",
"'seaborn.palettes._ColorPalette'> change them to --> ndarray, ColorPalette \"\"\" import re",
"'numpy.ndarray'> or <class 'seaborn.palettes._ColorPalette'> change them to --> ndarray, ColorPalette",
"process_types(tp: str) -> str: cleaned_type = remove_chars.sub('', tp) cleaned_type =",
"remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str) -> str: cleaned_type",
"def process_types(tp: str) -> str: cleaned_type = remove_chars.sub('', tp) cleaned_type",
"types extracted during runtime usually look something like --> <class",
"--> ndarray, ColorPalette \"\"\" import re remove_chars = re.compile(r'>|\\'|<|(class )|_|(type)')",
"runtime usually look something like --> <class 'numpy.ndarray'> or <class",
"<gh_stars>0 \"\"\" Created on 17-June-2020 @author <NAME> The types extracted",
"str: cleaned_type = remove_chars.sub('', tp) cleaned_type = cleaned_type.split('.')[-1].strip() return cleaned_type",
"Created on 17-June-2020 @author <NAME> The types extracted during runtime",
"@author <NAME> The types extracted during runtime usually look something",
"on 17-June-2020 @author <NAME> The types extracted during runtime usually",
"re.compile(r'>|\\'|<|(class )|_|(type)') def process_types(tp: str) -> str: cleaned_type = remove_chars.sub('',",
"17-June-2020 @author <NAME> The types extracted during runtime usually look",
"to --> ndarray, ColorPalette \"\"\" import re remove_chars = re.compile(r'>|\\'|<|(class",
"<NAME> The types extracted during runtime usually look something like",
"\"\"\" Created on 17-June-2020 @author <NAME> The types extracted during",
"or <class 'seaborn.palettes._ColorPalette'> change them to --> ndarray, ColorPalette \"\"\""
] |
[
"5, dpi = 100): self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self,",
"dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self,",
"matplotlib import pyplot as plt from matplotlib.figure import Figure from",
"theta_major_name.append(float(k)/ 180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta)))",
"= self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas): def",
"= (width, height), dpi = dpi, frameon = False) fig.subplots_adjust(bottom=0,",
"import * from PyQt5.QtWidgets import * from matplotlib import pyplot",
"in histogram.values.keys(): if i % 3 == 0: theta_major_name.append(float(k)/ 180",
"numpy as np import random, matplotlib.pyplot as plt class PlotCanvas(FigureCanvas):",
"PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import",
"from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas",
"'r-') ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas): def __init__(self, parent =",
"cmap = \"gray\") self.show() class HistogramCanvas(FigureCanvas): ''' This class is",
"= self.fig.add_subplot(111, projection='polar') else : self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO",
"in the main module. the values are computed in one",
"range(25)] ax = self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example') class",
"(fname - extention ?) FigureCanvas.updateGeometry(self) def plot(self, histogram, color =",
"QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self): data = [random.random() for",
"FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off') display = image.image display[display ==",
"data = [random.random() for i in range(25)] ax = self.figure.add_subplot(111)",
"= False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes",
"if image.color: self.axes.imshow(image.image) else : self.axes.imshow(display, cmap = \"gray\") self.show()",
"True, which='major', linestyle='-') self.axes.grid(b = True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values()))",
"image.image display[display == 1] = 255 if image.color: self.axes.imshow(image.image) else",
"for k in histogram.values.keys(): if i % 3 == 0:",
"import pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg",
"self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw() def clear(self):",
"height), dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,",
"class is used to plt the histogram of the two",
"from PyQt5.QtWidgets import * from matplotlib import pyplot as plt",
"= Figure(figsize = (width, height), dpi = dpi, frameon =",
"len(theta) > 16: i = 0 theta_major_name = [] for",
"top=1, left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self,",
"def plot(self, histogram, color = None): self.axes.set_title(\"Spatial relations between A",
"if len(theta) > 16: i = 0 theta_major_name = []",
"self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self)",
"dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)",
"def plot(self, image): self.axes.axis('off') display = image.image display[display == 1]",
"is used to plt the histogram of the two objects",
"0 theta_major_name = [] for k in histogram.values.keys(): if i",
"ticker import numpy as np import random, matplotlib.pyplot as plt",
"plot(self): data = [random.random() for i in range(25)] ax =",
"code if len(theta) > 16: i = 0 theta_major_name =",
"image.color: self.axes.imshow(image.image) else : self.axes.imshow(display, cmap = \"gray\") self.show() class",
"extention ?) FigureCanvas.updateGeometry(self) def plot(self, histogram, color = None): self.axes.set_title(\"Spatial",
"ax = self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas):",
"QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off') display = image.image display[display",
"the histogram to be polar or linear. ''' self.is_polar =",
"to be polar or linear. ''' self.is_polar = new_value self.fig.clear()",
"= [] for k in histogram.values.keys(): if i % 3",
"= [random.random() for i in range(25)] ax = self.figure.add_subplot(111) ax.plot(data,",
"projection='polar') else : self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add",
"i % 3 == 0: theta_major_name.append(float(k)/ 180 * np.pi) i+=1",
"linestyle='-') self.axes.grid(b = True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()),",
"type of the histogram to be polar or linear. '''",
"<filename>src/canvas.py<gh_stars>1-10 from PyQt5.QtGui import * from PyQt5.QtCore import * from",
"from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets",
"#TODO : Add the names of the objects (fname -",
"B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/ 180 *",
"self.setParent(parent) if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes",
"or linear. ''' self.is_polar = new_value self.fig.clear() if self.is_polar: self.axes",
"= new_value self.fig.clear() if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else",
"theta = [float(k)/ 180 * np.pi for k in histogram.values.keys()]",
"180 * np.pi for k in histogram.values.keys()] #TODO : refractor",
"new_value : bool): ''' set the type of the histogram",
"va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/ 180 * np.pi",
"dpi = dpi, frameon = False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1)",
"= 8, height = 5, dpi = 100): self.fig =",
"bool): ''' set the type of the histogram to be",
"class ImageCanvas(FigureCanvas): def __init__(self, parent = None, width = 5,",
"height = 4, dpi=100): fig = Figure(figsize = (width, height),",
"fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self): data",
"self.fig.add_subplot(111, projection='polar') else : self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO :",
"QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self): data = [random.random() for i",
"i = 0 theta_major_name = [] for k in histogram.values.keys():",
"import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as ticker import numpy",
"parent = None, width = 5, height = 4, dpi=100):",
"None, is_polar = True, width = 8, height = 5,",
"\"gray\") self.show() class HistogramCanvas(FigureCanvas): ''' This class is used to",
"refractor this ugly-but-working code if len(theta) > 16: i =",
"clear(self): self.axes.clear() def lin_or_polar(self, new_value : bool): ''' set the",
"= \"gray\") self.show() class HistogramCanvas(FigureCanvas): ''' This class is used",
"= is_polar self.setParent(parent) if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else",
"''' set the type of the histogram to be polar",
"0: theta_major_name.append(float(k)/ 180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta)))",
"as FigureCanvas import matplotlib.ticker as ticker import numpy as np",
"width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes =",
"[random.random() for i in range(25)] ax = self.figure.add_subplot(111) ax.plot(data, 'r-')",
"the values are computed in one of the descriptors. '''",
"= self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add the names of the",
"== 0: theta_major_name.append(float(k)/ 180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else :",
"color = None): self.axes.set_title(\"Spatial relations between A and B\", va='bottom')",
"color=\"red\", ls='--') self.draw() def clear(self): self.axes.clear() def lin_or_polar(self, new_value :",
"= fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot()",
"import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker",
"which='major', linestyle='-') self.axes.grid(b = True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else:",
"height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar self.setParent(parent) if self.is_polar:",
"[float(k)/ 180 * np.pi for k in histogram.values.keys()] #TODO :",
"def lin_or_polar(self, new_value : bool): ''' set the type of",
"self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes = self.fig.add_subplot(111)",
"from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as ticker",
"self.axes.imshow(image.image) else : self.axes.imshow(display, cmap = \"gray\") self.show() class HistogramCanvas(FigureCanvas):",
"5, height = 4, dpi=100): fig = Figure(figsize = (width,",
"matplotlib.pyplot as plt class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4,",
"else : self.axes.imshow(display, cmap = \"gray\") self.show() class HistogramCanvas(FigureCanvas): '''",
"main module. the values are computed in one of the",
"?) FigureCanvas.updateGeometry(self) def plot(self, histogram, color = None): self.axes.set_title(\"Spatial relations",
": bool): ''' set the type of the histogram to",
"are computed in one of the descriptors. ''' def __init__(self,",
"random, matplotlib.pyplot as plt class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5,",
"__init__(self, parent = None, is_polar = True, width = 8,",
"FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self):",
"from matplotlib import pyplot as plt from matplotlib.figure import Figure",
"= Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent)",
"np import random, matplotlib.pyplot as plt class PlotCanvas(FigureCanvas): def __init__(self,",
"plot(self, histogram, color = None): self.axes.set_title(\"Spatial relations between A and",
"None, width = 5, height = 4, dpi=100): fig =",
"for i in range(25)] ax = self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt",
"in one of the descriptors. ''' def __init__(self, parent =",
"new_value self.fig.clear() if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else :",
"import * from PyQt5.QtCore import * from PyQt5.QtWidgets import *",
"self.axes.grid(b = True, which='major', linestyle='-') self.axes.grid(b = True, which='minor', linestyle='--')",
"__init__(self, parent = None, width = 5, height = 4,",
"objects (fname - extention ?) FigureCanvas.updateGeometry(self) def plot(self, histogram, color",
"in range(25)] ax = self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example')",
"import matplotlib.ticker as ticker import numpy as np import random,",
"True, width = 8, height = 5, dpi = 100):",
"plt the histogram of the two objects in the main",
"left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,",
"= True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) #",
"= image.image display[display == 1] = 255 if image.color: self.axes.imshow(image.image)",
"of the descriptors. ''' def __init__(self, parent = None, is_polar",
"* from matplotlib import pyplot as plt from matplotlib.figure import",
"self.fig) self.is_polar = is_polar self.setParent(parent) if self.is_polar: self.axes = self.fig.add_subplot(111,",
": self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major', linestyle='-') self.axes.grid(b =",
"self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar",
"FigureCanvas.updateGeometry(self) self.plot() def plot(self): data = [random.random() for i in",
"plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as",
"pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import",
"True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()),",
"Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as",
"self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major', linestyle='-') self.axes.grid(b = True,",
"list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw() def clear(self): self.axes.clear()",
"self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/ 180 * np.pi for k",
"> 16: i = 0 theta_major_name = [] for k",
"used to plt the histogram of the two objects in",
"of the histogram to be polar or linear. ''' self.is_polar",
"parent = None, is_polar = True, width = 8, height",
"self.axes.grid(b = True, which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values()))",
"self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas): def __init__(self,",
"is_polar self.setParent(parent) if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else :",
"def clear(self): self.axes.clear() def lin_or_polar(self, new_value : bool): ''' set",
"the two objects in the main module. the values are",
"[] for k in histogram.values.keys(): if i % 3 ==",
"descriptors. ''' def __init__(self, parent = None, is_polar = True,",
"self.axes.set_title(\"Spatial relations between A and B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1)",
"dpi, frameon = False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self, fig)",
"list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw()",
"False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes =",
"FigureCanvas.updateGeometry(self) def plot(self, histogram, color = None): self.axes.set_title(\"Spatial relations between",
"is_polar = True, width = 8, height = 5, dpi",
"* np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b =",
"ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas): def __init__(self, parent = None,",
"QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off') display = image.image",
"of the objects (fname - extention ?) FigureCanvas.updateGeometry(self) def plot(self,",
"image): self.axes.axis('off') display = image.image display[display == 1] = 255",
"set the type of the histogram to be polar or",
"FigureCanvas import matplotlib.ticker as ticker import numpy as np import",
"in histogram.values.keys()] #TODO : refractor this ugly-but-working code if len(theta)",
"= None, width = 5, height = 4, dpi=100): fig",
"lin_or_polar(self, new_value : bool): ''' set the type of the",
"two objects in the main module. the values are computed",
"to plt the histogram of the two objects in the",
"parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes",
"from PyQt5.QtCore import * from PyQt5.QtWidgets import * from matplotlib",
"the descriptors. ''' def __init__(self, parent = None, is_polar =",
"height = 5, dpi = 100): self.fig = Figure(figsize=(width, height),",
"dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar self.setParent(parent) if self.is_polar: self.axes",
"if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes =",
"= 0 theta_major_name = [] for k in histogram.values.keys(): if",
"i in range(25)] ax = self.figure.add_subplot(111) ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib",
"self.axes.grid(True) #TODO : Add the names of the objects (fname",
"display[display == 1] = 255 if image.color: self.axes.imshow(image.image) else :",
"None): self.axes.set_title(\"Spatial relations between A and B\", va='bottom') if self.is_polar:",
"this ugly-but-working code if len(theta) > 16: i = 0",
"self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--')",
"def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height),",
"1] = 255 if image.color: self.axes.imshow(image.image) else : self.axes.imshow(display, cmap",
"height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111)",
"8, height = 5, dpi = 100): self.fig = Figure(figsize=(width,",
"k in histogram.values.keys(): if i % 3 == 0: theta_major_name.append(float(k)/",
"linear. ''' self.is_polar = new_value self.fig.clear() if self.is_polar: self.axes =",
"Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self,",
"which='minor', linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian),",
"255 if image.color: self.axes.imshow(image.image) else : self.axes.imshow(display, cmap = \"gray\")",
"* np.pi for k in histogram.values.keys()] #TODO : refractor this",
"self.plot() def plot(self): data = [random.random() for i in range(25)]",
"FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self)",
"self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw() def clear(self): self.axes.clear() def lin_or_polar(self,",
"the names of the objects (fname - extention ?) FigureCanvas.updateGeometry(self)",
"''' This class is used to plt the histogram of",
"self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self,",
"self.draw() def clear(self): self.axes.clear() def lin_or_polar(self, new_value : bool): '''",
"== 1] = 255 if image.color: self.axes.imshow(image.image) else : self.axes.imshow(display,",
"PyQt5.QtWidgets import * from matplotlib import pyplot as plt from",
"self.fig.clear() if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes",
": refractor this ugly-but-working code if len(theta) > 16: i",
"import numpy as np import random, matplotlib.pyplot as plt class",
"self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add the names of the objects",
"fig) self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def",
"if self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/ 180 * np.pi for",
"def __init__(self, parent = None, width = 5, height =",
"self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major', linestyle='-') self.axes.grid(b = True, which='minor',",
"fig.add_subplot(111) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def",
"k in histogram.values.keys()] #TODO : refractor this ugly-but-working code if",
"__init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi)",
"ax.plot(data, 'r-') ax.set_title('PyQt Matplotlib Example') class ImageCanvas(FigureCanvas): def __init__(self, parent",
"= None): self.axes.set_title(\"Spatial relations between A and B\", va='bottom') if",
"fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) FigureCanvas.__init__(self, fig)",
"computed in one of the descriptors. ''' def __init__(self, parent",
"fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes = fig.add_subplot(111)",
"import * from matplotlib import pyplot as plt from matplotlib.figure",
"Add the names of the objects (fname - extention ?)",
"width = 5, height = 4, dpi=100): fig = Figure(figsize",
"class HistogramCanvas(FigureCanvas): ''' This class is used to plt the",
"= 5, dpi = 100): self.fig = Figure(figsize=(width, height), dpi=dpi)",
"self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image):",
"self.axes.imshow(display, cmap = \"gray\") self.show() class HistogramCanvas(FigureCanvas): ''' This class",
"class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig =",
"HistogramCanvas(FigureCanvas): ''' This class is used to plt the histogram",
"ImageCanvas(FigureCanvas): def __init__(self, parent = None, width = 5, height",
"values are computed in one of the descriptors. ''' def",
"as np import random, matplotlib.pyplot as plt class PlotCanvas(FigureCanvas): def",
"self.is_polar = is_polar self.setParent(parent) if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar')",
"ugly-but-working code if len(theta) > 16: i = 0 theta_major_name",
"= None, is_polar = True, width = 8, height =",
"linestyle='--') self.axes.plot(theta, list(histogram.values.values())) else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\",",
"A and B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/",
"= True, width = 8, height = 5, dpi =",
"self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self): data =",
"100): self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar =",
"theta_major_name = [] for k in histogram.values.keys(): if i %",
"= 100): self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar",
"matplotlib.ticker as ticker import numpy as np import random, matplotlib.pyplot",
"self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes = self.fig.add_subplot(111) self.axes.grid(True)",
"fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off') display",
"Matplotlib Example') class ImageCanvas(FigureCanvas): def __init__(self, parent = None, width",
"Example') class ImageCanvas(FigureCanvas): def __init__(self, parent = None, width =",
"= [float(k)/ 180 * np.pi for k in histogram.values.keys()] #TODO",
"Figure(figsize = (width, height), dpi = dpi, frameon = False)",
"FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot() def plot(self): data = [random.random()",
"plot(self, image): self.axes.axis('off') display = image.image display[display == 1] =",
"= 4, dpi=100): fig = Figure(figsize = (width, height), dpi",
"and B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta = [float(k)/ 180",
"module. the values are computed in one of the descriptors.",
"self.show() class HistogramCanvas(FigureCanvas): ''' This class is used to plt",
"self.axes = self.fig.add_subplot(111, projection='polar') else : self.axes = self.fig.add_subplot(111) FigureCanvas.updateGeometry(self)",
"3 == 0: theta_major_name.append(float(k)/ 180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else",
": Add the names of the objects (fname - extention",
"FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as ticker import numpy as",
"def __init__(self, parent = None, is_polar = True, width =",
"self.axes.axis('off') display = image.image display[display == 1] = 255 if",
"polar or linear. ''' self.is_polar = new_value self.fig.clear() if self.is_polar:",
"def plot(self): data = [random.random() for i in range(25)] ax",
"= True, which='major', linestyle='-') self.axes.grid(b = True, which='minor', linestyle='--') self.axes.plot(theta,",
"histogram, color = None): self.axes.set_title(\"Spatial relations between A and B\",",
"This class is used to plt the histogram of the",
"Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar self.setParent(parent) if",
"list(histogram.gaussian), color=\"red\", ls='--') self.draw() def clear(self): self.axes.clear() def lin_or_polar(self, new_value",
"be polar or linear. ''' self.is_polar = new_value self.fig.clear() if",
"16: i = 0 theta_major_name = [] for k in",
"self.is_polar = new_value self.fig.clear() if self.is_polar: self.axes = self.fig.add_subplot(111, projection='polar')",
"right=1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.axes = fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)",
": self.axes.imshow(display, cmap = \"gray\") self.show() class HistogramCanvas(FigureCanvas): ''' This",
"frameon = False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self, fig) self.setParent(parent)",
"for k in histogram.values.keys()] #TODO : refractor this ugly-but-working code",
"% 3 == 0: theta_major_name.append(float(k)/ 180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name))",
"i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major',",
"self.axes.set_rlim(0,1) theta = [float(k)/ 180 * np.pi for k in",
"= 5, height = 4, dpi=100): fig = Figure(figsize =",
"as ticker import numpy as np import random, matplotlib.pyplot as",
"names of the objects (fname - extention ?) FigureCanvas.updateGeometry(self) def",
"relations between A and B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta",
"fig = Figure(figsize = (width, height), dpi = dpi, frameon",
"#TODO : refractor this ugly-but-working code if len(theta) > 16:",
"else: self.axes.plot(list(histogram.values.keys()), list(histogram.values.values())) # self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw() def",
"objects in the main module. the values are computed in",
"else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major', linestyle='-') self.axes.grid(b",
"self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True, which='major', linestyle='-')",
"= Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar self.setParent(parent)",
"= 255 if image.color: self.axes.imshow(image.image) else : self.axes.imshow(display, cmap =",
"the type of the histogram to be polar or linear.",
"histogram to be polar or linear. ''' self.is_polar = new_value",
"histogram.values.keys(): if i % 3 == 0: theta_major_name.append(float(k)/ 180 *",
"ls='--') self.draw() def clear(self): self.axes.clear() def lin_or_polar(self, new_value : bool):",
"matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import",
"np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b = True,",
"PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width,",
"between A and B\", va='bottom') if self.is_polar: self.axes.set_rlim(0,1) theta =",
"''' self.is_polar = new_value self.fig.clear() if self.is_polar: self.axes = self.fig.add_subplot(111,",
"the objects (fname - extention ?) FigureCanvas.updateGeometry(self) def plot(self, histogram,",
"plt class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig",
"of the two objects in the main module. the values",
"= dpi, frameon = False) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) FigureCanvas.__init__(self,",
"= fig.add_subplot(111) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off')",
"as plt class PlotCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100):",
"the histogram of the two objects in the main module.",
"width = 8, height = 5, dpi = 100): self.fig",
"histogram of the two objects in the main module. the",
"* from PyQt5.QtWidgets import * from matplotlib import pyplot as",
"180 * np.pi) i+=1 self.axes.xaxis.set_major_locator(ticker.FixedLocator(theta_major_name)) else : self.axes.xaxis.set_major_locator(ticker.LinearLocator(len(theta))) self.axes.xaxis.set_minor_locator(ticker.LinearLocator(len(theta))) self.axes.grid(b",
": self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add the names",
"else : self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add the",
"dpi = 100): self.fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.fig)",
"* from PyQt5.QtCore import * from PyQt5.QtWidgets import * from",
"height), dpi = dpi, frameon = False) fig.subplots_adjust(bottom=0, top=1, left=0,",
"PyQt5.QtCore import * from PyQt5.QtWidgets import * from matplotlib import",
"4, dpi=100): fig = Figure(figsize = (width, height), dpi =",
"matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.ticker as ticker import",
"# self.axes.plot(list(histogram.values.keys()), list(histogram.gaussian), color=\"red\", ls='--') self.draw() def clear(self): self.axes.clear() def",
"as plt from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg",
"import random, matplotlib.pyplot as plt class PlotCanvas(FigureCanvas): def __init__(self, parent=None,",
"self.axes = self.fig.add_subplot(111) self.axes.grid(True) #TODO : Add the names of",
"the main module. the values are computed in one of",
"if i % 3 == 0: theta_major_name.append(float(k)/ 180 * np.pi)",
"display = image.image display[display == 1] = 255 if image.color:",
"FigureCanvas.__init__(self, self.fig) self.is_polar = is_polar self.setParent(parent) if self.is_polar: self.axes =",
"histogram.values.keys()] #TODO : refractor this ugly-but-working code if len(theta) >",
"one of the descriptors. ''' def __init__(self, parent = None,",
"(width, height), dpi = dpi, frameon = False) fig.subplots_adjust(bottom=0, top=1,",
"''' def __init__(self, parent = None, is_polar = True, width",
"np.pi for k in histogram.values.keys()] #TODO : refractor this ugly-but-working",
"FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def plot(self, image): self.axes.axis('off') display =",
"dpi=100): fig = Figure(figsize = (width, height), dpi = dpi,",
"self.axes.clear() def lin_or_polar(self, new_value : bool): ''' set the type",
"- extention ?) FigureCanvas.updateGeometry(self) def plot(self, histogram, color = None):"
] |
[
"LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) -> None: '''Flash LEDs three times.'''",
"time def funcTest(timestamps: bool = False) -> None: cpg =",
"too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The normal behavior is",
"| {:7.2f} |' else: outHeading = '| count | temp",
"print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps) -> None: if timestamps: outHeading",
"{!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or right button...') print(outHeading) _printCountdown(3)",
"print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg)",
"| {:12.3f} | {:7.2f} | {:7.2f} | {:7.2f} |' testFunction",
"else: outHeading = '| count | light |' outFormat =",
"-> None: for i in range(start, 0, -1): print(i, end=\"",
"result = (count-i, *cpg.buttonAny_wts()) if timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result))",
"= timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average",
"any button |' outFormat = '| {:5} | {!s:10} |'",
"print(f'Testing Response-Wait-Time with {iterations} iterations ...') for i in range(iterations):",
"= cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...') print(outHeading) _printCountdown(3) count",
"timestamps: outHeading = '| count | timestamp | x m/s^2",
"'| count | temp °C |' outFormat = '| {:5}",
"= '| {0:5} | {1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch",
"m/s^2 |' outFormat = '| {:5} | {:7.2f} | {:7.2f}",
"'| {:5} | {:12.3f} | {!s:10} |' else: outHeading =",
"{:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or right button...')",
"is a response, resulting in an exception. # This is",
"range(10): # print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) value",
"def test_temp(cpg, timestamps) -> None: if timestamps: outHeading = '|",
"chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run a short chasing",
"= '| count | timestamp | light |' outFormat =",
"# This is what we expected. Therefore, just continue. pass",
"acc measurement values, but do not expect any response, even",
"funcTest(timestamps: bool = False) -> None: cpg = CircuitPlayground() if",
"| any button |' outFormat = '| {:5} | {!s:10}",
"| switch |' outFormat = '| {:5} | {!s:6} |'",
"LEDs...') test_ledDemo(cpg) value=1 # print('| val | LEDs |') for",
"per measurement.') def testLightSpeed(cpg, iterations: int = 100) -> None:",
"30 for i in range(count): result = (count-i, *cpg.touch_wts()) if",
"outHeading = '| count | switch |' outFormat = '|",
"value=1 # print('| val | LEDs |') for i in",
"def test_touch(cpg, timestamps) -> None: if timestamps: outHeading = '|",
"count | timestamp | switch |' outFormat = '| {:5}",
"FUNCTIONAL-TESTS WITH THE CPG with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING",
"CircuitPlaygroundVersion import time def funcTest(timestamps: bool = False) -> None:",
"import CircuitPlayground from .. import __version__ as CircuitPlaygroundVersion import time",
"| {:7.2f} | {:7.2f} | {:7.2f} |' testFunction = cpg.acc_wts",
"*cpg.buttonAny_wts()) if timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg,",
"test_acc(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"outHeading = '| count | temp °C |' outFormat =",
"|' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count = 20 for i",
"|' outFormat = '| {0:5} | {1:5} | {1:08b} |'",
"i in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps) ->",
"-> None: '''Flash LEDs and run a short chasing light.'''",
"count | light |' outFormat = '| {:5} | {:5}",
"cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps) -> None: if timestamps:",
"test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine()",
"outHeading = '| count | timestamp | temp °C |'",
"| light |' outFormat = '| {:5} | {:12.3f} |",
"| timestamp | x m/s^2 | y m/s^2 | z",
"= '| {:5} | {:12.3f} | {:7.2f} |' else: outHeading",
"the wait time for additional, unexpected responses is long enough.'''",
"with {iterations} iterations ...') for i in range(iterations): if i%100==0:",
"= 60 for i in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def",
"binary |' outFormat = '| {0:5} | {1:5} | {1:08b}",
"_printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run a short chasing light...') print('flashing",
"count = 30 for i in range(count): result = (count-i,",
"iterations: int = 10000) -> None: '''Test it the wait",
"outFormat = '| {0:5} | {1:12.3f} | {2:5} | {2:08b}",
"test_ledDemo(cpg) value=1 # print('| val | LEDs |') for i",
"timestamps: outHeading = '| count | timestamp | temp °C",
"If we are still here, we did not get a",
"print(outHeading) _printCountdown(3) count = 60 for i in range(count): print(outFormat.format(count-i,",
"iterations. Please wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.acc(),",
"(count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) -> None: '''Flash LEDs",
"= '| {:5} | {:12.3f} | {:5} |' else: outHeading",
"...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG without",
"None: '''Measure how long it takes to do a light",
"-> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading) def",
"if timestamps else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps)",
"Exception: # The normal behavior is a response, resulting in",
"an exception. # This is what we expected. Therefore, just",
"(count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps) -> None: if",
"the right # print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2)",
"outHeading = '| count | timestamp | light |' outFormat",
"cpg.wait(0.5) def test_acc(cpg, timestamps) -> None: if timestamps: outHeading =",
"'| {:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or right",
"cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps) -> None: if timestamps:",
"else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps) -> None:",
"outHeading = '| count | light |' outFormat = '|",
"board...') print(outHeading) _printCountdown(3) count = 60 for i in range(count):",
"-> None: cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME",
"(count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps) -> None: if",
"is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response was too late.')",
"touch | binary |' outFormat = '| {0:5} | {1:5}",
"pads...') print(outHeading) _printCountdown(3) count = 30 for i in range(count):",
"{:12.3f} | {:7.2f} | {:7.2f} | {:7.2f} |' testFunction =",
"= '| count | any button |' outFormat = '|",
"run a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run",
"print('| val | LEDs |') for i in range(10): #",
"cpg._query('MEAS:ACC?', 0) # If we are still here, we did",
"-> None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps) -> None: if",
"= (count-i, *cpg.temp_wts()) if timestamps else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5)",
"print('', flush=True) def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) ->",
"|' outFormat = '| {:5} | {:12.3f} | {:5} |'",
"| {:7.2f} | {:7.2f} |' testFunction = cpg.acc_wts else: outHeading",
"timestamps: outHeading = '| count | timestamp | touch |",
"= '| {:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3)",
"| {!s:10} |' else: outHeading = '| count | any",
"shift 1 bit to the left for i in range(10):",
"if the CPG will send one. cpg._query('MEAS:ACC?', 0) # If",
"how long it takes to do a light sensor measurement.'''",
"'| count | timestamp | any button |' outFormat =",
"if timestamps: outHeading = '| count | timestamp | x",
"we are still here, we did not get a response.",
"(count-i, *cpg.touch_wts()) if timestamps else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def",
"|' outFormat = '| {:5} | {:12.3f} | {!s:6} |'",
"_printCountdown(start: int = 3) -> None: for i in range(start,",
"| {2:08b} |' else: outHeading = '| count | touch",
"switch |' outFormat = '| {:5} | {:12.3f} | {!s:6}",
"range(count): result = (count-i, *cpg.touch_wts()) if timestamps else (count-i, cpg.touch())",
"test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH",
"|' outFormat = '| {0:5} | {1:12.3f} | {2:5} |",
"(count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps) -> None: if",
"did not get a response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR",
"WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int = 3) -> None:",
"in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps) -> None:",
"0) # If we are still here, we did not",
"do not expect any response, even if the CPG will",
"is long enough.''' print(f'Testing Response-Wait-Time with {iterations} iterations ...') for",
"|' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or right button...') print(outHeading) _printCountdown(3) count",
"Press left or right button...') print(outHeading) _printCountdown(3) count = 10",
"we did not get a response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')",
"z m/s^2 |' outFormat = '| {:5} | {:7.2f} |",
"{result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def _testResponseWaitTime(cpg,",
"print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) -> None: '''Flash LEDs and run",
"cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...') print(outHeading) _printCountdown(3) count =",
"| {1:12.3f} | {2:5} | {2:08b} |' else: outHeading =",
"outHeading = '| count | timestamp | any button |'",
"| {:12.3f} | {:7.2f} |' else: outHeading = '| count",
"| timestamp | light |' outFormat = '| {:5} |",
"cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms",
"wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total",
"without timestamps ...\\n') # test_led(cpg) # test_buttonAny(cpg, timestamps) # test_switch(cpg,",
"None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg,",
"{value:010b} |') cpg.led(value) cpg.wait(0.2) value <<= 1 # shift 1",
"_testResponseWaitTime(cpg, iterations: int = 10000) -> None: '''Test it the",
"None: for i in range(start, 0, -1): print(i, end=\" \",",
"light sensor measurement.''' print(f'Testing light measurement speed with {iterations} iterations.",
"range(count): result = (count-i, *cpg.temp_wts()) if timestamps else (count-i, cpg.temp())",
"outFormat = '| {:5} | {:12.3f} | {!s:10} |' else:",
"# print('| val | LEDs |') for i in range(10):",
"# test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg,",
"for i in range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations: int",
"# The normal behavior is a response, resulting in an",
"= (count-i, *cpg.touch_wts()) if timestamps else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5)",
"def test_buttonAny(cpg, timestamps) -> None: if timestamps: outHeading = '|",
".. import __version__ as CircuitPlaygroundVersion import time def funcTest(timestamps: bool",
"print(outHeading) _printCountdown(3) count = 10 for i in range(count): result",
"10 for i in range(count): result = (count-i, *cpg.buttonAny_wts()) if",
"10 for i in range(count): result = (count-i, *cpg.switch_wts()) if",
"was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The normal behavior",
"timestamps ...\\n') # test_led(cpg) # test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps)",
"= '| count | temp °C |' outFormat = '|",
"print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def _testResponseWaitTime(cpg, iterations: int",
"not expect any response, even if the CPG will send",
"for i in range(start, 0, -1): print(i, end=\" \", flush=True)",
"|' else: outHeading = '| count | switch |' outFormat",
"0, -1): print(i, end=\" \", flush=True) time.sleep(1) print('', flush=True) def",
"long enough.''' print(f'Testing Response-Wait-Time with {iterations} iterations ...') for i",
"capacitive sensor pads...') print(outHeading) _printCountdown(3) count = 30 for i",
"left or right button...') print(outHeading) _printCountdown(3) count = 10 for",
"result = (count-i, *cpg.temp_wts()) if timestamps else (count-i, cpg.temp()) print(outFormat.format(*result))",
"'| {:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light",
"| {:7.2f} |' testFunction = cpg.acc_wts else: outHeading = '|",
"position...') print(outHeading) _printCountdown(3) count = 10 for i in range(count):",
"{!s:6} |' else: outHeading = '| count | switch |'",
"else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps) -> None:",
"m/s^2 | y m/s^2 | z m/s^2 |' outFormat =",
"20 for i in range(count): result = (count-i, *cpg.temp_wts()) if",
"None: '''Flash LEDs and run a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test:",
"outFormat = '| {:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left",
"exception. # This is what we expected. Therefore, just continue.",
"'| count | switch |' outFormat = '| {:5} |",
"= '| {:5} | {:12.3f} | {:7.2f} | {:7.2f} |",
"| {:5} |' else: outHeading = '| count | light",
"result = (count-i, *cpg.touch_wts()) if timestamps else (count-i, cpg.touch()) print(outFormat.format(*result))",
"send one. cpg._query('MEAS:ACC?', 0) # If we are still here,",
"bit to the right # print(f'| {value:4} | {value:010b} |')",
"None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps) -> None: if timestamps:",
"def testAccSpeed(cpg, iterations: int = 100) -> None: '''Measure how",
"tests for CPG''' from .. import CircuitPlayground from .. import",
"FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int = 3) -> None: for",
"test_led(cpg) -> None: '''Flash LEDs and run a short chasing",
"{:12.3f} | {:5} |' else: outHeading = '| count |",
"seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def _testResponseWaitTime(cpg, iterations:",
"testLightSpeed(cpg, iterations: int = 100) -> None: '''Measure how long",
"'''Test it the wait time for additional, unexpected responses is",
"Please wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations)",
"wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total",
"right # print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing",
"_printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG with timestamps ...\\n')",
"# print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) value <<=",
"print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) value <<= 1",
"unexpected responses is long enough.''' print(f'Testing Response-Wait-Time with {iterations} iterations",
"timestamps else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps) ->",
"'| count | timestamp | x m/s^2 | y m/s^2",
"acc measurement speed with {iterations} iterations. Please wait ...') import",
"timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int = 3)",
"light |' outFormat = '| {:5} | {:12.3f} | {:5}",
"resulting in an exception. # This is what we expected.",
"|') cpg.led(value) cpg.wait(0.2) value <<= 1 # shift 1 bit",
"{1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...') print(outHeading) _printCountdown(3) count",
"60 for i in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg,",
"seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def testLightSpeed(cpg, iterations:",
"'''Measure how long it takes to do an accelerometer measurement.'''",
"for i in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps)",
"_printCountdown(3) count = 30 for i in range(count): result =",
"= '| count | switch |' outFormat = '| {:5}",
"test_buttonAny(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The normal behavior is a",
"{!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...') print(outHeading) _printCountdown(3) count",
"or right button...') print(outHeading) _printCountdown(3) count = 10 for i",
"for i in range(10): # print(f'| {value:4} | {value:010b} |')",
"{(result*1000/iterations):.1f} ms per measurement.') def testLightSpeed(cpg, iterations: int = 100)",
"outFormat = '| {:5} | {:7.2f} | {:7.2f} | {:7.2f}",
"in range(10): value >>= 1 # shift 1 bit to",
"|' outFormat = '| {:5} | {:12.3f} | {:7.2f} |'",
"int = 100) -> None: '''Measure how long it takes",
"| {1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...')",
"timestamp | switch |' outFormat = '| {:5} | {:12.3f}",
"i in range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations: int =",
"a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run a",
"right button...') print(outHeading) _printCountdown(3) count = 10 for i in",
"to the right # print(f'| {value:4} | {value:010b} |') cpg.led(value)",
"|' outFormat = '| {:5} | {:12.3f} | {!s:10} |'",
"flush=True) def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None:",
"CPG with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH",
"but do not expect any response, even if the CPG",
"in range(count): result = (count-i, *cpg.light_wts()) if timestamps else (count-i,",
"{:7.2f} | {:7.2f} | {:7.2f} |' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test:",
"_printFuncTestDeliLine() def _printCountdown(start: int = 3) -> None: for i",
"print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps) -> None: if timestamps:",
"_printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps) -> None: if timestamps: outHeading",
"|' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...') print(outHeading) _printCountdown(3) count =",
"for additional, unexpected responses is long enough.''' print(f'Testing Response-Wait-Time with",
"Change slider switch position...') print(outHeading) _printCountdown(3) count = 10 for",
"measurement speed with {iterations} iterations. Please wait ...') import timeit",
"i in range(count): result = (count-i, *cpg.light_wts()) if timestamps else",
"x m/s^2 | y m/s^2 | z m/s^2 |' outFormat",
"print(outHeading) _printCountdown(3) count = 20 for i in range(count): result",
"testAccSpeed(cpg, iterations: int = 100) -> None: '''Measure how long",
"v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG with timestamps ...\\n') else:",
"= '| count | x m/s^2 | y m/s^2 |",
"{0:5} | {1:12.3f} | {2:5} | {2:08b} |' else: outHeading",
"timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps) ->",
"print('try-count', i) try: # Request acc measurement values, but do",
"print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps)",
"'''Flash LEDs three times.''' for i in range(3): cpg.ledDemo() cpg.wait(0.2)",
"Response-Wait-Time with {iterations} iterations ...') for i in range(iterations): if",
"| {:7.2f} | {:7.2f} | {:7.2f} |' testFunction = cpg.acc",
"result = (count-i, *cpg.light_wts()) if timestamps else (count-i, cpg.light()) print(outFormat.format(*result))",
"timestamp | any button |' outFormat = '| {:5} |",
"{2:5} | {2:08b} |' else: outHeading = '| count |",
"timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS')",
"if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG with",
"here, we did not get a response. This is bad.",
"'| count | any button |' outFormat = '| {:5}",
"i in range(10): # print(f'| {value:4} | {value:010b} |') cpg.led(value)",
"cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) -> None: '''Flash",
"test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start:",
"touch | binary |' outFormat = '| {0:5} | {1:12.3f}",
"a light sensor measurement.''' print(f'Testing light measurement speed with {iterations}",
"Tilt the CPG board...') print(outHeading) _printCountdown(3) count = 60 for",
"if timestamps: outHeading = '| count | timestamp | light",
"{:5} |' else: outHeading = '| count | light |'",
"= '| {:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or",
"cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps) -> None: if timestamps:",
"in range(iterations): if i%100==0: print('try-count', i) try: # Request acc",
"a response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response",
"in range(count): result = (count-i, *cpg.temp_wts()) if timestamps else (count-i,",
"timestamps else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps) ->",
"'| count | timestamp | temp °C |' outFormat =",
"# shift 1 bit to the left for i in",
"sensor measurement.''' print(f'Testing light measurement speed with {iterations} iterations. Please",
"# If we are still here, we did not get",
"normal behavior is a response, resulting in an exception. #",
"timestamps else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) -> None:",
"cpg.wait(0.2) def test_touch(cpg, timestamps) -> None: if timestamps: outHeading =",
"LEDs and run a short chasing light...') print('flashing LEDs...') test_ledDemo(cpg)",
"cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms",
"'| {:5} | {:7.2f} | {:7.2f} | {:7.2f} |' testFunction",
"| {value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg)",
"{value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) ->",
"else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps) -> None:",
"*testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps) -> None: if timestamps: outHeading",
"outFormat = '| {:5} | {:12.3f} | {:7.2f} | {:7.2f}",
"if i%100==0: print('try-count', i) try: # Request acc measurement values,",
"\", flush=True) time.sleep(1) print('', flush=True) def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')",
"{:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light sensor...')",
"testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...') print(outHeading) _printCountdown(3)",
"with {iterations} iterations. Please wait ...') import timeit result =",
"'| {:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...')",
"timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE",
"for i in range(count): result = (count-i, *cpg.temp_wts()) if timestamps",
"sensor...') print(outHeading) _printCountdown(3) count = 20 for i in range(count):",
"{2:08b} |' else: outHeading = '| count | touch |",
"average {(result*1000/iterations):.1f} ms per measurement.') def testLightSpeed(cpg, iterations: int =",
"light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run a short chasing light...')",
"testResponseWaitTime(): CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The",
"3) -> None: for i in range(start, 0, -1): print(i,",
"1 bit to the left for i in range(10): value",
"# shift 1 bit to the right # print(f'| {value:4}",
"°C |' outFormat = '| {:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test",
"= '| count | timestamp | temp °C |' outFormat",
"count = 10 for i in range(count): result = (count-i,",
"| {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...') print(outHeading) _printCountdown(3)",
"*cpg.switch_wts()) if timestamps else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg,",
"as CircuitPlaygroundVersion import time def funcTest(timestamps: bool = False) ->",
"y m/s^2 | z m/s^2 |' outFormat = '| {:5}",
"| {:12.3f} | {!s:6} |' else: outHeading = '| count",
"= '| {0:5} | {1:12.3f} | {2:5} | {2:08b} |'",
"= '| {:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over",
"print(heading) def test_buttonAny(cpg, timestamps) -> None: if timestamps: outHeading =",
"| {:12.3f} | {:5} |' else: outHeading = '| count",
"with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE",
"{1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...') print(outHeading)",
"print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps) -> None: if timestamps: outHeading",
"'''Functional tests for CPG''' from .. import CircuitPlayground from ..",
"button |' outFormat = '| {:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test:",
"count | x m/s^2 | y m/s^2 | z m/s^2",
".. import CircuitPlayground from .. import __version__ as CircuitPlaygroundVersion import",
"timestamp | temp °C |' outFormat = '| {:5} |",
"test_light(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On",
"else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG without timestamps",
"outHeading = '| count | timestamp | x m/s^2 |",
"outFormat = '| {:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand",
"in range(count): result = (count-i, *cpg.switch_wts()) if timestamps else (count-i,",
"run a short chasing light...') print('flashing LEDs...') test_ledDemo(cpg) value=1 #",
"range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2) def test_touch(cpg, timestamps) -> None: if",
"{!s:10} |' else: outHeading = '| count | any button",
"in range(count): result = (count-i, *cpg.touch_wts()) if timestamps else (count-i,",
"'| {:5} | {:12.3f} | {!s:6} |' else: outHeading =",
"accelerometer measurement.''' print(f'Testing acc measurement speed with {iterations} iterations. Please",
"test_switch(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"count | switch |' outFormat = '| {:5} | {!s:6}",
"|' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...') print(outHeading) _printCountdown(3) count =",
"it takes to do a light sensor measurement.''' print(f'Testing light",
"= (count-i, *cpg.buttonAny_wts()) if timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5)",
"else: outHeading = '| count | touch | binary |'",
"i in range(start, 0, -1): print(i, end=\" \", flush=True) time.sleep(1)",
"{result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def testLightSpeed(cpg,",
"{:7.2f} |' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...')",
"{:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count =",
"'| count | timestamp | touch | binary |' outFormat",
"average {(result*1000/iterations):.1f} ms per measurement.') def _testResponseWaitTime(cpg, iterations: int =",
"one. cpg._query('MEAS:ACC?', 0) # If we are still here, we",
"setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms per",
"in testResponseWaitTime(): CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: #",
"m/s^2 | z m/s^2 |' outFormat = '| {:5} |",
"range(start, 0, -1): print(i, end=\" \", flush=True) time.sleep(1) print('', flush=True)",
"ms per measurement.') def testLightSpeed(cpg, iterations: int = 100) ->",
"cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) -> None: '''Flash LEDs",
"count | timestamp | any button |' outFormat = '|",
"The normal behavior is a response, resulting in an exception.",
"count | temp °C |' outFormat = '| {:5} |",
"test_ledDemo(cpg) -> None: '''Flash LEDs three times.''' for i in",
"try: # Request acc measurement values, but do not expect",
"count = 60 for i in range(count): print(outFormat.format(count-i, *testFunction())) cpg.wait(0.2)",
"__version__ as CircuitPlaygroundVersion import time def funcTest(timestamps: bool = False)",
"= 10 for i in range(count): result = (count-i, *cpg.switch_wts())",
"range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations: int = 100) ->",
"temp °C |' outFormat = '| {:5} | {:12.3f} |",
"iterations. Please wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.light(),",
"timeit result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.')",
"in range(start, 0, -1): print(i, end=\" \", flush=True) time.sleep(1) print('',",
"test_led(cpg) # test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg,",
"{:5} | {:12.3f} | {:7.2f} | {:7.2f} | {:7.2f} |'",
"| {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count = 20",
"values, but do not expect any response, even if the",
"= '| count | timestamp | any button |' outFormat",
"outFormat = '| {:5} | {:12.3f} | {:7.2f} |' else:",
"{:5} | {:12.3f} | {:5} |' else: outHeading = '|",
"|' outFormat = '| {:5} | {:7.2f} | {:7.2f} |",
"LEDs |') for i in range(10): # print(f'| {value:4} |",
"= 100) -> None: '''Measure how long it takes to",
"def _testResponseWaitTime(cpg, iterations: int = 10000) -> None: '''Test it",
"will send one. cpg._query('MEAS:ACC?', 0) # If we are still",
"timestamp | x m/s^2 | y m/s^2 | z m/s^2",
"|' else: outHeading = '| count | light |' outFormat",
"the CPG will send one. cpg._query('MEAS:ACC?', 0) # If we",
"switch position...') print(outHeading) _printCountdown(3) count = 10 for i in",
"CircuitPlayground from .. import __version__ as CircuitPlaygroundVersion import time def",
"| binary |' outFormat = '| {0:5} | {1:12.3f} |",
"| timestamp | temp °C |' outFormat = '| {:5}",
"| y m/s^2 | z m/s^2 |' outFormat = '|",
"print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps) -> None: if timestamps: outHeading",
"get a response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime():",
"outFormat = '| {:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider",
"Request acc measurement values, but do not expect any response,",
"print(f'Testing light measurement speed with {iterations} iterations. Please wait ...')",
"bit to the left for i in range(10): value >>=",
"= 3) -> None: for i in range(start, 0, -1):",
"| any button |' outFormat = '| {:5} | {:12.3f}",
"to the left for i in range(10): value >>= 1",
"if timestamps: outHeading = '| count | timestamp | any",
"timestamps: outHeading = '| count | timestamp | switch |'",
"{:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light sensor...') print(outHeading) _printCountdown(3)",
"{:5} | {:12.3f} | {!s:6} |' else: outHeading = '|",
"| z m/s^2 |' outFormat = '| {:5} | {:12.3f}",
"cpg.led(value) cpg.wait(0.2) value <<= 1 # shift 1 bit to",
"range(10): value >>= 1 # shift 1 bit to the",
"timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f}",
"def test_light(cpg, timestamps) -> None: if timestamps: outHeading = '|",
"binary |' outFormat = '| {0:5} | {1:12.3f} | {2:5}",
"def test_acc(cpg, timestamps) -> None: if timestamps: outHeading = '|",
"response, resulting in an exception. # This is what we",
"for i in range(10): value >>= 1 # shift 1",
"|') for i in range(10): # print(f'| {value:4} | {value:010b}",
"20 for i in range(count): result = (count-i, *cpg.light_wts()) if",
"cpg.wait(0.5) def test_light(cpg, timestamps) -> None: if timestamps: outHeading =",
"test_ledDemo(cpg) def test_ledDemo(cpg) -> None: '''Flash LEDs three times.''' for",
"response, even if the CPG will send one. cpg._query('MEAS:ACC?', 0)",
"test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg,",
"= '| count | touch | binary |' outFormat =",
"1 # shift 1 bit to the right # print(f'|",
"how long it takes to do an accelerometer measurement.''' print(f'Testing",
"if timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def test_switch(cpg, timestamps)",
"cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH",
"timestamps: outHeading = '| count | timestamp | light |'",
"100) -> None: '''Measure how long it takes to do",
"Flash LEDs and run a short chasing light...') print('flashing LEDs...')",
"long it takes to do an accelerometer measurement.''' print(f'Testing acc",
"_printCountdown(3) count = 20 for i in range(count): result =",
"else: outHeading = '| count | switch |' outFormat =",
"(count-i, *cpg.buttonAny_wts()) if timestamps else (count-i, cpg.buttonAny()) print(outFormat.format(*result)) cpg.wait(0.5) def",
"i in range(count): result = (count-i, *cpg.switch_wts()) if timestamps else",
"'| {0:5} | {1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive",
"value <<= 1 # shift 1 bit to the left",
"do a light sensor measurement.''' print(f'Testing light measurement speed with",
"time for additional, unexpected responses is long enough.''' print(f'Testing Response-Wait-Time",
"count | timestamp | temp °C |' outFormat = '|",
"def test_led(cpg) -> None: '''Flash LEDs and run a short",
"*cpg.touch_wts()) if timestamps else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg)",
"{:12.3f} | {:7.2f} |' else: outHeading = '| count |",
"timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int",
"for i in range(count): result = (count-i, *cpg.light_wts()) if timestamps",
"time.sleep(1) print('', flush=True) def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading)",
"short chasing light...') print('flashing LEDs...') test_ledDemo(cpg) value=1 # print('| val",
"-> None: if timestamps: outHeading = '| count | timestamp",
"|' outFormat = '| {:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...')",
"(count-i, *cpg.temp_wts()) if timestamps else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def",
"an accelerometer measurement.''' print(f'Testing acc measurement speed with {iterations} iterations.",
"*cpg.temp_wts()) if timestamps else (count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg,",
"print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except",
"|') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) -> None:",
"'| {:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count",
"range(count): result = (count-i, *cpg.buttonAny_wts()) if timestamps else (count-i, cpg.buttonAny())",
"-> None: '''Test it the wait time for additional, unexpected",
"measurement.') def testLightSpeed(cpg, iterations: int = 100) -> None: '''Measure",
"bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')",
"_printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG without timestamps ...\\n')",
"if timestamps: outHeading = '| count | timestamp | touch",
"response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response was",
"except Exception: # The normal behavior is a response, resulting",
"i) try: # Request acc measurement values, but do not",
"i in range(count): result = (count-i, *cpg.touch_wts()) if timestamps else",
"if timestamps else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps)",
"FUNCTIONAL-TESTS WITH THE CPG without timestamps ...\\n') # test_led(cpg) #",
"any button |' outFormat = '| {:5} | {:12.3f} |",
"| {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...') print(outHeading) _printCountdown(3)",
"None: '''Test it the wait time for additional, unexpected responses",
"timestamps: outHeading = '| count | timestamp | any button",
"result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On",
"outFormat = '| {0:5} | {1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test:",
"'| count | timestamp | light |' outFormat = '|",
"SOME FUNCTIONAL-TESTS WITH THE CPG without timestamps ...\\n') # test_led(cpg)",
"{1:12.3f} | {2:5} | {2:08b} |' else: outHeading = '|",
"value >>= 1 # shift 1 bit to the right",
"*cpg.light_wts()) if timestamps else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg,",
"the CPG board...') print(outHeading) _printCountdown(3) count = 60 for i",
"| LEDs |') for i in range(10): # print(f'| {value:4}",
"if timestamps: outHeading = '| count | timestamp | temp",
"_printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps) -> None:",
"= '| {:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch",
"timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def",
"else: outHeading = '| count | temp °C |' outFormat",
"else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) -> None: '''Flash",
"|' else: outHeading = '| count | temp °C |'",
"|' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...') print(outHeading)",
"| {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light sensor...') print(outHeading)",
"light sensor...') print(outHeading) _printCountdown(3) count = 20 for i in",
"timestamps else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps) ->",
"_printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG board...') print(outHeading) _printCountdown(3) count = 60",
"enough.''' print(f'Testing Response-Wait-Time with {iterations} iterations ...') for i in",
"flush=True) time.sleep(1) print('', flush=True) def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def",
"= 10 for i in range(count): result = (count-i, *cpg.buttonAny_wts())",
"(count-i, *cpg.switch_wts()) if timestamps else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5) def",
"'| count | light |' outFormat = '| {:5} |",
"| {:7.2f} | {:7.2f} |' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt",
"timestamp | touch | binary |' outFormat = '| {0:5}",
"button |' outFormat = '| {:5} | {:12.3f} | {!s:10}",
"CPG board...') print(outHeading) _printCountdown(3) count = 60 for i in",
"it the wait time for additional, unexpected responses is long",
"{:7.2f} | {:7.2f} | {:7.2f} |' testFunction = cpg.acc_wts else:",
"takes to do an accelerometer measurement.''' print(f'Testing acc measurement speed",
"CPG''' from .. import CircuitPlayground from .. import __version__ as",
"(count-i, *cpg.light_wts()) if timestamps else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def",
"{0:5} | {1:5} | {1:08b} |' _printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor",
"test_touch(cpg, timestamps) _printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int =",
"shift 1 bit to the right # print(f'| {value:4} |",
"count = 20 for i in range(count): result = (count-i,",
"cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) -> None: '''Flash LEDs and",
"any response, even if the CPG will send one. cpg._query('MEAS:ACC?',",
"= '| {:5} | {:7.2f} | {:7.2f} | {:7.2f} |'",
"cpg.wait(0.5) def test_temp(cpg, timestamps) -> None: if timestamps: outHeading =",
"hand over light sensor...') print(outHeading) _printCountdown(3) count = 20 for",
"short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and run a short",
"|' else: outHeading = '| count | any button |'",
"cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations: int = 100) -> None:",
"def testLightSpeed(cpg, iterations: int = 100) -> None: '''Measure how",
"left for i in range(10): value >>= 1 # shift",
"= 20 for i in range(count): result = (count-i, *cpg.light_wts())",
"= 10000) -> None: '''Test it the wait time for",
"CPG without timestamps ...\\n') # test_led(cpg) # test_buttonAny(cpg, timestamps) #",
"for i in range(count): result = (count-i, *cpg.touch_wts()) if timestamps",
"def test_ledDemo(cpg) -> None: '''Flash LEDs three times.''' for i",
"it takes to do an accelerometer measurement.''' print(f'Testing acc measurement",
"iterations ...') for i in range(iterations): if i%100==0: print('try-count', i)",
"'| {0:5} | {1:12.3f} | {2:5} | {2:08b} |' else:",
"range(iterations): if i%100==0: print('try-count', i) try: # Request acc measurement",
"to do a light sensor measurement.''' print(f'Testing light measurement speed",
"-> None: '''Measure how long it takes to do an",
"cpg.wait(0.5) def test_switch(cpg, timestamps) -> None: if timestamps: outHeading =",
"test_temp(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in testResponseWaitTime(): CPG-Response was too",
"def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading) def test_buttonAny(cpg, timestamps) ->",
"{(result*1000/iterations):.1f} ms per measurement.') def _testResponseWaitTime(cpg, iterations: int = 10000)",
"outFormat = '| {:5} | {:12.3f} | {:5} |' else:",
"WITH THE CPG with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME",
"'''Measure how long it takes to do a light sensor",
"= False) -> None: cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi",
"measurement.''' print(f'Testing acc measurement speed with {iterations} iterations. Please wait",
"bool = False) -> None: cpg = CircuitPlayground() if timestamps:",
"in range(10): # print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2)",
"print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The normal behavior is a response,",
"timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG",
"import timeit result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f}",
"= '| count | timestamp | switch |' outFormat =",
"...') for i in range(iterations): if i%100==0: print('try-count', i) try:",
"| {2:5} | {2:08b} |' else: outHeading = '| count",
"outHeading = '| count | any button |' outFormat =",
"test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps) test_touch(cpg, timestamps)",
"|' outFormat = '| {:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move",
"else: outHeading = '| count | any button |' outFormat",
"| light |' outFormat = '| {:5} | {:5} |'",
"1 # shift 1 bit to the left for i",
"for CPG''' from .. import CircuitPlayground from .. import __version__",
"-> None: '''Flash LEDs three times.''' for i in range(3):",
"z m/s^2 |' outFormat = '| {:5} | {:12.3f} |",
"import timeit result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f}",
"-1): print(i, end=\" \", flush=True) time.sleep(1) print('', flush=True) def _printFuncTestDeliLine()",
"# Request acc measurement values, but do not expect any",
"i in range(count): result = (count-i, *cpg.buttonAny_wts()) if timestamps else",
"range(count): result = (count-i, *cpg.light_wts()) if timestamps else (count-i, cpg.light())",
"outHeading = '| count | touch | binary |' outFormat",
"outFormat = '| {:5} | {:12.3f} | {!s:6} |' else:",
"# test_led(cpg) # test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps) test_temp(cpg, timestamps)",
"LEDs and run a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs",
"_printCountdown(3) count = 10 for i in range(count): result =",
"for i in range(count): result = (count-i, *cpg.buttonAny_wts()) if timestamps",
"timeit result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.')",
"to do an accelerometer measurement.''' print(f'Testing acc measurement speed with",
"speed with {iterations} iterations. Please wait ...') import timeit result",
"cpg.acc_wts else: outHeading = '| count | x m/s^2 |",
"= cpg.acc_wts else: outHeading = '| count | x m/s^2",
"|' outFormat = '| {:5} | {:12.3f} | {:7.2f} |",
"i in range(10): value >>= 1 # shift 1 bit",
"a response, resulting in an exception. # This is what",
"count | touch | binary |' outFormat = '| {0:5}",
"even if the CPG will send one. cpg._query('MEAS:ACC?', 0) #",
"'| count | touch | binary |' outFormat = '|",
"count | timestamp | light |' outFormat = '| {:5}",
"'| count | timestamp | switch |' outFormat = '|",
"the left for i in range(10): value >>= 1 #",
"for i in range(iterations): if i%100==0: print('try-count', i) try: #",
"result = (count-i, *cpg.switch_wts()) if timestamps else (count-i, cpg.switch()) print(outFormat.format(*result))",
"10000) -> None: '''Test it the wait time for additional,",
"...') import timeit result = timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time:",
"{:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count = 20 for",
"val | LEDs |') for i in range(10): # print(f'|",
"{:7.2f} |' testFunction = cpg.acc_wts else: outHeading = '| count",
"| {!s:6} |' else: outHeading = '| count | switch",
"def test_switch(cpg, timestamps) -> None: if timestamps: outHeading = '|",
"'| {:5} | {:12.3f} | {:7.2f} |' else: outHeading =",
"| touch | binary |' outFormat = '| {0:5} |",
"|' outFormat = '| {:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change",
"Touch capacitive sensor pads...') print(outHeading) _printCountdown(3) count = 30 for",
"<<= 1 # shift 1 bit to the left for",
"outHeading = '| count | x m/s^2 | y m/s^2",
"None: cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS",
"|' testFunction = cpg.acc_wts else: outHeading = '| count |",
"{value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) value <<= 1 #",
"SOME FUNCTIONAL-TESTS WITH THE CPG with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi",
"a short chasing light...') print('flashing LEDs...') test_ledDemo(cpg) value=1 # print('|",
"CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception: # The normal",
"end=\" \", flush=True) time.sleep(1) print('', flush=True) def _printFuncTestDeliLine() -> None:",
"takes to do a light sensor measurement.''' print(f'Testing light measurement",
"times.''' for i in range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations:",
"print(f'Testing acc measurement speed with {iterations} iterations. Please wait ...')",
"do an accelerometer measurement.''' print(f'Testing acc measurement speed with {iterations}",
"not get a response. This is bad. print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') print('ERROR in",
"print(outFormat.format(*result)) cpg.wait(0.5) def test_temp(cpg, timestamps) -> None: if timestamps: outHeading",
"...\\n') # test_led(cpg) # test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps) test_temp(cpg,",
"= '| {:5} | {:12.3f} | {!s:6} |' else: outHeading",
"°C |' outFormat = '| {:5} | {:12.3f} | {:7.2f}",
"| temp °C |' outFormat = '| {:5} | {:7.2f}",
"| binary |' outFormat = '| {0:5} | {1:5} |",
"def _printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine()",
"range(count): result = (count-i, *cpg.switch_wts()) if timestamps else (count-i, cpg.switch())",
"print('ERROR in testResponseWaitTime(): CPG-Response was too late.') print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') except Exception:",
"# test_buttonAny(cpg, timestamps) # test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps)",
"{iterations} iterations ...') for i in range(iterations): if i%100==0: print('try-count',",
"measurement.') def _testResponseWaitTime(cpg, iterations: int = 10000) -> None: '''Test",
"= 20 for i in range(count): result = (count-i, *cpg.temp_wts())",
"= '| count | timestamp | touch | binary |'",
"_printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...') print(outHeading) _printCountdown(3) count = 10",
"= '| count | timestamp | x m/s^2 | y",
"_printFuncTestHeadingWithDeliLine('Touch-Sensor-Test: Touch capacitive sensor pads...') print(outHeading) _printCountdown(3) count = 30",
"{:12.3f} | {!s:10} |' else: outHeading = '| count |",
"count | timestamp | x m/s^2 | y m/s^2 |",
"still here, we did not get a response. This is",
"_printFuncTestHeadingWithDeliLine('Button-Test: Press left or right button...') print(outHeading) _printCountdown(3) count =",
"{:7.2f} | {:7.2f} |' testFunction = cpg.acc_wts else: outHeading =",
"{:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test: Change slider switch position...') print(outHeading)",
"= CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE",
"'| count | x m/s^2 | y m/s^2 | z",
"and run a short chasing light...') print('flashing LEDs...') test_ledDemo(cpg) value=1",
"measurement.''' print(f'Testing light measurement speed with {iterations} iterations. Please wait",
"timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f}",
"= '| count | light |' outFormat = '| {:5}",
"responses is long enough.''' print(f'Testing Response-Wait-Time with {iterations} iterations ...')",
"and run a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash LEDs and",
">>= 1 # shift 1 bit to the right #",
"{iterations} iterations. Please wait ...') import timeit result = timeit.Timer(stmt=lambda:",
"THE CPG without timestamps ...\\n') # test_led(cpg) # test_buttonAny(cpg, timestamps)",
"(count-i, cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps) -> None: if",
"from .. import CircuitPlayground from .. import __version__ as CircuitPlaygroundVersion",
"per measurement.') def _testResponseWaitTime(cpg, iterations: int = 10000) -> None:",
"| z m/s^2 |' outFormat = '| {:5} | {:7.2f}",
"print(outHeading) _printCountdown(3) count = 30 for i in range(count): result",
"...') print(outHeading) _printCountdown(3) count = 20 for i in range(count):",
"False) -> None: cpg = CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING",
"'| {:5} | {:12.3f} | {:7.2f} | {:7.2f} | {:7.2f}",
"i%100==0: print('try-count', i) try: # Request acc measurement values, but",
"def _printCountdown(start: int = 3) -> None: for i in",
"over light sensor...') print(outHeading) _printCountdown(3) count = 20 for i",
"_printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading) _printCountdown(3) count = 20 for i in",
"in an exception. # This is what we expected. Therefore,",
"-> None: '''Measure how long it takes to do a",
"= 30 for i in range(count): result = (count-i, *cpg.touch_wts())",
"| timestamp | touch | binary |' outFormat = '|",
"None: if timestamps: outHeading = '| count | timestamp |",
"| {value:010b} |') cpg.led(value) cpg.wait(0.2) value <<= 1 # shift",
"| x m/s^2 | y m/s^2 | z m/s^2 |'",
"| switch |' outFormat = '| {:5} | {:12.3f} |",
"iterations: int = 100) -> None: '''Measure how long it",
"CircuitPlayground() if timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG",
"CPG will send one. cpg._query('MEAS:ACC?', 0) # If we are",
"Move hand over light sensor...') print(outHeading) _printCountdown(3) count = 20",
"| timestamp | switch |' outFormat = '| {:5} |",
"testFunction = cpg.acc_wts else: outHeading = '| count | x",
"m/s^2 |' outFormat = '| {:5} | {:12.3f} | {:7.2f}",
"timestamp | light |' outFormat = '| {:5} | {:12.3f}",
"measurement values, but do not expect any response, even if",
"light measurement speed with {iterations} iterations. Please wait ...') import",
"for i in range(count): result = (count-i, *cpg.switch_wts()) if timestamps",
"'| {:5} | {:12.3f} | {:5} |' else: outHeading =",
"sensor pads...') print(outHeading) _printCountdown(3) count = 30 for i in",
"import time def funcTest(timestamps: bool = False) -> None: cpg",
"1 bit to the right # print(f'| {value:4} | {value:010b}",
"count | timestamp | touch | binary |' outFormat =",
"_printFuncTestHeadingWithDeliLine('DONE WITH FUNCTIONAL-TESTS') _printFuncTestDeliLine() def _printCountdown(start: int = 3) ->",
"count | any button |' outFormat = '| {:5} |",
"button...') print(outHeading) _printCountdown(3) count = 10 for i in range(count):",
"v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG without timestamps ...\\n') #",
"cpg.wait(0.2) def testAccSpeed(cpg, iterations: int = 100) -> None: '''Measure",
"LEDs three times.''' for i in range(3): cpg.ledDemo() cpg.wait(0.2) def",
"expect any response, even if the CPG will send one.",
"additional, unexpected responses is long enough.''' print(f'Testing Response-Wait-Time with {iterations}",
"slider switch position...') print(outHeading) _printCountdown(3) count = 10 for i",
"in range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg, iterations: int = 100)",
"{:5} | {:12.3f} | {!s:10} |' else: outHeading = '|",
"{:5} | {:7.2f} | {:7.2f} | {:7.2f} |' testFunction =",
"Please wait ...') import timeit result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations)",
"= '| {:5} | {:12.3f} | {!s:10} |' else: outHeading",
"print('flashing LEDs...') test_ledDemo(cpg) value=1 # print('| val | LEDs |')",
"None: '''Measure how long it takes to do an accelerometer",
"in range(count): result = (count-i, *cpg.buttonAny_wts()) if timestamps else (count-i,",
"int = 10000) -> None: '''Test it the wait time",
"WITH THE CPG without timestamps ...\\n') # test_led(cpg) # test_buttonAny(cpg,",
"def funcTest(timestamps: bool = False) -> None: cpg = CircuitPlayground()",
"print(i, end=\" \", flush=True) time.sleep(1) print('', flush=True) def _printFuncTestDeliLine() ->",
"if timestamps else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps)",
"from .. import __version__ as CircuitPlaygroundVersion import time def funcTest(timestamps:",
"|' outFormat = '| {:5} | {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press",
"are still here, we did not get a response. This",
"= (count-i, *cpg.switch_wts()) if timestamps else (count-i, cpg.switch()) print(outFormat.format(*result)) cpg.wait(0.5)",
"outFormat = '| {:5} | {:7.2f} |' _printFuncTestHeadingWithDeliLine('Temp-Sensor-Test ...') print(outHeading)",
"| {:7.2f} |' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the CPG",
"i in range(count): result = (count-i, *cpg.temp_wts()) if timestamps else",
"light |' outFormat = '| {:5} | {:5} |' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test:",
"long it takes to do a light sensor measurement.''' print(f'Testing",
"test_touch(cpg, timestamps) -> None: if timestamps: outHeading = '| count",
"switch |' outFormat = '| {:5} | {!s:6} |' _printFuncTestHeadingWithDeliLine('Switch-Test:",
"None: '''Flash LEDs three times.''' for i in range(3): cpg.ledDemo()",
"timestamps) # test_switch(cpg, timestamps) test_temp(cpg, timestamps) test_light(cpg, timestamps) test_acc(cpg, timestamps)",
"{:12.3f} | {!s:6} |' else: outHeading = '| count |",
"print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def testLightSpeed(cpg, iterations: int",
"{:7.2f} |' else: outHeading = '| count | temp °C",
"import __version__ as CircuitPlaygroundVersion import time def funcTest(timestamps: bool =",
"cpg.wait(0.2) value <<= 1 # shift 1 bit to the",
"| {:12.3f} | {!s:10} |' else: outHeading = '| count",
"outHeading = '| count | timestamp | touch | binary",
"print(f'Total time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.')",
"{value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...') test_ledDemo(cpg) def",
"behavior is a response, resulting in an exception. # This",
"THE CPG with timestamps ...\\n') else: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS",
"= timeit.Timer(stmt=lambda: cpg.light(), setup='pass').timeit(number=iterations) print(f'Total time: {result:.1f} seconds.') print(f'On average",
"temp °C |' outFormat = '| {:5} | {:7.2f} |'",
"else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5) def test_acc(cpg, timestamps) -> None:",
"...') import timeit result = timeit.Timer(stmt=lambda: cpg.acc(), setup='pass').timeit(number=iterations) print(f'Total time:",
"wait time for additional, unexpected responses is long enough.''' print(f'Testing",
"| timestamp | any button |' outFormat = '| {:5}",
"# print(f'| {value:4} | {value:010b} |') cpg.led(value) cpg.wait(0.2) print('flashing LEDs...')",
"|' else: outHeading = '| count | touch | binary",
"| temp °C |' outFormat = '| {:5} | {:12.3f}",
"{:5} | {:12.3f} | {:7.2f} |' else: outHeading = '|",
"{:7.2f} | {:7.2f} |' testFunction = cpg.acc _printFuncTestHeadingWithDeliLine('Accelerometer-Test: Tilt the",
"_printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light sensor...') print(outHeading) _printCountdown(3) count =",
"cpg.wait(0.5) def test_led(cpg) -> None: '''Flash LEDs and run a",
"light...') print('flashing LEDs...') test_ledDemo(cpg) value=1 # print('| val | LEDs",
"print('flashing LEDs...') test_ledDemo(cpg) def test_ledDemo(cpg) -> None: '''Flash LEDs three",
"if timestamps else (count-i, cpg.touch()) print(outFormat.format(*result)) cpg.wait(0.5) def test_led(cpg) ->",
"ms per measurement.') def _testResponseWaitTime(cpg, iterations: int = 10000) ->",
"else: outHeading = '| count | x m/s^2 | y",
"|' _printFuncTestHeadingWithDeliLine('Light-Sensor-Test: Move hand over light sensor...') print(outHeading) _printCountdown(3) count",
"_printFuncTestDeliLine() -> None: print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') def _printFuncTestHeadingWithDeliLine(heading) -> None: _printFuncTestDeliLine() print(heading)",
"= (count-i, *cpg.light_wts()) if timestamps else (count-i, cpg.light()) print(outFormat.format(*result)) cpg.wait(0.5)",
"outHeading = '| count | timestamp | switch |' outFormat",
"i in range(iterations): if i%100==0: print('try-count', i) try: # Request",
"_printCountdown(3) count = 60 for i in range(count): print(outFormat.format(count-i, *testFunction()))",
"| {!s:10} |' _printFuncTestHeadingWithDeliLine('Button-Test: Press left or right button...') print(outHeading)",
"timestamps: _printFuncTestHeadingWithDeliLine(f'cpg_scpi v{CircuitPlaygroundVersion}\\nRUNNING SOME FUNCTIONAL-TESTS WITH THE CPG with timestamps",
"if timestamps: outHeading = '| count | timestamp | switch",
"three times.''' for i in range(3): cpg.ledDemo() cpg.wait(0.2) def testAccSpeed(cpg,",
"cpg.temp()) print(outFormat.format(*result)) cpg.wait(0.5) def test_light(cpg, timestamps) -> None: if timestamps:",
"int = 3) -> None: for i in range(start, 0,",
"timestamps) -> None: if timestamps: outHeading = '| count |",
"'''Flash LEDs and run a short chasing light.''' _printFuncTestHeadingWithDeliLine('LED-Test: Flash",
"chasing light...') print('flashing LEDs...') test_ledDemo(cpg) value=1 # print('| val |",
"time: {result:.1f} seconds.') print(f'On average {(result*1000/iterations):.1f} ms per measurement.') def"
] |
[
"models class Account(models.Model): clsNb = models.IntegerField() Name = models.CharField(max_length=10) pw",
"from django.db import models class Account(models.Model): clsNb = models.IntegerField() Name",
"models.IntegerField() Name = models.CharField(max_length=10) pw = models.IntegerField() def __str__(self): return",
"class Account(models.Model): clsNb = models.IntegerField() Name = models.CharField(max_length=10) pw =",
"import models class Account(models.Model): clsNb = models.IntegerField() Name = models.CharField(max_length=10)",
"clsNb = models.IntegerField() Name = models.CharField(max_length=10) pw = models.IntegerField() def",
"Name = models.CharField(max_length=10) pw = models.IntegerField() def __str__(self): return self.Name",
"= models.IntegerField() Name = models.CharField(max_length=10) pw = models.IntegerField() def __str__(self):",
"django.db import models class Account(models.Model): clsNb = models.IntegerField() Name =",
"Account(models.Model): clsNb = models.IntegerField() Name = models.CharField(max_length=10) pw = models.IntegerField()"
] |
[
"geodesic_distance(pos, face) expected = [ [0, 1, 1, sqrt(2)], [1,",
"[2, 2 * sqrt(2), 0, 2], [2 * sqrt(2), 2,",
"[0, 1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos,",
"1], [sqrt(2), 1, 1, 0], ] assert torch.allclose(out, torch.tensor(expected)) assert",
"2 * sqrt(2)], [2, 0, 2 * sqrt(2), 2], [2,",
"norm=False) expected = [ [0, 2, 2, 2 * sqrt(2)],",
"] assert torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0, 0, 0, 0])",
"[2, 0, 2 * sqrt(2), 2], [2, 2 * sqrt(2),",
"sqrt(2), 2, 2, 0], ] assert torch.allclose(out, torch.tensor(expected)) src =",
"math import sqrt import torch from torch_geometric.utils import geodesic_distance def",
"out = geodesic_distance(pos, face, dest=dest) expected = [0, 0, 0,",
"0]]) face = torch.tensor([[0, 1, 3], [0, 2, 3]]).t() out",
"torch.tensor([0, 0, 0, 0]) dest = torch.tensor([0, 1, 2, 3])",
"import torch from torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos =",
"torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, src=src[0:1]) expected = [0,",
"1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, src=src[0:1])",
"face, dest=dest) expected = [0, 0, 0, 0] assert torch.allclose(out,",
"torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out = geodesic_distance(pos, face,",
"geodesic_distance(pos, face, src=src, dest=dest) expected = [0, 1, 1, sqrt(2)]",
"[0, 2, 0], [2, 2, 0]]) face = torch.tensor([[0, 1,",
"torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out = geodesic_distance(pos,",
"from torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0, 0,",
"= geodesic_distance(pos, face, norm=False) expected = [ [0, 2, 2,",
"[2 * sqrt(2), 2, 2, 0], ] assert torch.allclose(out, torch.tensor(expected))",
"* sqrt(2), 2], [2, 2 * sqrt(2), 0, 2], [2",
"3]) out = geodesic_distance(pos, face, src=src, dest=dest) expected = [0,",
"= torch.tensor([[0, 1, 3], [0, 2, 3]]).t() out = geodesic_distance(pos,",
"2, 0]]) face = torch.tensor([[0, 1, 3], [0, 2, 3]]).t()",
"[1, sqrt(2), 0, 1], [sqrt(2), 1, 1, 0], ] assert",
"torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0, 0, 0, 0]) dest =",
"out = geodesic_distance(pos, face, src=src, dest=dest) expected = [0, 1,",
"[0, 2, 3]]).t() out = geodesic_distance(pos, face) expected = [",
"src=src, dest=dest) expected = [0, 1, 1, sqrt(2)] assert torch.allclose(out,",
"= geodesic_distance(pos, face) expected = [ [0, 1, 1, sqrt(2)],",
"torch.tensor(expected)) out = geodesic_distance(pos, face, src=src[0:1]) expected = [0, 1,",
"expected = [0, 1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out",
"face, src=src[0:1]) expected = [0, 1, 1, sqrt(2)] assert torch.allclose(out,",
"sqrt(2)], [2, 0, 2 * sqrt(2), 2], [2, 2 *",
"0, 0], [2, 0, 0], [0, 2, 0], [2, 2,",
"torch.tensor([0, 1, 2, 3]) out = geodesic_distance(pos, face, src=src, dest=dest)",
"assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, dest=dest) expected =",
"2, 2, 2 * sqrt(2)], [2, 0, 2 * sqrt(2),",
"face, norm=False) expected = [ [0, 2, 2, 2 *",
"torch.tensor(expected)) src = torch.tensor([0, 0, 0, 0]) dest = torch.tensor([0,",
"= geodesic_distance(pos, face, src=src[0:1]) expected = [0, 1, 1, sqrt(2)]",
"from math import sqrt import torch from torch_geometric.utils import geodesic_distance",
"= geodesic_distance(pos, face, src=src, dest=dest) expected = [0, 1, 1,",
"0], [2, 2, 0]]) face = torch.tensor([[0, 1, 3], [0,",
"0, 2], [2 * sqrt(2), 2, 2, 0], ] assert",
"out = geodesic_distance(pos, face) expected = [ [0, 1, 1,",
"[0, 2, 2, 2 * sqrt(2)], [2, 0, 2 *",
"0], [0, 2, 0], [2, 2, 0]]) face = torch.tensor([[0,",
"[2, 2, 0]]) face = torch.tensor([[0, 1, 3], [0, 2,",
"expected = [ [0, 2, 2, 2 * sqrt(2)], [2,",
"expected = [ [0, 1, 1, sqrt(2)], [1, 0, sqrt(2),",
"1, 2, 3]) out = geodesic_distance(pos, face, src=src, dest=dest) expected",
"0, sqrt(2), 1], [1, sqrt(2), 0, 1], [sqrt(2), 1, 1,",
"1, 0], ] assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face,",
"sqrt import torch from torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos",
"1, 1, sqrt(2)], [1, 0, sqrt(2), 1], [1, sqrt(2), 0,",
"src = torch.tensor([0, 0, 0, 0]) dest = torch.tensor([0, 1,",
"0, 1], [sqrt(2), 1, 1, 0], ] assert torch.allclose(out, torch.tensor(expected))",
"geodesic_distance(pos, face, dest=dest) expected = [0, 0, 0, 0] assert",
"geodesic_distance(pos, face, norm=False) expected = [ [0, 2, 2, 2",
"geodesic_distance(pos, face, num_workers=-1)) out = geodesic_distance(pos, face, norm=False) expected =",
"[1, 0, sqrt(2), 1], [1, sqrt(2), 0, 1], [sqrt(2), 1,",
"= geodesic_distance(pos, face, dest=dest) expected = [0, 0, 0, 0]",
"dest=dest) expected = [0, 1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected))",
"0, 0]) dest = torch.tensor([0, 1, 2, 3]) out =",
"sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, dest=dest) expected",
"2 * sqrt(2), 0, 2], [2 * sqrt(2), 2, 2,",
"1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face,",
"assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out = geodesic_distance(pos, face, norm=False)",
"1, 3], [0, 2, 3]]).t() out = geodesic_distance(pos, face) expected",
"torch.Tensor([[0, 0, 0], [2, 0, 0], [0, 2, 0], [2,",
"sqrt(2), 0, 2], [2 * sqrt(2), 2, 2, 0], ]",
"3]]).t() out = geodesic_distance(pos, face) expected = [ [0, 1,",
"torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out = geodesic_distance(pos, face, norm=False) expected",
"[2, 0, 0], [0, 2, 0], [2, 2, 0]]) face",
"1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, dest=dest)",
"= torch.tensor([0, 1, 2, 3]) out = geodesic_distance(pos, face, src=src,",
"0, 2 * sqrt(2), 2], [2, 2 * sqrt(2), 0,",
"2, 3]]).t() out = geodesic_distance(pos, face) expected = [ [0,",
"0], [2, 0, 0], [0, 2, 0], [2, 2, 0]])",
"] assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out",
"1], [1, sqrt(2), 0, 1], [sqrt(2), 1, 1, 0], ]",
"test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0], [2, 0, 0], [0,",
"sqrt(2)], [1, 0, sqrt(2), 1], [1, sqrt(2), 0, 1], [sqrt(2),",
"0], ] assert torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0, 0, 0,",
"face, src=src, dest=dest) expected = [0, 1, 1, sqrt(2)] assert",
"src=src[0:1]) expected = [0, 1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected))",
"torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, dest=dest) expected = [0,",
"2, 2 * sqrt(2)], [2, 0, 2 * sqrt(2), 2],",
"= torch.Tensor([[0, 0, 0], [2, 0, 0], [0, 2, 0],",
"0, 0], [0, 2, 0], [2, 2, 0]]) face =",
"[ [0, 1, 1, sqrt(2)], [1, 0, sqrt(2), 1], [1,",
"* sqrt(2), 2, 2, 0], ] assert torch.allclose(out, torch.tensor(expected)) src",
"num_workers=-1)) out = geodesic_distance(pos, face, norm=False) expected = [ [0,",
"0]) dest = torch.tensor([0, 1, 2, 3]) out = geodesic_distance(pos,",
"dest=dest) expected = [0, 0, 0, 0] assert torch.allclose(out, torch.Tensor(expected))",
"2], [2 * sqrt(2), 2, 2, 0], ] assert torch.allclose(out,",
"torch.tensor(expected)) out = geodesic_distance(pos, face, dest=dest) expected = [0, 0,",
"[sqrt(2), 1, 1, 0], ] assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out,",
"[0, 1, 1, sqrt(2)], [1, 0, sqrt(2), 1], [1, sqrt(2),",
"* sqrt(2), 0, 2], [2 * sqrt(2), 2, 2, 0],",
"out = geodesic_distance(pos, face, norm=False) expected = [ [0, 2,",
"assert torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0, 0, 0, 0]) dest",
"[ [0, 2, 2, 2 * sqrt(2)], [2, 0, 2",
"sqrt(2), 1], [1, sqrt(2), 0, 1], [sqrt(2), 1, 1, 0],",
"sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, src=src[0:1]) expected",
"geodesic_distance(pos, face, src=src[0:1]) expected = [0, 1, 1, sqrt(2)] assert",
"def test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0], [2, 0, 0],",
"0], ] assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1))",
"import sqrt import torch from torch_geometric.utils import geodesic_distance def test_geodesic_distance():",
"2, 0], ] assert torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0, 0,",
"3], [0, 2, 3]]).t() out = geodesic_distance(pos, face) expected =",
"dest = torch.tensor([0, 1, 2, 3]) out = geodesic_distance(pos, face,",
"1, sqrt(2)], [1, 0, sqrt(2), 1], [1, sqrt(2), 0, 1],",
"assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos, face, num_workers=-1)) out =",
"torch from torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0,",
"sqrt(2), 2], [2, 2 * sqrt(2), 0, 2], [2 *",
"torch_geometric.utils import geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0],",
"2, 0], [2, 2, 0]]) face = torch.tensor([[0, 1, 3],",
"2, 3]) out = geodesic_distance(pos, face, src=src, dest=dest) expected =",
"pos = torch.Tensor([[0, 0, 0], [2, 0, 0], [0, 2,",
"= torch.tensor([0, 0, 0, 0]) dest = torch.tensor([0, 1, 2,",
"sqrt(2), 0, 1], [sqrt(2), 1, 1, 0], ] assert torch.allclose(out,",
"geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0], [2, 0,",
"face, num_workers=-1)) out = geodesic_distance(pos, face, norm=False) expected = [",
"= [0, 1, 1, sqrt(2)] assert torch.allclose(out, torch.tensor(expected)) out =",
"* sqrt(2)], [2, 0, 2 * sqrt(2), 2], [2, 2",
"= [ [0, 1, 1, sqrt(2)], [1, 0, sqrt(2), 1],",
"= [ [0, 2, 2, 2 * sqrt(2)], [2, 0,",
"face) expected = [ [0, 1, 1, sqrt(2)], [1, 0,",
"out = geodesic_distance(pos, face, src=src[0:1]) expected = [0, 1, 1,",
"0, 0, 0]) dest = torch.tensor([0, 1, 2, 3]) out",
"2, 2, 0], ] assert torch.allclose(out, torch.tensor(expected)) src = torch.tensor([0,",
"2 * sqrt(2), 2], [2, 2 * sqrt(2), 0, 2],",
"torch.tensor([[0, 1, 3], [0, 2, 3]]).t() out = geodesic_distance(pos, face)",
"import geodesic_distance def test_geodesic_distance(): pos = torch.Tensor([[0, 0, 0], [2,",
"1, 1, 0], ] assert torch.allclose(out, torch.tensor(expected)) assert torch.allclose(out, geodesic_distance(pos,",
"2], [2, 2 * sqrt(2), 0, 2], [2 * sqrt(2),",
"face = torch.tensor([[0, 1, 3], [0, 2, 3]]).t() out =",
"assert torch.allclose(out, torch.tensor(expected)) out = geodesic_distance(pos, face, src=src[0:1]) expected ="
] |