Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> if unit: unit = '<tr><td><b>%s</b>: </td><td>%s</td></tr>' % ( tr('Unit'), unit) description = """ <table border="0" width="100%%"> <tr><td><b>%s</b>: </td><td>%s</td></tr> <tr><td><b>%s</b>: </td><td>%s</td></tr> %s %s <tr><td><b>%s</b>: </td><td>%s</td></tr> </table> """ % (tr('Title'), keywords.get('title'), tr('Purpose'), keywords.get('layer_purpose'), subcategory, unit, tr('Source'), keywords.get('source')) elif keywords: # The layer has keywords, but the version is wrong layer_version = keyword_version or tr('No Version') description = tr( 'Your layer\'s keyword\'s version ({layer_version}) does not ' 'match with your InaSAFE version ({inasafe_version}). If you wish ' 'to use it as an exposure, hazard, or aggregation layer in an ' 'analysis, please update the keywords. Click Next if you want to ' 'assign keywords now.').format( layer_version=layer_version, inasafe_version=get_version()) else: # The layer is keywordless if is_point_layer(layer): <|code_end|> , generate the next line using the imports in this file: import logging import os import safe.gui.tools.wizard.wizard_strings from qgis.PyQt import QtCore from qgis.core import QgsCoordinateTransform, QgsProject from safe.common.version import get_version from safe.definitions.constants import RECENT, GLOBAL from safe.definitions.layer_modes import layer_mode_classified from safe.definitions.layer_purposes import ( layer_geometry_line, layer_geometry_point, layer_geometry_polygon) from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard) from safe.utilities.default_values import get_inasafe_default_value_qsetting from safe.utilities.gis import ( is_raster_layer, is_point_layer, is_polygon_layer) from safe.utilities.i18n import tr from safe.utilities.resources import resources_path from safe.utilities.utilities import is_keyword_version_supported and context (functions, classes, or occasionally code) from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
geom_type = layer_geometry_point['key']
Given the code snippet: <|code_start|> tr('Unit'), unit) description = """ <table border="0" width="100%%"> <tr><td><b>%s</b>: </td><td>%s</td></tr> <tr><td><b>%s</b>: </td><td>%s</td></tr> %s %s <tr><td><b>%s</b>: </td><td>%s</td></tr> </table> """ % (tr('Title'), keywords.get('title'), tr('Purpose'), keywords.get('layer_purpose'), subcategory, unit, tr('Source'), keywords.get('source')) elif keywords: # The layer has keywords, but the version is wrong layer_version = keyword_version or tr('No Version') description = tr( 'Your layer\'s keyword\'s version ({layer_version}) does not ' 'match with your InaSAFE version ({inasafe_version}). If you wish ' 'to use it as an exposure, hazard, or aggregation layer in an ' 'analysis, please update the keywords. Click Next if you want to ' 'assign keywords now.').format( layer_version=layer_version, inasafe_version=get_version()) else: # The layer is keywordless if is_point_layer(layer): geom_type = layer_geometry_point['key'] elif is_polygon_layer(layer): <|code_end|> , generate the next line using the imports in this file: import logging import os import safe.gui.tools.wizard.wizard_strings from qgis.PyQt import QtCore from qgis.core import QgsCoordinateTransform, QgsProject from safe.common.version import get_version from safe.definitions.constants import RECENT, GLOBAL from safe.definitions.layer_modes import layer_mode_classified from safe.definitions.layer_purposes import ( layer_geometry_line, layer_geometry_point, layer_geometry_polygon) from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard) from safe.utilities.default_values import get_inasafe_default_value_qsetting from safe.utilities.gis import ( is_raster_layer, is_point_layer, is_polygon_layer) from safe.utilities.i18n import tr from safe.utilities.resources import resources_path from safe.utilities.utilities import is_keyword_version_supported and context (functions, classes, or occasionally code) from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
geom_type = layer_geometry_polygon['key']
Using the snippet: <|code_start|> def layer_description_html(layer, keywords=None): """Form a html description of a given layer based on the layer parameters and keywords if provided :param layer: The layer to get the description :type layer: QgsMapLayer :param keywords: The layer keywords :type keywords: None, dict :returns: The html description in tabular format, ready to use in a label or tool tip. :rtype: str """ if keywords and 'keyword_version' in keywords: keyword_version = str(keywords['keyword_version']) else: keyword_version = None if (keywords and keyword_version and is_keyword_version_supported(keyword_version)): # The layer has valid keywords purpose = keywords.get('layer_purpose') if purpose == layer_purpose_hazard['key']: subcategory = '<tr><td><b>%s</b>: </td><td>%s</td></tr>' % ( tr('Hazard'), keywords.get(purpose)) unit = keywords.get('continuous_hazard_unit') <|code_end|> , determine the next line of code. You have imports: import logging import os import safe.gui.tools.wizard.wizard_strings from qgis.PyQt import QtCore from qgis.core import QgsCoordinateTransform, QgsProject from safe.common.version import get_version from safe.definitions.constants import RECENT, GLOBAL from safe.definitions.layer_modes import layer_mode_classified from safe.definitions.layer_purposes import ( layer_geometry_line, layer_geometry_point, layer_geometry_polygon) from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard) from safe.utilities.default_values import get_inasafe_default_value_qsetting from safe.utilities.gis import ( is_raster_layer, is_point_layer, is_polygon_layer) from safe.utilities.i18n import tr from safe.utilities.resources import resources_path from safe.utilities.utilities import is_keyword_version_supported and context (class names, function names, or code) available: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
elif purpose == layer_purpose_exposure['key']:
Predict the next line after this snippet: <|code_start|> extent_b = (coord_transform.transform( extent_b, QgsCoordinateTransform.ReverseTransform)) return extent_a.intersects(extent_b) def layer_description_html(layer, keywords=None): """Form a html description of a given layer based on the layer parameters and keywords if provided :param layer: The layer to get the description :type layer: QgsMapLayer :param keywords: The layer keywords :type keywords: None, dict :returns: The html description in tabular format, ready to use in a label or tool tip. :rtype: str """ if keywords and 'keyword_version' in keywords: keyword_version = str(keywords['keyword_version']) else: keyword_version = None if (keywords and keyword_version and is_keyword_version_supported(keyword_version)): # The layer has valid keywords purpose = keywords.get('layer_purpose') <|code_end|> using the current file's imports: import logging import os import safe.gui.tools.wizard.wizard_strings from qgis.PyQt import QtCore from qgis.core import QgsCoordinateTransform, QgsProject from safe.common.version import get_version from safe.definitions.constants import RECENT, GLOBAL from safe.definitions.layer_modes import layer_mode_classified from safe.definitions.layer_purposes import ( layer_geometry_line, layer_geometry_point, layer_geometry_polygon) from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard) from safe.utilities.default_values import get_inasafe_default_value_qsetting from safe.utilities.gis import ( is_raster_layer, is_point_layer, is_polygon_layer) from safe.utilities.i18n import tr from safe.utilities.resources import resources_path from safe.utilities.utilities import is_keyword_version_supported and any relevant context from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
if purpose == layer_purpose_hazard['key']:
Here is a snippet: <|code_start|> layer_purpose_nearby_places = { 'key': 'nearby_places', 'name': tr('Nearby Places'), 'description': tr('Lorem ipsum on the nearby places layers.'), 'allowed_geometries': [layer_geometry_point], 'citations': [ { 'text': None, 'link': None } ] } layer_purpose_earthquake_contour = { 'key': 'earthquake_contour', 'name': tr('Earthquake Contour'), 'description': tr('A contour of a hazard earthquake'), 'allowed_geometries': [layer_geometry_line], 'citations': [ { 'text': None, 'link': None } ] } layer_purpose = { 'key': 'layer_purpose', 'name': tr('Purpose'), <|code_end|> . Write the next line using the current file imports: from safe.definitions.concepts import concepts from safe.definitions.field_groups import aggregation_field_groups from safe.definitions.keyword_properties import property_layer_purpose from safe.definitions.layer_geometry import ( layer_geometry_raster, layer_geometry_line, layer_geometry_point, layer_geometry_polygon ) from safe.utilities.i18n import tr and context from other files: # Path: safe/definitions/keyword_properties.py , which may include functions, classes, or code. Output only the next line.
'description': property_layer_purpose['description'],
Continue the code snippet: <|code_start|> should accept params 'current' (int), 'maximum' (int) and 'step' (str). Defaults to None. :type callback: function :return: The buffered vector layer. :rtype: QgsVectorLayer """ # Layer output output_layer_name = buffer_steps['output_layer_name'] processing_step = buffer_steps['step_name'] input_crs = layer.crs() feature_count = layer.featureCount() fields = layer.fields() # Set the new hazard class field. new_field = create_field_from_definition(hazard_class_field) fields.append(new_field) # Set the new buffer distances field. new_field = create_field_from_definition(buffer_distance_field) fields.append(new_field) buffered = create_memory_layer( output_layer_name, QgsWkbTypes.PolygonGeometry, input_crs, fields) buffered.startEditing() # Reproject features if needed into UTM if the layer is in 4326. if layer.crs().authid() == 'EPSG:4326': center = layer.extent().center() utm = QgsCoordinateReferenceSystem( <|code_end|> . Use current file imports: from qgis.core import ( QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsGeometry, QgsFeature, QgsWkbTypes, ) from safe.common.utilities import get_utm_epsg from safe.definitions.fields import hazard_class_field, buffer_distance_field from safe.definitions.layer_purposes import layer_purpose_hazard from safe.definitions.processing_steps import buffer_steps from safe.gis.sanity_check import check_layer from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition) from safe.utilities.profiling import profile and context (classes, functions, or code) from other files: # Path: safe/common/utilities.py # def get_utm_epsg(longitude, latitude, crs=None): # """Return epsg code of the utm zone according to X, Y coordinates. # # By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will # be reprojected from the input CRS to WGS84. # # The code is based on the code: # http://gis.stackexchange.com/questions/34401 # # :param longitude: The longitude. # :type longitude: float # # :param latitude: The latitude. # :type latitude: float # # :param crs: The coordinate reference system of the latitude, longitude. # :type crs: QgsCoordinateReferenceSystem # """ # if crs is None or crs.authid() == 'EPSG:4326': # epsg = 32600 # if latitude < 0.0: # epsg += 100 # epsg += get_utm_zone(longitude) # return epsg # else: # epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326') # transform = QgsCoordinateTransform( # crs, epsg_4326, QgsProject.instance()) # geom = QgsGeometry.fromPointXY(QgsPointXY(longitude, latitude)) # geom.transform(transform) # point = geom.asPoint() # # The point is now in 4326, we can call the function again. # return get_utm_epsg(point.x(), point.y()) # # Path: safe/definitions/layer_purposes.py . Output only the next line.
get_utm_epsg(center.x(), center.y(), input_crs))
Next line prediction: <|code_start|> # We add the hazard value name to the attribute table. attributes.append(radii[radius]) # We add the value of buffer distance to the attribute table. attributes.append(radius) circle = geom.buffer(radius, 30) if inner_ring: circle.addRing(inner_ring) inner_ring = circle.asPolygon()[0] new_feature = QgsFeature() if reverse_transform: circle.transform(reverse_transform) new_feature.setGeometry(circle) new_feature.setAttributes(attributes) buffered.addFeature(new_feature) if callback: callback(current=i, maximum=feature_count, step=processing_step) buffered.commitChanges() # We transfer keywords to the output. buffered.keywords = layer.keywords buffered.keywords['layer_geometry'] = 'polygon' <|code_end|> . Use current file imports: (from qgis.core import ( QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsGeometry, QgsFeature, QgsWkbTypes, ) from safe.common.utilities import get_utm_epsg from safe.definitions.fields import hazard_class_field, buffer_distance_field from safe.definitions.layer_purposes import layer_purpose_hazard from safe.definitions.processing_steps import buffer_steps from safe.gis.sanity_check import check_layer from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition) from safe.utilities.profiling import profile) and context including class names, function names, or small code snippets from other files: # Path: safe/common/utilities.py # def get_utm_epsg(longitude, latitude, crs=None): # """Return epsg code of the utm zone according to X, Y coordinates. # # By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will # be reprojected from the input CRS to WGS84. # # The code is based on the code: # http://gis.stackexchange.com/questions/34401 # # :param longitude: The longitude. # :type longitude: float # # :param latitude: The latitude. # :type latitude: float # # :param crs: The coordinate reference system of the latitude, longitude. # :type crs: QgsCoordinateReferenceSystem # """ # if crs is None or crs.authid() == 'EPSG:4326': # epsg = 32600 # if latitude < 0.0: # epsg += 100 # epsg += get_utm_zone(longitude) # return epsg # else: # epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326') # transform = QgsCoordinateTransform( # crs, epsg_4326, QgsProject.instance()) # geom = QgsGeometry.fromPointXY(QgsPointXY(longitude, latitude)) # geom.transform(transform) # point = geom.asPoint() # # The point is now in 4326, we can call the function again. # return get_utm_epsg(point.x(), point.y()) # # Path: safe/definitions/layer_purposes.py . Output only the next line.
buffered.keywords['layer_purpose'] = layer_purpose_hazard['key']
Next line prediction: <|code_start|>__license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' class TestMultiBuffering(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_multi_buffer_points(self): """Test we can multi buffer points such as volcano points.""" radii = OrderedDict() radii[500] = 'high' radii[1000] = 'medium' radii[2000] = 'low' # Let's add a vector layer. layer = load_test_vector_layer('hazard', 'volcano_point.geojson') keywords = layer.keywords self.assertEqual(layer.keywords['layer_geometry'], 'point') expected_keywords = keywords.copy() expected_keywords['layer_geometry'] = 'polygon' expected_name_field = hazard_class_field['field_name'] expected_keywords['inasafe_fields'][hazard_class_field['key']] = ( expected_name_field) <|code_end|> . Use current file imports: (import unittest from collections import OrderedDict from safe.definitions.constants import INASAFE_TEST from safe.test.utilities import ( get_qgis_app, load_test_vector_layer) from qgis.core import QgsWkbTypes from safe.gis.vector.multi_buffering import multi_buffering from safe.definitions.fields import hazard_class_field, buffer_distance_field) and context including class names, function names, or small code snippets from other files: # Path: safe/gis/vector/multi_buffering.py # @profile # def multi_buffering(layer, radii, callback=None): # """Buffer a vector layer using many buffers (for volcanoes or rivers). # # This processing algorithm will keep the original attribute table and # will add a new one for the hazard class name according to # safe.definitions.fields.hazard_value_field. # # radii = OrderedDict() # radii[500] = 'high' # radii[1000] = 'medium' # radii[2000] = 'low' # # Issue https://github.com/inasafe/inasafe/issues/3185 # # :param layer: The layer to polygonize. # :type layer: QgsVectorLayer # # :param radii: A dictionary of radius. # :type radii: OrderedDict # # :param callback: A function to all to indicate progress. The function # should accept params 'current' (int), 'maximum' (int) and 'step' (str). # Defaults to None. # :type callback: function # # :return: The buffered vector layer. # :rtype: QgsVectorLayer # """ # # Layer output # output_layer_name = buffer_steps['output_layer_name'] # processing_step = buffer_steps['step_name'] # # input_crs = layer.crs() # feature_count = layer.featureCount() # # fields = layer.fields() # # Set the new hazard class field. # new_field = create_field_from_definition(hazard_class_field) # fields.append(new_field) # # Set the new buffer distances field. # new_field = create_field_from_definition(buffer_distance_field) # fields.append(new_field) # # buffered = create_memory_layer( # output_layer_name, QgsWkbTypes.PolygonGeometry, input_crs, fields) # buffered.startEditing() # # # Reproject features if needed into UTM if the layer is in 4326. # if layer.crs().authid() == 'EPSG:4326': # center = layer.extent().center() # utm = QgsCoordinateReferenceSystem( # get_utm_epsg(center.x(), center.y(), input_crs)) # transform = QgsCoordinateTransform( # layer.crs(), utm, QgsProject.instance()) # reverse_transform = QgsCoordinateTransform( # utm, layer.crs(), QgsProject.instance()) # else: # transform = None # reverse_transform = None # # for i, feature in enumerate(layer.getFeatures()): # geom = QgsGeometry(feature.geometry()) # # if transform: # geom.transform(transform) # # inner_ring = None # # for radius in radii: # attributes = feature.attributes() # # # We add the hazard value name to the attribute table. # attributes.append(radii[radius]) # # We add the value of buffer distance to the attribute table. # attributes.append(radius) # # circle = geom.buffer(radius, 30) # # if inner_ring: # circle.addRing(inner_ring) # # inner_ring = circle.asPolygon()[0] # # new_feature = QgsFeature() # if reverse_transform: # circle.transform(reverse_transform) # # new_feature.setGeometry(circle) # new_feature.setAttributes(attributes) # # buffered.addFeature(new_feature) # # if callback: # callback(current=i, maximum=feature_count, step=processing_step) # # buffered.commitChanges() # # # We transfer keywords to the output. # buffered.keywords = layer.keywords # buffered.keywords['layer_geometry'] = 'polygon' # buffered.keywords['layer_purpose'] = layer_purpose_hazard['key'] # buffered.keywords['inasafe_fields'][hazard_class_field['key']] = ( # hazard_class_field['field_name']) # # check_layer(buffered) # return buffered . Output only the next line.
result = multi_buffering(
Predict the next line after this snippet: <|code_start|> analysis_layer.keywords[inasafe_keyword_version_key] = ( inasafe_keyword_version) analysis_layer.keywords['inasafe_fields'] = { analysis_name_field['key']: analysis_name_field['field_name'] } return analysis_layer def create_profile_layer(profiling): """Create a tabular layer with the profiling. :param profiling: A dict containing benchmarking data. :type profiling: safe.messaging.message.Message :return: A tabular layer. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(profiling_function_field), create_field_from_definition(profiling_time_field) ] if setting(key='memory_profile', expected_type=bool): fields.append(create_field_from_definition(profiling_memory_field)) tabular = create_memory_layer( 'profiling', QgsWkbTypes.NullGeometry, fields=fields) # Generate profiling keywords <|code_end|> using the current file's imports: import logging from qgis.core import ( QgsFeature, QgsWkbTypes, ) from safe.definitions.constants import inasafe_keyword_version_key from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, analysis_name_field, profiling_function_field, profiling_time_field, profiling_memory_field ) from safe.definitions.layer_purposes import ( layer_purpose_profiling, layer_purpose_aggregation, layer_purpose_analysis_impacted, ) from safe.definitions.versions import inasafe_keyword_version from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition, copy_layer) from safe.utilities.gis import qgis_version from safe.utilities.i18n import tr from safe.utilities.profiling import profile from safe.utilities.settings import setting and any relevant context from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/versions.py . Output only the next line.
tabular.keywords['layer_purpose'] = layer_purpose_profiling['key']
Given the following code snippet before the placeholder: <|code_start|>@profile def create_virtual_aggregation(geometry, crs): """Function to create aggregation layer based on extent. :param geometry: The geometry to use as an extent. :type geometry: QgsGeometry :param crs: The Coordinate Reference System to use for the layer. :type crs: QgsCoordinateReferenceSystem :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(aggregation_id_field), create_field_from_definition(aggregation_name_field) ] aggregation_layer = create_memory_layer( 'aggregation', QgsWkbTypes.PolygonGeometry, crs, fields) aggregation_layer.startEditing() feature = QgsFeature() feature.setGeometry(geometry) feature.setAttributes([1, tr('Entire Area')]) aggregation_layer.addFeature(feature) aggregation_layer.commitChanges() # Generate aggregation keywords aggregation_layer.keywords['layer_purpose'] = ( <|code_end|> , predict the next line using imports from the current file: import logging from qgis.core import ( QgsFeature, QgsWkbTypes, ) from safe.definitions.constants import inasafe_keyword_version_key from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, analysis_name_field, profiling_function_field, profiling_time_field, profiling_memory_field ) from safe.definitions.layer_purposes import ( layer_purpose_profiling, layer_purpose_aggregation, layer_purpose_analysis_impacted, ) from safe.definitions.versions import inasafe_keyword_version from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition, copy_layer) from safe.utilities.gis import qgis_version from safe.utilities.i18n import tr from safe.utilities.profiling import profile from safe.utilities.settings import setting and context including class names, function names, and sometimes code from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/versions.py . Output only the next line.
layer_purpose_aggregation['key'])
Given the code snippet: <|code_start|> :param analysis_extent: The analysis extent. :type analysis_extent: QgsGeometry :param crs: The CRS to use. :type crs: QgsCoordinateReferenceSystem :param name: The name of the analysis. :type name: basestring :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(analysis_name_field) ] analysis_layer = create_memory_layer( 'analysis', QgsWkbTypes.PolygonGeometry, crs, fields) analysis_layer.startEditing() feature = QgsFeature() # noinspection PyCallByClass,PyArgumentList,PyTypeChecker feature.setGeometry(analysis_extent) feature.setAttributes([name]) analysis_layer.addFeature(feature) analysis_layer.commitChanges() # Generate analysis keywords analysis_layer.keywords['layer_purpose'] = ( <|code_end|> , generate the next line using the imports in this file: import logging from qgis.core import ( QgsFeature, QgsWkbTypes, ) from safe.definitions.constants import inasafe_keyword_version_key from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, analysis_name_field, profiling_function_field, profiling_time_field, profiling_memory_field ) from safe.definitions.layer_purposes import ( layer_purpose_profiling, layer_purpose_aggregation, layer_purpose_analysis_impacted, ) from safe.definitions.versions import inasafe_keyword_version from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition, copy_layer) from safe.utilities.gis import qgis_version from safe.utilities.i18n import tr from safe.utilities.profiling import profile from safe.utilities.settings import setting and context (functions, classes, or occasionally code) from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/versions.py . Output only the next line.
layer_purpose_analysis_impacted['key'])
Continue the code snippet: <|code_start|> :param geometry: The geometry to use as an extent. :type geometry: QgsGeometry :param crs: The Coordinate Reference System to use for the layer. :type crs: QgsCoordinateReferenceSystem :returns: A polygon layer with exposure's crs. :rtype: QgsVectorLayer """ fields = [ create_field_from_definition(aggregation_id_field), create_field_from_definition(aggregation_name_field) ] aggregation_layer = create_memory_layer( 'aggregation', QgsWkbTypes.PolygonGeometry, crs, fields) aggregation_layer.startEditing() feature = QgsFeature() feature.setGeometry(geometry) feature.setAttributes([1, tr('Entire Area')]) aggregation_layer.addFeature(feature) aggregation_layer.commitChanges() # Generate aggregation keywords aggregation_layer.keywords['layer_purpose'] = ( layer_purpose_aggregation['key']) aggregation_layer.keywords['title'] = 'aggr_from_bbox' aggregation_layer.keywords[inasafe_keyword_version_key] = ( <|code_end|> . Use current file imports: import logging from qgis.core import ( QgsFeature, QgsWkbTypes, ) from safe.definitions.constants import inasafe_keyword_version_key from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, analysis_name_field, profiling_function_field, profiling_time_field, profiling_memory_field ) from safe.definitions.layer_purposes import ( layer_purpose_profiling, layer_purpose_aggregation, layer_purpose_analysis_impacted, ) from safe.definitions.versions import inasafe_keyword_version from safe.gis.vector.tools import ( create_memory_layer, create_field_from_definition, copy_layer) from safe.utilities.gis import qgis_version from safe.utilities.i18n import tr from safe.utilities.profiling import profile from safe.utilities.settings import setting and context (classes, functions, or code) from other files: # Path: safe/definitions/layer_purposes.py # # Path: safe/definitions/versions.py . Output only the next line.
inasafe_keyword_version)
Given snippet: <|code_start|> msg = '%s not found in %s' % ( size_field['key'], layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) indexes = [] absolute_field_keys = [f['key'] for f in count_fields] for field, field_name in list(fields.items()): if field in absolute_field_keys and field != size_field['key']: indexes.append(layer.fields().lookupField(field_name)) LOGGER.info( 'We detected the count {field_name}, we will recompute the ' 'count according to the new size.'.format( field_name=field_name)) if not len(indexes): msg = 'Absolute field not found in the layer %s' % ( layer.keywords['title']) raise InvalidKeywordsForProcessingAlgorithm(msg) size_field_name = fields[size_field['key']] size_field_index = layer.fields().lookupField(size_field_name) layer.startEditing() exposure_key = layer.keywords['exposure_keywords']['exposure'] size_calculator = SizeCalculator( layer.crs(), layer.geometryType(), exposure_key) for feature in layer.getFeatures(): old_size = feature[size_field_name] <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from safe.common.exceptions import InvalidKeywordsForProcessingAlgorithm from safe.definitions.fields import ( size_field, count_fields, ) from safe.definitions.processing_steps import ( recompute_counts_steps) from safe.gis.sanity_check import check_layer from safe.gis.vector.tools import SizeCalculator from safe.processors.post_processor_functions import size from safe.utilities.profiling import profile and context: # Path: safe/processors/post_processor_functions.py # def size(size_calculator, geometry): # """Simple postprocessor where we compute the size of a feature. # # :param geometry: The geometry. # :type geometry: QgsGeometry # # :param size_calculator: The size calculator. # :type size_calculator: safe.gis.vector.tools.SizeCalculator # # :return: The size. # """ # feature_size = size_calculator.measure(geometry) # return feature_size which might include code, classes, or functions. Output only the next line.
new_size = size(
Given the code snippet: <|code_start|> 'key': 'earthquake_mmi_scale', 'name': tr('Earthquake MMI scale'), 'description': tr( 'This scale, composed of increasing levels of intensity that range ' 'from imperceptible shaking to catastrophic destruction, is ' 'designated by Roman numerals. It does not have a mathematical ' 'basis; instead it is an arbitrary ranking based on observed ' 'effects. Note that fatality rates listed here are based on the ' 'active earthquake fatality model (currently set to %s). Users ' 'can select the active earthquake fatality model in InaSAFE ' 'Options.' % current_earthquake_model_name()), 'type': hazard_classification_type, 'citations': [ { 'text': None, 'link': None } ], 'classes': [ { 'key': 'X', 'value': 10, 'color': MMI_10, 'name': tr('X'), 'affected': True, 'description': tr('Some well-built wooden structures destroyed; most masonry ' 'and frame structures destroyed with foundations. ' 'Rails bent.'), 'string_defaults': ['extreme'], <|code_end|> , generate the next line using the imports in this file: from safe.definitions import concepts from safe.definitions.constants import big_number from safe.definitions.earthquake import ( earthquake_fatality_rate, current_earthquake_model_name) from safe.definitions.exposure import ( exposure_land_cover, exposure_place, exposure_population, exposure_road, exposure_structure) from safe.definitions.styles import ( grey, green, light_green, yellow, orange, red, dark_red, very_dark_red, MMI_10, MMI_9, MMI_8, MMI_7, MMI_6, MMI_5, MMI_4, MMI_3, MMI_2, MMI_1) from safe.definitions.units import ( unit_centimetres, unit_miles_per_hour, unit_kilometres_per_hour, unit_knots, unit_metres_per_second ) from safe.utilities.i18n import tr and context (functions, classes, or occasionally code) from other files: # Path: safe/definitions/earthquake.py # def earthquake_fatality_rate(hazard_level): # """Earthquake fatality ratio for a given hazard level. # # It reads the QGIS QSettings to know what is the default earthquake # function. # # :param hazard_level: The hazard level. # :type hazard_level: int # # :return: The fatality rate. # :rtype: float # """ # earthquake_function = setting( # 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) # ratio = 0 # for model in EARTHQUAKE_FUNCTIONS: # if model['key'] == earthquake_function: # eq_function = model['fatality_rates'] # ratio = eq_function().get(hazard_level) # return ratio # # def current_earthquake_model_name(): # """Human friendly name for the currently active earthquake fatality model. # # :returns: Name of the current EQ fatality model as defined in users # settings. # """ # default_earthquake_function = setting( # 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) # current_function = None # for model in EARTHQUAKE_FUNCTIONS: # if model['key'] == default_earthquake_function: # current_function = model['name'] # return current_function . Output only the next line.
'fatality_rate': earthquake_fatality_rate(10),
Next line prediction: <|code_start|> 'numeric_default_max': 2, 'citations': [ { 'text': None, 'link': None } ], } ], 'exposures': [ exposure_land_cover, exposure_place, exposure_population, exposure_road, exposure_structure ], 'classification_unit': tr('hazard zone') } earthquake_mmi_scale = { 'key': 'earthquake_mmi_scale', 'name': tr('Earthquake MMI scale'), 'description': tr( 'This scale, composed of increasing levels of intensity that range ' 'from imperceptible shaking to catastrophic destruction, is ' 'designated by Roman numerals. It does not have a mathematical ' 'basis; instead it is an arbitrary ranking based on observed ' 'effects. Note that fatality rates listed here are based on the ' 'active earthquake fatality model (currently set to %s). Users ' 'can select the active earthquake fatality model in InaSAFE ' <|code_end|> . Use current file imports: (from safe.definitions import concepts from safe.definitions.constants import big_number from safe.definitions.earthquake import ( earthquake_fatality_rate, current_earthquake_model_name) from safe.definitions.exposure import ( exposure_land_cover, exposure_place, exposure_population, exposure_road, exposure_structure) from safe.definitions.styles import ( grey, green, light_green, yellow, orange, red, dark_red, very_dark_red, MMI_10, MMI_9, MMI_8, MMI_7, MMI_6, MMI_5, MMI_4, MMI_3, MMI_2, MMI_1) from safe.definitions.units import ( unit_centimetres, unit_miles_per_hour, unit_kilometres_per_hour, unit_knots, unit_metres_per_second ) from safe.utilities.i18n import tr) and context including class names, function names, or small code snippets from other files: # Path: safe/definitions/earthquake.py # def earthquake_fatality_rate(hazard_level): # """Earthquake fatality ratio for a given hazard level. # # It reads the QGIS QSettings to know what is the default earthquake # function. # # :param hazard_level: The hazard level. # :type hazard_level: int # # :return: The fatality rate. # :rtype: float # """ # earthquake_function = setting( # 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) # ratio = 0 # for model in EARTHQUAKE_FUNCTIONS: # if model['key'] == earthquake_function: # eq_function = model['fatality_rates'] # ratio = eq_function().get(hazard_level) # return ratio # # def current_earthquake_model_name(): # """Human friendly name for the currently active earthquake fatality model. # # :returns: Name of the current EQ fatality model as defined in users # settings. # """ # default_earthquake_function = setting( # 'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'], str) # current_function = None # for model in EARTHQUAKE_FUNCTIONS: # if model['key'] == default_earthquake_function: # current_function = model['name'] # return current_function . Output only the next line.
'Options.' % current_earthquake_model_name()),
Given the code snippet: <|code_start|> summary_field['field_name']) # Only add absolute value if there is no summarization / no exposure # classification if not summarization_dicts: # For each absolute values for absolute_field in list(absolute_values.keys()): field_definition = definition(absolute_values[absolute_field][1]) field = create_field_from_definition(field_definition) tabular.addAttribute(field) key = field_definition['key'] value = field_definition['field_name'] tabular.keywords['inasafe_fields'][key] = value for exposure_type in unique_exposure: feature = QgsFeature() attributes = [exposure_type] total_affected = 0 total_not_affected = 0 total_not_exposed = 0 total = 0 for hazard_class in unique_hazard: if hazard_class == '' or hazard_class is None: hazard_class = 'NULL' value = flat_table.get_value( hazard_class=hazard_class, exposure_class=exposure_type ) attributes.append(value) <|code_end|> , generate the next line using the imports in this file: from numbers import Number from qgis.core import QgsWkbTypes, QgsFeatureRequest, QgsFeature from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, hazard_id_field, hazard_class_field, exposure_type_field, total_affected_field, total_not_affected_field, total_not_exposed_field, total_field, affected_field, hazard_count_field, exposure_count_field, exposure_class_field, summary_rules, ) from safe.definitions.hazard_classifications import not_exposed_class from safe.definitions.layer_purposes import \ layer_purpose_exposure_summary_table from safe.definitions.processing_steps import ( summary_4_exposure_summary_table_steps) from safe.definitions.utilities import definition from safe.gis.sanity_check import check_layer from safe.gis.vector.summary_tools import ( check_inputs, create_absolute_values_structure) from safe.gis.vector.tools import ( create_field_from_definition, read_dynamic_inasafe_field, create_memory_layer) from safe.processors import post_processor_affected_function from safe.utilities.gis import qgis_version from safe.utilities.pivot_table import FlatTable from safe.utilities.profiling import profile and context (functions, classes, or occasionally code) from other files: # Path: safe/definitions/hazard_classifications.py # # Path: safe/definitions/layer_purposes.py # # Path: safe/utilities/pivot_table.py # class FlatTable(): # """ Flat table object - used as a source of data for pivot tables. # After constructing the object, repeatedly call "add_value" method # for each row of the input table. FlatTable stores only fields # that are important for the creation of pivot tables later. It also # aggregates values of rows where specified fields have the same value, # saving memory by not storing all source data. # # An example of use for the flat table - afterwards it can be converted # into a pivot table: # # flat_table = FlatTable('hazard_type', 'road_type', 'district') # # for f in layer.getFeatures(): # flat_table.add_value( # f.geometry().length(), # hazard_type=f['hazard'], # road_type=f['road'], # zone=f['zone']) # """ # # def __init__(self, *args): # """ Construct flat table, fields are passed""" # self.groups = args # self.data = {} # # Store keys, allowing for consistent ordered # self.data_keys = [] # # def add_value(self, value, **kwargs): # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # self.data_keys.append(key) # self.data[key] += value # # def get_value(self, **kwargs): # """Return the value for a specific key.""" # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # return self.data[key] # # def group_values(self, group_name): # """Return all distinct group values for given group.""" # group_index = self.groups.index(group_name) # values = [] # for key in self.data_keys: # if key[group_index] not in values: # values.append(key[group_index]) # return values # # def to_json(self): # """Return json representation of FlatTable # # :returns: JSON string. # :rtype: str # """ # return json.dumps(self.to_dict()) # # def from_json(self, json_string): # """Override current FlatTable using data from json. # # :param json_string: JSON String # :type json_string: str # """ # # obj = json.loads(json_string) # self.from_dict(obj['groups'], obj['data']) # # return self # # def to_dict(self): # """Return common list python object. # :returns: Dictionary of groups and data # :rtype: dict # """ # list_data = [] # for key, value in list(self.data.items()): # row = list(key) # row.append(value) # list_data.append(row) # return { # 'groups': self.groups, # 'data': list_data # } # # def from_dict(self, groups, data): # """Populate FlatTable based on groups and data. # # :param groups: List of group name. # :type groups: list # # :param data: Dictionary of raw table. # :type data: list # # example of groups: ["road_type", "hazard"] # example of data: [ # ["residential", "low", 50], # ["residential", "medium", 30], # ["secondary", "low", 40], # ["primary", "high", 10], # ["primary", "medium", 20] # ] # """ # self.groups = tuple(groups) # for item in data: # kwargs = {} # for i in range(len(self.groups)): # kwargs[self.groups[i]] = item[i] # self.add_value(item[-1], **kwargs) # # return self . Output only the next line.
if hazard_affected[hazard_class] == not_exposed_class['key']:
Given the following code snippet before the placeholder: <|code_start|> total += value attributes.append(total_affected) attributes.append(total_not_affected) attributes.append(total_not_exposed) attributes.append(total) if summarization_dicts: for key in sorted_keys: attributes.append(summarization_dicts[key].get( exposure_type, 0)) else: for i, field in enumerate(absolute_values.values()): value = field[0].get_value( all='all' ) attributes.append(value) feature.setAttributes(attributes) tabular.addFeature(feature) # Sanity check ± 1 to the result. Disabled for now as it seems ± 1 is # not enough. ET 13/02/17 # total_computed = ( # total_affected + total_not_affected + total_not_exposed) # if not -1 < (total_computed - total) < 1: # raise ComputationError tabular.commitChanges() <|code_end|> , predict the next line using imports from the current file: from numbers import Number from qgis.core import QgsWkbTypes, QgsFeatureRequest, QgsFeature from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, hazard_id_field, hazard_class_field, exposure_type_field, total_affected_field, total_not_affected_field, total_not_exposed_field, total_field, affected_field, hazard_count_field, exposure_count_field, exposure_class_field, summary_rules, ) from safe.definitions.hazard_classifications import not_exposed_class from safe.definitions.layer_purposes import \ layer_purpose_exposure_summary_table from safe.definitions.processing_steps import ( summary_4_exposure_summary_table_steps) from safe.definitions.utilities import definition from safe.gis.sanity_check import check_layer from safe.gis.vector.summary_tools import ( check_inputs, create_absolute_values_structure) from safe.gis.vector.tools import ( create_field_from_definition, read_dynamic_inasafe_field, create_memory_layer) from safe.processors import post_processor_affected_function from safe.utilities.gis import qgis_version from safe.utilities.pivot_table import FlatTable from safe.utilities.profiling import profile and context including class names, function names, and sometimes code from other files: # Path: safe/definitions/hazard_classifications.py # # Path: safe/definitions/layer_purposes.py # # Path: safe/utilities/pivot_table.py # class FlatTable(): # """ Flat table object - used as a source of data for pivot tables. # After constructing the object, repeatedly call "add_value" method # for each row of the input table. FlatTable stores only fields # that are important for the creation of pivot tables later. It also # aggregates values of rows where specified fields have the same value, # saving memory by not storing all source data. # # An example of use for the flat table - afterwards it can be converted # into a pivot table: # # flat_table = FlatTable('hazard_type', 'road_type', 'district') # # for f in layer.getFeatures(): # flat_table.add_value( # f.geometry().length(), # hazard_type=f['hazard'], # road_type=f['road'], # zone=f['zone']) # """ # # def __init__(self, *args): # """ Construct flat table, fields are passed""" # self.groups = args # self.data = {} # # Store keys, allowing for consistent ordered # self.data_keys = [] # # def add_value(self, value, **kwargs): # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # self.data_keys.append(key) # self.data[key] += value # # def get_value(self, **kwargs): # """Return the value for a specific key.""" # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # return self.data[key] # # def group_values(self, group_name): # """Return all distinct group values for given group.""" # group_index = self.groups.index(group_name) # values = [] # for key in self.data_keys: # if key[group_index] not in values: # values.append(key[group_index]) # return values # # def to_json(self): # """Return json representation of FlatTable # # :returns: JSON string. # :rtype: str # """ # return json.dumps(self.to_dict()) # # def from_json(self, json_string): # """Override current FlatTable using data from json. # # :param json_string: JSON String # :type json_string: str # """ # # obj = json.loads(json_string) # self.from_dict(obj['groups'], obj['data']) # # return self # # def to_dict(self): # """Return common list python object. # :returns: Dictionary of groups and data # :rtype: dict # """ # list_data = [] # for key, value in list(self.data.items()): # row = list(key) # row.append(value) # list_data.append(row) # return { # 'groups': self.groups, # 'data': list_data # } # # def from_dict(self, groups, data): # """Populate FlatTable based on groups and data. # # :param groups: List of group name. # :type groups: list # # :param data: Dictionary of raw table. # :type data: list # # example of groups: ["road_type", "hazard"] # example of data: [ # ["residential", "low", 50], # ["residential", "medium", 30], # ["secondary", "low", 40], # ["primary", "high", 10], # ["primary", "medium", 20] # ] # """ # self.groups = tuple(groups) # for item in data: # kwargs = {} # for i in range(len(self.groups)): # kwargs[self.groups[i]] = item[i] # self.add_value(item[-1], **kwargs) # # return self . Output only the next line.
tabular.keywords['title'] = layer_purpose_exposure_summary_table['name']
Based on the snippet: <|code_start|> :return: The new tabular table, without geometry. :rtype: QgsVectorLayer .. versionadded:: 4.0 """ output_layer_name = summary_4_exposure_summary_table_steps[ 'output_layer_name'] source_fields = aggregate_hazard.keywords['inasafe_fields'] source_compulsory_fields = [ aggregation_id_field, aggregation_name_field, hazard_id_field, hazard_class_field, affected_field, total_field ] check_inputs(source_compulsory_fields, source_fields) absolute_values = create_absolute_values_structure( aggregate_hazard, ['all']) hazard_class = source_fields[hazard_class_field['key']] hazard_class_index = aggregate_hazard.fields().lookupField(hazard_class) unique_hazard = aggregate_hazard.uniqueValues(hazard_class_index) unique_exposure = read_dynamic_inasafe_field( source_fields, exposure_count_field) <|code_end|> , predict the immediate next line with the help of imports: from numbers import Number from qgis.core import QgsWkbTypes, QgsFeatureRequest, QgsFeature from safe.definitions.fields import ( aggregation_id_field, aggregation_name_field, hazard_id_field, hazard_class_field, exposure_type_field, total_affected_field, total_not_affected_field, total_not_exposed_field, total_field, affected_field, hazard_count_field, exposure_count_field, exposure_class_field, summary_rules, ) from safe.definitions.hazard_classifications import not_exposed_class from safe.definitions.layer_purposes import \ layer_purpose_exposure_summary_table from safe.definitions.processing_steps import ( summary_4_exposure_summary_table_steps) from safe.definitions.utilities import definition from safe.gis.sanity_check import check_layer from safe.gis.vector.summary_tools import ( check_inputs, create_absolute_values_structure) from safe.gis.vector.tools import ( create_field_from_definition, read_dynamic_inasafe_field, create_memory_layer) from safe.processors import post_processor_affected_function from safe.utilities.gis import qgis_version from safe.utilities.pivot_table import FlatTable from safe.utilities.profiling import profile and context (classes, functions, sometimes code) from other files: # Path: safe/definitions/hazard_classifications.py # # Path: safe/definitions/layer_purposes.py # # Path: safe/utilities/pivot_table.py # class FlatTable(): # """ Flat table object - used as a source of data for pivot tables. # After constructing the object, repeatedly call "add_value" method # for each row of the input table. FlatTable stores only fields # that are important for the creation of pivot tables later. It also # aggregates values of rows where specified fields have the same value, # saving memory by not storing all source data. # # An example of use for the flat table - afterwards it can be converted # into a pivot table: # # flat_table = FlatTable('hazard_type', 'road_type', 'district') # # for f in layer.getFeatures(): # flat_table.add_value( # f.geometry().length(), # hazard_type=f['hazard'], # road_type=f['road'], # zone=f['zone']) # """ # # def __init__(self, *args): # """ Construct flat table, fields are passed""" # self.groups = args # self.data = {} # # Store keys, allowing for consistent ordered # self.data_keys = [] # # def add_value(self, value, **kwargs): # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # self.data_keys.append(key) # self.data[key] += value # # def get_value(self, **kwargs): # """Return the value for a specific key.""" # key = tuple(kwargs[group] for group in self.groups) # if key not in self.data: # self.data[key] = 0 # return self.data[key] # # def group_values(self, group_name): # """Return all distinct group values for given group.""" # group_index = self.groups.index(group_name) # values = [] # for key in self.data_keys: # if key[group_index] not in values: # values.append(key[group_index]) # return values # # def to_json(self): # """Return json representation of FlatTable # # :returns: JSON string. # :rtype: str # """ # return json.dumps(self.to_dict()) # # def from_json(self, json_string): # """Override current FlatTable using data from json. # # :param json_string: JSON String # :type json_string: str # """ # # obj = json.loads(json_string) # self.from_dict(obj['groups'], obj['data']) # # return self # # def to_dict(self): # """Return common list python object. # :returns: Dictionary of groups and data # :rtype: dict # """ # list_data = [] # for key, value in list(self.data.items()): # row = list(key) # row.append(value) # list_data.append(row) # return { # 'groups': self.groups, # 'data': list_data # } # # def from_dict(self, groups, data): # """Populate FlatTable based on groups and data. # # :param groups: List of group name. # :type groups: list # # :param data: Dictionary of raw table. # :type data: list # # example of groups: ["road_type", "hazard"] # example of data: [ # ["residential", "low", 50], # ["residential", "medium", 30], # ["secondary", "low", 40], # ["primary", "high", 10], # ["primary", "medium", 20] # ] # """ # self.groups = tuple(groups) # for item in data: # kwargs = {} # for i in range(len(self.groups)): # kwargs[self.groups[i]] = item[i] # self.add_value(item[-1], **kwargs) # # return self . Output only the next line.
flat_table = FlatTable('hazard_class', 'exposure_class')
Continue the code snippet: <|code_start|> self.action_multi_exposure = None self.action_function_centric_wizard = None self.action_import_dialog = None self.action_keywords_wizard = None self.action_minimum_needs = None self.action_minimum_needs_config = None self.action_multi_buffer = None self.action_options = None self.action_run_tests = None self.action_save_scenario = None self.action_shake_converter = None self.action_show_definitions = None self.action_toggle_rubberbands = None self.action_metadata_converter = None self.translator = None self.toolbar = None self.wizard = None self.actions = [] # list of all QActions we create for InaSAFE self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) developer_mode = setting( 'developer_mode', False, expected_type=bool) self.hide_developer_buttons = ( <|code_end|> . Use current file imports: import sys import os import qgis # NOQA pylint: disable=unused-import from functools import partial from distutils.version import StrictVersion from qgis.core import ( QgsRectangle, QgsRasterLayer, QgsMapLayer, QgsExpression, QgsProject, ) from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis.PyQt.QtWidgets import ( QAction, QApplication, QToolButton, QMenu, QLineEdit, QInputDialog ) from qgis.PyQt.QtGui import QIcon from safe.common.custom_logging import LOGGER from safe.utilities.expressions import qgis_expressions from safe.definitions.versions import inasafe_release_status, inasafe_version from safe.common.exceptions import ( KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError, ) from safe.common.signals import send_static_message from safe.utilities.resources import resources_path from safe.utilities.gis import is_raster_layer from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard ) from safe.definitions.utilities import get_field_groups from safe.utilities.i18n import tr from safe.utilities.keyword_io import KeywordIO from safe.utilities.utilities import is_keyword_version_supported from safe.utilities.settings import setting, set_setting from safe.gui.widgets.dock import Dock from safe.test.utilities import load_standard_layers from qgis.PyQt.QtWidgets import QDockWidget from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.widgets.message import getting_started_message from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog from safe.utilities.help import show_help from safe.gui.tools.help import definitions_help from safe.gui.tools.field_mapping_dialog import FieldMappingDialog from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog from safe.gui.tools.batch.batch_dialog import BatchDialog from safe.gui.tools.save_scenario import SaveScenarioDialog and context (classes, functions, or code) from other files: # Path: safe/definitions/versions.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
inasafe_release_status == 'final' and not developer_mode)
Predict the next line for this snippet: <|code_start|> # import here only so that it is AFTER i18n set up dialog = NeedsManagerDialog( parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up dialog = OptionsDialog( iface=self.iface, parent=self.iface.mainWindow()) dialog.show_option_dialog() if dialog.exec_(): # modal self.dock_widget.read_settings() send_static_message(self.dock_widget, getting_started_message()) # Issue #4734, make sure to update the combobox after update the # InaSAFE option self.dock_widget.get_layers() def show_welcome_message(self): """Show the welcome message.""" # import here only so that it is AFTER i18n set up # Do not show by default show_message = False previous_version = StrictVersion(setting('previous_version')) <|code_end|> with the help of current file imports: import sys import os import qgis # NOQA pylint: disable=unused-import from functools import partial from distutils.version import StrictVersion from qgis.core import ( QgsRectangle, QgsRasterLayer, QgsMapLayer, QgsExpression, QgsProject, ) from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis.PyQt.QtWidgets import ( QAction, QApplication, QToolButton, QMenu, QLineEdit, QInputDialog ) from qgis.PyQt.QtGui import QIcon from safe.common.custom_logging import LOGGER from safe.utilities.expressions import qgis_expressions from safe.definitions.versions import inasafe_release_status, inasafe_version from safe.common.exceptions import ( KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError, ) from safe.common.signals import send_static_message from safe.utilities.resources import resources_path from safe.utilities.gis import is_raster_layer from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard ) from safe.definitions.utilities import get_field_groups from safe.utilities.i18n import tr from safe.utilities.keyword_io import KeywordIO from safe.utilities.utilities import is_keyword_version_supported from safe.utilities.settings import setting, set_setting from safe.gui.widgets.dock import Dock from safe.test.utilities import load_standard_layers from qgis.PyQt.QtWidgets import QDockWidget from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.widgets.message import getting_started_message from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog from safe.utilities.help import show_help from safe.gui.tools.help import definitions_help from safe.gui.tools.field_mapping_dialog import FieldMappingDialog from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog from safe.gui.tools.batch.batch_dialog import BatchDialog from safe.gui.tools.save_scenario import SaveScenarioDialog and context from other files: # Path: safe/definitions/versions.py # # Path: safe/definitions/layer_purposes.py , which may contain function names, class names, or code. Output only the next line.
current_version = StrictVersion(inasafe_version)
Predict the next line after this snippet: <|code_start|> """ if not layer: enable_keyword_wizard = False elif not hasattr(layer, 'providerType'): enable_keyword_wizard = False elif layer.providerType() == 'wms': enable_keyword_wizard = False else: enable_keyword_wizard = True try: if layer: if is_raster_layer(layer): enable_field_mapping_tool = False else: keywords = KeywordIO().read_keywords(layer) keywords_version = keywords.get('keyword_version') if not keywords_version: supported = False else: supported = ( is_keyword_version_supported(keywords_version)) if not supported: enable_field_mapping_tool = False else: layer_purpose = keywords.get('layer_purpose') if not layer_purpose: enable_field_mapping_tool = False else: <|code_end|> using the current file's imports: import sys import os import qgis # NOQA pylint: disable=unused-import from functools import partial from distutils.version import StrictVersion from qgis.core import ( QgsRectangle, QgsRasterLayer, QgsMapLayer, QgsExpression, QgsProject, ) from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis.PyQt.QtWidgets import ( QAction, QApplication, QToolButton, QMenu, QLineEdit, QInputDialog ) from qgis.PyQt.QtGui import QIcon from safe.common.custom_logging import LOGGER from safe.utilities.expressions import qgis_expressions from safe.definitions.versions import inasafe_release_status, inasafe_version from safe.common.exceptions import ( KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError, ) from safe.common.signals import send_static_message from safe.utilities.resources import resources_path from safe.utilities.gis import is_raster_layer from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard ) from safe.definitions.utilities import get_field_groups from safe.utilities.i18n import tr from safe.utilities.keyword_io import KeywordIO from safe.utilities.utilities import is_keyword_version_supported from safe.utilities.settings import setting, set_setting from safe.gui.widgets.dock import Dock from safe.test.utilities import load_standard_layers from qgis.PyQt.QtWidgets import QDockWidget from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.widgets.message import getting_started_message from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog from safe.utilities.help import show_help from safe.gui.tools.help import definitions_help from safe.gui.tools.field_mapping_dialog import FieldMappingDialog from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog from safe.gui.tools.batch.batch_dialog import BatchDialog from safe.gui.tools.save_scenario import SaveScenarioDialog and any relevant context from other files: # Path: safe/definitions/versions.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
if layer_purpose == layer_purpose_exposure['key']:
Given the following code snippet before the placeholder: <|code_start|> enable_keyword_wizard = False elif not hasattr(layer, 'providerType'): enable_keyword_wizard = False elif layer.providerType() == 'wms': enable_keyword_wizard = False else: enable_keyword_wizard = True try: if layer: if is_raster_layer(layer): enable_field_mapping_tool = False else: keywords = KeywordIO().read_keywords(layer) keywords_version = keywords.get('keyword_version') if not keywords_version: supported = False else: supported = ( is_keyword_version_supported(keywords_version)) if not supported: enable_field_mapping_tool = False else: layer_purpose = keywords.get('layer_purpose') if not layer_purpose: enable_field_mapping_tool = False else: if layer_purpose == layer_purpose_exposure['key']: layer_subcategory = keywords.get('exposure') <|code_end|> , predict the next line using imports from the current file: import sys import os import qgis # NOQA pylint: disable=unused-import from functools import partial from distutils.version import StrictVersion from qgis.core import ( QgsRectangle, QgsRasterLayer, QgsMapLayer, QgsExpression, QgsProject, ) from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis.PyQt.QtWidgets import ( QAction, QApplication, QToolButton, QMenu, QLineEdit, QInputDialog ) from qgis.PyQt.QtGui import QIcon from safe.common.custom_logging import LOGGER from safe.utilities.expressions import qgis_expressions from safe.definitions.versions import inasafe_release_status, inasafe_version from safe.common.exceptions import ( KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError, ) from safe.common.signals import send_static_message from safe.utilities.resources import resources_path from safe.utilities.gis import is_raster_layer from safe.definitions.layer_purposes import ( layer_purpose_exposure, layer_purpose_hazard ) from safe.definitions.utilities import get_field_groups from safe.utilities.i18n import tr from safe.utilities.keyword_io import KeywordIO from safe.utilities.utilities import is_keyword_version_supported from safe.utilities.settings import setting, set_setting from safe.gui.widgets.dock import Dock from safe.test.utilities import load_standard_layers from qgis.PyQt.QtWidgets import QDockWidget from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog ) from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.widgets.message import getting_started_message from safe.gui.tools.options_dialog import OptionsDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.wizard.wizard_dialog import WizardDialog from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog from safe.utilities.help import show_help from safe.gui.tools.help import definitions_help from safe.gui.tools.field_mapping_dialog import FieldMappingDialog from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog from safe.gui.tools.batch.batch_dialog import BatchDialog from safe.gui.tools.save_scenario import SaveScenarioDialog and context including class names, function names, and sometimes code from other files: # Path: safe/definitions/versions.py # # Path: safe/definitions/layer_purposes.py . Output only the next line.
elif layer_purpose == layer_purpose_hazard['key']:
Continue the code snippet: <|code_start|> """Test translations work.""" def setUp(self): """Runs before each test.""" if 'LANG' in iter(list(os.environ.keys())): os.environ.__delitem__('LANG') def tearDown(self): """Runs after each test.""" if 'LANG' in iter(list(os.environ.keys())): os.environ.__delitem__('LANG') def test_impact_summary_words(self): """Test specific words from impact summary info shown in doc see #348. """ os.environ['LANG'] = 'id' phrase_list = [] message = 'Specific words checked for translation:\n' for phrase in phrase_list: if phrase == tr(phrase): message += 'FAIL: %s' % phrase else: message += 'PASS: %s' % phrase self.assertNotIn('FAIL', message, message) # Set back to en os.environ['LANG'] = 'en' def test_qgis_translations(self): """Test for qgis translations.""" <|code_end|> . Use current file imports: import unittest import os import qgis # pylint: disable=unused-import from safe.definitions.constants import INASAFE_TEST from safe.utilities.i18n import tr, locale from safe.common.utilities import safe_dir from qgis.PyQt.QtCore import QCoreApplication, QTranslator from safe.test.utilities import get_qgis_app from safe.definitions.constants import no_field from safe.definitions.constants import no_field and context (classes, functions, or code) from other files: # Path: safe/common/utilities.py # def safe_dir(sub_dir=None): # """Absolute path from safe package directory. # # :param sub_dir: Sub directory relative to safe package directory. # :type sub_dir: str # # :return: The Absolute path. # :rtype: str # """ # safe_relative_path = os.path.join( # os.path.dirname(__file__), '../') # return os.path.abspath( # os.path.join(safe_relative_path, sub_dir)) . Output only the next line.
file_path = safe_dir('i18n/inasafe_id.qm')
Next line prediction: <|code_start|> """Try to make a layer valid.""" __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' @profile def clean_layer(layer): """Clean a vector layer. :param layer: The vector layer. :type layer: qgis.core.QgsVectorLayer :return: The buffered vector layer. :rtype: qgis.core.QgsVectorLayer """ output_layer_name = clean_geometry_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] count = layer.featureCount() parameters = { 'INPUT': layer, 'OUTPUT': 'memory:' } <|code_end|> . Use current file imports: (import processing from safe.common.custom_logging import LOGGER from safe.common.exceptions import ProcessingInstallationError from safe.definitions.processing_steps import clean_geometry_steps from safe.gis.processing_tools import ( initialize_processing, create_processing_feedback, create_processing_context) from safe.gis.sanity_check import check_layer from safe.utilities.profiling import profile) and context including class names, function names, or small code snippets from other files: # Path: safe/gis/processing_tools.py # def initialize_processing(): # """ # Initializes processing, if it's not already been done # """ # # need_initialize = False # # needed_algorithms = [ # 'native:clip', # 'gdal:cliprasterbyextent', # 'native:union', # 'native:intersection' # ] # # if not QgsApplication.processingRegistry().algorithms(): # need_initialize = True # # if not need_initialize: # for needed_algorithm in needed_algorithms: # if not QgsApplication.processingRegistry().algorithmById( # needed_algorithm): # need_initialize = True # break # # if need_initialize: # QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # processing.Processing.initialize() # # def create_processing_feedback(): # """ # Creates a default processing feedback object # # :return: Processing feedback # :rtype: QgsProcessingFeedback # """ # return QgsProcessingFeedback() # # def create_processing_context(feedback): # """ # Creates a default processing context # # :param feedback: Linked processing feedback object # :type feedback: QgsProcessingFeedback # # :return: Processing context # :rtype: QgsProcessingContext # """ # context = QgsProcessingContext() # context.setFeedback(feedback) # context.setProject(QgsProject.instance()) # # # skip Processing geometry checks - Inasafe has its own geometry validation # # routines which have already been used # context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) # return context . Output only the next line.
initialize_processing()
Continue the code snippet: <|code_start|> __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' @profile def clean_layer(layer): """Clean a vector layer. :param layer: The vector layer. :type layer: qgis.core.QgsVectorLayer :return: The buffered vector layer. :rtype: qgis.core.QgsVectorLayer """ output_layer_name = clean_geometry_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] count = layer.featureCount() parameters = { 'INPUT': layer, 'OUTPUT': 'memory:' } initialize_processing() <|code_end|> . Use current file imports: import processing from safe.common.custom_logging import LOGGER from safe.common.exceptions import ProcessingInstallationError from safe.definitions.processing_steps import clean_geometry_steps from safe.gis.processing_tools import ( initialize_processing, create_processing_feedback, create_processing_context) from safe.gis.sanity_check import check_layer from safe.utilities.profiling import profile and context (classes, functions, or code) from other files: # Path: safe/gis/processing_tools.py # def initialize_processing(): # """ # Initializes processing, if it's not already been done # """ # # need_initialize = False # # needed_algorithms = [ # 'native:clip', # 'gdal:cliprasterbyextent', # 'native:union', # 'native:intersection' # ] # # if not QgsApplication.processingRegistry().algorithms(): # need_initialize = True # # if not need_initialize: # for needed_algorithm in needed_algorithms: # if not QgsApplication.processingRegistry().algorithmById( # needed_algorithm): # need_initialize = True # break # # if need_initialize: # QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # processing.Processing.initialize() # # def create_processing_feedback(): # """ # Creates a default processing feedback object # # :return: Processing feedback # :rtype: QgsProcessingFeedback # """ # return QgsProcessingFeedback() # # def create_processing_context(feedback): # """ # Creates a default processing context # # :param feedback: Linked processing feedback object # :type feedback: QgsProcessingFeedback # # :return: Processing context # :rtype: QgsProcessingContext # """ # context = QgsProcessingContext() # context.setFeedback(feedback) # context.setProject(QgsProject.instance()) # # # skip Processing geometry checks - Inasafe has its own geometry validation # # routines which have already been used # context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) # return context . Output only the next line.
feedback = create_processing_feedback()
Given the code snippet: <|code_start|> __copyright__ = "Copyright 2016, The InaSAFE Project" __license__ = "GPL version 3" __email__ = "info@inasafe.org" __revision__ = '$Format:%H$' @profile def clean_layer(layer): """Clean a vector layer. :param layer: The vector layer. :type layer: qgis.core.QgsVectorLayer :return: The buffered vector layer. :rtype: qgis.core.QgsVectorLayer """ output_layer_name = clean_geometry_steps['output_layer_name'] output_layer_name = output_layer_name % layer.keywords['layer_purpose'] count = layer.featureCount() parameters = { 'INPUT': layer, 'OUTPUT': 'memory:' } initialize_processing() feedback = create_processing_feedback() <|code_end|> , generate the next line using the imports in this file: import processing from safe.common.custom_logging import LOGGER from safe.common.exceptions import ProcessingInstallationError from safe.definitions.processing_steps import clean_geometry_steps from safe.gis.processing_tools import ( initialize_processing, create_processing_feedback, create_processing_context) from safe.gis.sanity_check import check_layer from safe.utilities.profiling import profile and context (functions, classes, or occasionally code) from other files: # Path: safe/gis/processing_tools.py # def initialize_processing(): # """ # Initializes processing, if it's not already been done # """ # # need_initialize = False # # needed_algorithms = [ # 'native:clip', # 'gdal:cliprasterbyextent', # 'native:union', # 'native:intersection' # ] # # if not QgsApplication.processingRegistry().algorithms(): # need_initialize = True # # if not need_initialize: # for needed_algorithm in needed_algorithms: # if not QgsApplication.processingRegistry().algorithmById( # needed_algorithm): # need_initialize = True # break # # if need_initialize: # QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) # processing.Processing.initialize() # # def create_processing_feedback(): # """ # Creates a default processing feedback object # # :return: Processing feedback # :rtype: QgsProcessingFeedback # """ # return QgsProcessingFeedback() # # def create_processing_context(feedback): # """ # Creates a default processing context # # :param feedback: Linked processing feedback object # :type feedback: QgsProcessingFeedback # # :return: Processing context # :rtype: QgsProcessingContext # """ # context = QgsProcessingContext() # context.setFeedback(feedback) # context.setProject(QgsProject.instance()) # # # skip Processing geometry checks - Inasafe has its own geometry validation # # routines which have already been used # context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) # return context . Output only the next line.
context = create_processing_context(feedback=feedback)
Next line prediction: <|code_start|> # This postprocessor function is also used in the aggregation_summary def post_processor_affected_function( exposure=None, hazard=None, classification=None, hazard_class=None): """Private function used in the affected postprocessor. It returns a boolean if it's affected or not, or not exposed. :param exposure: The exposure to use. :type exposure: str :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :return: If this hazard class is affected or not. It can be `not exposed`. The not exposed value returned is the key defined in `hazard_classification.py` at the top of the file. :rtype: bool,'not exposed' """ if exposure == exposure_population['key']: affected = is_affected( hazard, classification, hazard_class) else: classes = None <|code_end|> . Use current file imports: (from math import floor from qgis.core import QgsPointXY from safe.definitions.exposure import exposure_population from safe.definitions.hazard_classifications import ( hazard_classes_all, not_exposed_class) from safe.definitions.utilities import get_displacement_rate, is_affected from safe.utilities.i18n import tr) and context including class names, function names, or small code snippets from other files: # Path: safe/definitions/hazard_classifications.py . Output only the next line.
for hazard in hazard_classes_all:
Using the snippet: <|code_start|> :param hazard: The hazard to use. :type hazard: str :param classification: The hazard classification to use. :type classification: str :param hazard_class: The hazard class of the feature. :type hazard_class: str :return: If this hazard class is affected or not. It can be `not exposed`. The not exposed value returned is the key defined in `hazard_classification.py` at the top of the file. :rtype: bool,'not exposed' """ if exposure == exposure_population['key']: affected = is_affected( hazard, classification, hazard_class) else: classes = None for hazard in hazard_classes_all: if hazard['key'] == classification: classes = hazard['classes'] break for the_class in classes: if the_class['key'] == hazard_class: affected = the_class['affected'] break else: <|code_end|> , determine the next line of code. You have imports: from math import floor from qgis.core import QgsPointXY from safe.definitions.exposure import exposure_population from safe.definitions.hazard_classifications import ( hazard_classes_all, not_exposed_class) from safe.definitions.utilities import get_displacement_rate, is_affected from safe.utilities.i18n import tr and context (class names, function names, or code) available: # Path: safe/definitions/hazard_classifications.py . Output only the next line.
affected = not_exposed_class['key']
Given the following code snippet before the placeholder: <|code_start|> help_text = '' def __init__(self, subcommand_creator): # keep a local copy of the config file which is useful during # autocompletion self.config = None # set up the subcommand options self.subcommand_creator = subcommand_creator self.option_parser = self.subcommand_creator.add_parser( self.get_command_name(), help=self.help_text, description=self.help_text, ) self.add_command_line_options() def get_command_name(self): """The command name defaults to the name of the module.""" return self.__module__.rsplit('.', 1)[1] def add_command_line_options(self): self.option_parser.add_argument( '-c', '--config', type=str, help='Specify a particular YAML configuration file.', ) def execute(self, config=None): self.config = config <|code_end|> , predict the next line using imports from the current file: from ..parser import load_task_graph, get_task_kwargs_list from ..exceptions import ConfigurationNotFound, YamlError and context including class names, function names, and sometimes code from other files: # Path: flo/parser.py # @memoize # def load_task_graph(config=None): # """Load the task graph from the configuration file located at # config_path # """ # # config_path = find_config_path(config=config) # # # convert each task_kwargs into a Task object and add it to the # # TaskGraph # return TaskGraph(config_path, get_task_kwargs_list(config_path)) # # @memoize # def get_task_kwargs_list(config=None): # """Get a list of dictionaries that are read from the flo.yaml # file and collapse the global variables into each task. # """ # # # get workflow configuration file # config_path = find_config_path(config=config) # # # load the data # with open(config_path) as stream: # config_yaml = yaml.load_all(stream.read()) # try: # return config_yaml2task_kwargs_list(config_yaml) # except yaml.constructor.ConstructorError, error: # raise exceptions.YamlError(config_path, error) # # Path: flo/exceptions.py # class ConfigurationNotFound(CommandLineException): # def __init__(self, config_filename, cwd): # self.config_filename = config_filename # self.cwd = cwd # # def __str__(self): # return "No configuration file called '%s' found in directory\n'%s'" % ( # self.config_filename, # self.cwd, # ) # # class YamlError(CommandLineException): # def __init__(self, config_filename, yaml_error): # self.config_filename = config_filename # self.yaml_error = yaml_error # # def __str__(self): # msg = "There was an error loading your YAML configuration file " # msg += "located at\n%s:\n\n" % self.config_filename # msg += str(self.yaml_error) # # # provide useful hints here for common problems # if "{{" in str(self.yaml_error): # msg += "\n\n" # msg += "Try quoting your jinja templates if they start with '{{'\n" # msg += "because YAML interprets an unquoted '{' as the start of\n" # msg += "a new YAML object." # return msg . Output only the next line.
self.task_graph = load_task_graph(config=config)
Here is a snippet: <|code_start|> self.subcommand_creator = subcommand_creator self.option_parser = self.subcommand_creator.add_parser( self.get_command_name(), help=self.help_text, description=self.help_text, ) self.add_command_line_options() def get_command_name(self): """The command name defaults to the name of the module.""" return self.__module__.rsplit('.', 1)[1] def add_command_line_options(self): self.option_parser.add_argument( '-c', '--config', type=str, help='Specify a particular YAML configuration file.', ) def execute(self, config=None): self.config = config self.task_graph = load_task_graph(config=config) # this is a performance optimization to make it possible to use # the flo.yaml file to inform useful *and responsive* tab # completion on the command line _task_kwargs_list is used as a # local cache that is loaded once and inherited by all subclasses. @property def task_kwargs_list(self): try: <|code_end|> . Write the next line using the current file imports: from ..parser import load_task_graph, get_task_kwargs_list from ..exceptions import ConfigurationNotFound, YamlError and context from other files: # Path: flo/parser.py # @memoize # def load_task_graph(config=None): # """Load the task graph from the configuration file located at # config_path # """ # # config_path = find_config_path(config=config) # # # convert each task_kwargs into a Task object and add it to the # # TaskGraph # return TaskGraph(config_path, get_task_kwargs_list(config_path)) # # @memoize # def get_task_kwargs_list(config=None): # """Get a list of dictionaries that are read from the flo.yaml # file and collapse the global variables into each task. # """ # # # get workflow configuration file # config_path = find_config_path(config=config) # # # load the data # with open(config_path) as stream: # config_yaml = yaml.load_all(stream.read()) # try: # return config_yaml2task_kwargs_list(config_yaml) # except yaml.constructor.ConstructorError, error: # raise exceptions.YamlError(config_path, error) # # Path: flo/exceptions.py # class ConfigurationNotFound(CommandLineException): # def __init__(self, config_filename, cwd): # self.config_filename = config_filename # self.cwd = cwd # # def __str__(self): # return "No configuration file called '%s' found in directory\n'%s'" % ( # self.config_filename, # self.cwd, # ) # # class YamlError(CommandLineException): # def __init__(self, config_filename, yaml_error): # self.config_filename = config_filename # self.yaml_error = yaml_error # # def __str__(self): # msg = "There was an error loading your YAML configuration file " # msg += "located at\n%s:\n\n" % self.config_filename # msg += str(self.yaml_error) # # # provide useful hints here for common problems # if "{{" in str(self.yaml_error): # msg += "\n\n" # msg += "Try quoting your jinja templates if they start with '{{'\n" # msg += "because YAML interprets an unquoted '{' as the start of\n" # msg += "a new YAML object." # return msg , which may include functions, classes, or code. Output only the next line.
return get_task_kwargs_list(config=self.config)
Using the snippet: <|code_start|> self.option_parser = self.subcommand_creator.add_parser( self.get_command_name(), help=self.help_text, description=self.help_text, ) self.add_command_line_options() def get_command_name(self): """The command name defaults to the name of the module.""" return self.__module__.rsplit('.', 1)[1] def add_command_line_options(self): self.option_parser.add_argument( '-c', '--config', type=str, help='Specify a particular YAML configuration file.', ) def execute(self, config=None): self.config = config self.task_graph = load_task_graph(config=config) # this is a performance optimization to make it possible to use # the flo.yaml file to inform useful *and responsive* tab # completion on the command line _task_kwargs_list is used as a # local cache that is loaded once and inherited by all subclasses. @property def task_kwargs_list(self): try: return get_task_kwargs_list(config=self.config) <|code_end|> , determine the next line of code. You have imports: from ..parser import load_task_graph, get_task_kwargs_list from ..exceptions import ConfigurationNotFound, YamlError and context (class names, function names, or code) available: # Path: flo/parser.py # @memoize # def load_task_graph(config=None): # """Load the task graph from the configuration file located at # config_path # """ # # config_path = find_config_path(config=config) # # # convert each task_kwargs into a Task object and add it to the # # TaskGraph # return TaskGraph(config_path, get_task_kwargs_list(config_path)) # # @memoize # def get_task_kwargs_list(config=None): # """Get a list of dictionaries that are read from the flo.yaml # file and collapse the global variables into each task. # """ # # # get workflow configuration file # config_path = find_config_path(config=config) # # # load the data # with open(config_path) as stream: # config_yaml = yaml.load_all(stream.read()) # try: # return config_yaml2task_kwargs_list(config_yaml) # except yaml.constructor.ConstructorError, error: # raise exceptions.YamlError(config_path, error) # # Path: flo/exceptions.py # class ConfigurationNotFound(CommandLineException): # def __init__(self, config_filename, cwd): # self.config_filename = config_filename # self.cwd = cwd # # def __str__(self): # return "No configuration file called '%s' found in directory\n'%s'" % ( # self.config_filename, # self.cwd, # ) # # class YamlError(CommandLineException): # def __init__(self, config_filename, yaml_error): # self.config_filename = config_filename # self.yaml_error = yaml_error # # def __str__(self): # msg = "There was an error loading your YAML configuration file " # msg += "located at\n%s:\n\n" % self.config_filename # msg += str(self.yaml_error) # # # provide useful hints here for common problems # if "{{" in str(self.yaml_error): # msg += "\n\n" # msg += "Try quoting your jinja templates if they start with '{{'\n" # msg += "because YAML interprets an unquoted '{' as the start of\n" # msg += "a new YAML object." # return msg . Output only the next line.
except (ConfigurationNotFound, YamlError):
Using the snippet: <|code_start|> self.option_parser = self.subcommand_creator.add_parser( self.get_command_name(), help=self.help_text, description=self.help_text, ) self.add_command_line_options() def get_command_name(self): """The command name defaults to the name of the module.""" return self.__module__.rsplit('.', 1)[1] def add_command_line_options(self): self.option_parser.add_argument( '-c', '--config', type=str, help='Specify a particular YAML configuration file.', ) def execute(self, config=None): self.config = config self.task_graph = load_task_graph(config=config) # this is a performance optimization to make it possible to use # the flo.yaml file to inform useful *and responsive* tab # completion on the command line _task_kwargs_list is used as a # local cache that is loaded once and inherited by all subclasses. @property def task_kwargs_list(self): try: return get_task_kwargs_list(config=self.config) <|code_end|> , determine the next line of code. You have imports: from ..parser import load_task_graph, get_task_kwargs_list from ..exceptions import ConfigurationNotFound, YamlError and context (class names, function names, or code) available: # Path: flo/parser.py # @memoize # def load_task_graph(config=None): # """Load the task graph from the configuration file located at # config_path # """ # # config_path = find_config_path(config=config) # # # convert each task_kwargs into a Task object and add it to the # # TaskGraph # return TaskGraph(config_path, get_task_kwargs_list(config_path)) # # @memoize # def get_task_kwargs_list(config=None): # """Get a list of dictionaries that are read from the flo.yaml # file and collapse the global variables into each task. # """ # # # get workflow configuration file # config_path = find_config_path(config=config) # # # load the data # with open(config_path) as stream: # config_yaml = yaml.load_all(stream.read()) # try: # return config_yaml2task_kwargs_list(config_yaml) # except yaml.constructor.ConstructorError, error: # raise exceptions.YamlError(config_path, error) # # Path: flo/exceptions.py # class ConfigurationNotFound(CommandLineException): # def __init__(self, config_filename, cwd): # self.config_filename = config_filename # self.cwd = cwd # # def __str__(self): # return "No configuration file called '%s' found in directory\n'%s'" % ( # self.config_filename, # self.cwd, # ) # # class YamlError(CommandLineException): # def __init__(self, config_filename, yaml_error): # self.config_filename = config_filename # self.yaml_error = yaml_error # # def __str__(self): # msg = "There was an error loading your YAML configuration file " # msg += "located at\n%s:\n\n" % self.config_filename # msg += str(self.yaml_error) # # # provide useful hints here for common problems # if "{{" in str(self.yaml_error): # msg += "\n\n" # msg += "Try quoting your jinja templates if they start with '{{'\n" # msg += "because YAML interprets an unquoted '{' as the start of\n" # msg += "a new YAML object." # return msg . Output only the next line.
except (ConfigurationNotFound, YamlError):
Given snippet: <|code_start|> class memoize(object): """Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). adapted from https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args, **kwargs): # cast kwargs as an immutable dictionary so this caching works <|code_end|> , continue by predicting the next line. Consider current file imports: import functools from .types import FrozenDict and context: # Path: flo/types.py # class FrozenDict(collections.Mapping): # """FrozenDict makes the equivalent of an immutable dictionary for the # purpose of memoization. # # adapted from http://stackoverflow.com/a/2705638/564709 # """ # # def __init__(self, *args, **kwargs): # self._d = dict(*args, **kwargs) # # def __iter__(self): # return iter(self._d) # # def __len__(self): # return len(self._d) # # def __getitem__(self, key): # return self._d[key] # # def __hash__(self): # return hash(tuple(sorted(self._d.iteritems()))) which might include code, classes, or functions. Output only the next line.
frozen_kwargs = FrozenDict(kwargs)
Given snippet: <|code_start|> Returns: np.ndarray: A TPM with the same number of dimensions, with the nodes marginalized out. """ return tpm.sum(tuple(node_indices), keepdims=True) / ( np.array(tpm.shape)[list(node_indices)].prod() ) def infer_edge(tpm, a, b, contexts): """Infer the presence or absence of an edge from node A to node B. Let |S| be the set of all nodes in a network. Let |A' = S - {A}|. We call the state of |A'| the context |C| of |A|. There is an edge from |A| to |B| if there exists any context |C(A)| such that |Pr(B | C(A), A=0) != Pr(B | C(A), A=1)|. Args: tpm (np.ndarray): The TPM in state-by-node, multidimensional form. a (int): The index of the putative source node. b (int): The index of the putative sink node. Returns: bool: ``True`` if the edge |A -> B| exists, ``False`` otherwise. """ def a_in_context(context): """Given a context C(A), return the states of the full system with A OFF and ON, respectively. """ <|code_end|> , continue by predicting the next line. Consider current file imports: from itertools import chain from .constants import OFF, ON from .utils import all_states import numpy as np and context: # Path: pyphi/constants.py # OFF = (0,) # # ON = (1,) # # Path: pyphi/utils.py # def all_states(n, big_endian=False): # """Return all binary states for a system. # # Args: # n (int): The number of elements in the system. # big_endian (bool): Whether to return the states in big-endian order # instead of little-endian order. # # Yields: # tuple[int]: The next state of an ``n``-element system, in little-endian # order unless ``big_endian`` is ``True``. # """ # if n == 0: # return # # for state in product((0, 1), repeat=n): # if big_endian: # yield state # else: # yield state[::-1] # Convert to little-endian ordering which might include code, classes, or functions. Output only the next line.
a_off = context[:a] + OFF + context[a:]
Based on the snippet: <|code_start|> Returns: np.ndarray: A TPM with the same number of dimensions, with the nodes marginalized out. """ return tpm.sum(tuple(node_indices), keepdims=True) / ( np.array(tpm.shape)[list(node_indices)].prod() ) def infer_edge(tpm, a, b, contexts): """Infer the presence or absence of an edge from node A to node B. Let |S| be the set of all nodes in a network. Let |A' = S - {A}|. We call the state of |A'| the context |C| of |A|. There is an edge from |A| to |B| if there exists any context |C(A)| such that |Pr(B | C(A), A=0) != Pr(B | C(A), A=1)|. Args: tpm (np.ndarray): The TPM in state-by-node, multidimensional form. a (int): The index of the putative source node. b (int): The index of the putative sink node. Returns: bool: ``True`` if the edge |A -> B| exists, ``False`` otherwise. """ def a_in_context(context): """Given a context C(A), return the states of the full system with A OFF and ON, respectively. """ a_off = context[:a] + OFF + context[a:] <|code_end|> , predict the immediate next line with the help of imports: from itertools import chain from .constants import OFF, ON from .utils import all_states import numpy as np and context (classes, functions, sometimes code) from other files: # Path: pyphi/constants.py # OFF = (0,) # # ON = (1,) # # Path: pyphi/utils.py # def all_states(n, big_endian=False): # """Return all binary states for a system. # # Args: # n (int): The number of elements in the system. # big_endian (bool): Whether to return the states in big-endian order # instead of little-endian order. # # Yields: # tuple[int]: The next state of an ``n``-element system, in little-endian # order unless ``big_endian`` is ``True``. # """ # if n == 0: # return # # for state in product((0, 1), repeat=n): # if big_endian: # yield state # else: # yield state[::-1] # Convert to little-endian ordering . Output only the next line.
a_on = context[:a] + ON + context[a:]
Next line prediction: <|code_start|> Args: tpm (np.ndarray): The TPM in state-by-node, multidimensional form. a (int): The index of the putative source node. b (int): The index of the putative sink node. Returns: bool: ``True`` if the edge |A -> B| exists, ``False`` otherwise. """ def a_in_context(context): """Given a context C(A), return the states of the full system with A OFF and ON, respectively. """ a_off = context[:a] + OFF + context[a:] a_on = context[:a] + ON + context[a:] return (a_off, a_on) def a_affects_b_in_context(context): """Return ``True`` if A has an effect on B, given a context.""" a_off, a_on = a_in_context(context) return tpm[a_off][b] != tpm[a_on][b] return any(a_affects_b_in_context(context) for context in contexts) def infer_cm(tpm): """Infer the connectivity matrix associated with a state-by-node TPM in multidimensional form. """ network_size = tpm.shape[-1] <|code_end|> . Use current file imports: (from itertools import chain from .constants import OFF, ON from .utils import all_states import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: pyphi/constants.py # OFF = (0,) # # ON = (1,) # # Path: pyphi/utils.py # def all_states(n, big_endian=False): # """Return all binary states for a system. # # Args: # n (int): The number of elements in the system. # big_endian (bool): Whether to return the states in big-endian order # instead of little-endian order. # # Yields: # tuple[int]: The next state of an ``n``-element system, in little-endian # order unless ``big_endian`` is ``True``. # """ # if n == 0: # return # # for state in product((0, 1), repeat=n): # if big_endian: # yield state # else: # yield state[::-1] # Convert to little-endian ordering . Output only the next line.
all_contexts = tuple(all_states(network_size - 1))
Predict the next line after this snippet: <|code_start|> [0., 0., 0., 0., 1., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 1., 0., 0.]]) >>> tpm = np.array([[0.1, 0.3, 0.7], ... [0.3, 0.9, 0.2], ... [0.3, 0.9, 0.1], ... [0.2, 0.8, 0.5], ... [0.1, 0.7, 0.4], ... [0.4, 0.3, 0.6], ... [0.4, 0.3, 0.1], ... [0.5, 0.2, 0.1]]) >>> state_by_node2state_by_state(tpm) array([[0.189, 0.021, 0.081, 0.009, 0.441, 0.049, 0.189, 0.021], [0.056, 0.024, 0.504, 0.216, 0.014, 0.006, 0.126, 0.054], [0.063, 0.027, 0.567, 0.243, 0.007, 0.003, 0.063, 0.027], [0.08 , 0.02 , 0.32 , 0.08 , 0.08 , 0.02 , 0.32 , 0.08 ], [0.162, 0.018, 0.378, 0.042, 0.108, 0.012, 0.252, 0.028], [0.168, 0.112, 0.072, 0.048, 0.252, 0.168, 0.108, 0.072], [0.378, 0.252, 0.162, 0.108, 0.042, 0.028, 0.018, 0.012], [0.36 , 0.36 , 0.09 , 0.09 , 0.04 , 0.04 , 0.01 , 0.01 ]]) """ # Reshape to 2D sbn_tpm = to_2dimensional(tpm) # Get number of previous states Sp = sbn_tpm.shape[0] # Get number of nodes in the next state Nn = sbn_tpm.shape[1] # Get the number of next states Sn = 2 ** Nn <|code_end|> using the current file's imports: import logging import numpy as np from itertools import product from math import log2 from .tpm import is_deterministic and any relevant context from other files: # Path: pyphi/tpm.py # def is_deterministic(tpm): # """Return whether the TPM is deterministic.""" # return np.all(np.logical_or(tpm == 1, tpm == 0)) . Output only the next line.
if is_deterministic(tpm):
Based on the snippet: <|code_start|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # test/test_utils.py def test_all_states(): assert list(utils.all_states(0)) == [] assert list(utils.all_states(1)) == [(0,), (1,)] states = [ (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), ] assert list(utils.all_states(3)) == states assert list(utils.all_states(3, big_endian=True)) == [ tuple(reversed(state)) for state in states ] def test_eq(): phi = 0.5 <|code_end|> , predict the immediate next line with the help of imports: from unittest.mock import patch from pyphi import constants, utils import numpy as np and context (classes, functions, sometimes code) from other files: # Path: pyphi/constants.py # EPSILON = None # FILESYSTEM = "fs" # DATABASE = "db" # PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL # OFF = (0,) # ON = (1,) # # Path: pyphi/utils.py # def state_of(nodes, network_state): # def all_states(n, big_endian=False): # def np_immutable(a): # def np_hash(a): # def __init__(self, array): # def __hash__(self): # def __eq__(self, other): # def __repr__(self): # def eq(x, y): # def combs(a, r): # def comb_indices(n, k): # def powerset(iterable, nonempty=False, reverse=False): # def load_data(directory, num): # def get_path(i): # pylint: disable=missing-docstring # def time_annotated(func, *args, **kwargs): # class np_hashable: . Output only the next line.
close_enough = phi - constants.EPSILON / 2
Given the code snippet: <|code_start|> assert np.array_equal( distribution.marginal(repertoire, 0), np.array([[[0.5]], [[0.5]]]) ) assert np.array_equal(distribution.marginal(repertoire, 1), np.array([[[0], [1]]])) assert np.array_equal(distribution.marginal(repertoire, 2), np.array([[[0, 1]]])) def test_independent(): # fmt: off repertoire = np.array([ [[0.25], [0.25]], [[0.25], [0.25]], ]) # fmt: on assert distribution.independent(repertoire) # fmt: off repertoire = np.array([ [[0.5], [0.0]], [[0.0], [0.5]], ]) # fmt: on assert not distribution.independent(repertoire) def test_purview_size(s): <|code_end|> , generate the next line using the imports in this file: import numpy as np from pyphi import distribution from pyphi.utils import powerset and context (functions, classes, or occasionally code) from other files: # Path: pyphi/distribution.py # def normalize(a): # def uniform_distribution(number_of_nodes): # def marginal_zero(repertoire, node_index): # def marginal(repertoire, node_index): # def independent(repertoire): # def purview(repertoire): # def purview_size(repertoire): # def repertoire_shape(purview, N): # pylint: disable=redefined-outer-name # def flatten(repertoire, big_endian=False): # def unflatten(repertoire, purview, N, big_endian=False): # def max_entropy_distribution(node_indices, number_of_nodes): # # Path: pyphi/utils.py # def powerset(iterable, nonempty=False, reverse=False): # """Generate the power set of an iterable. # # Args: # iterable (Iterable): The iterable from which to generate the power set. # # Keyword Args: # nonempty (boolean): If True, don't include the empty set. # reverse (boolean): If True, reverse the order of the powerset. # # Returns: # Iterable: An iterator over the power set. # # Example: # >>> ps = powerset(np.arange(2)) # >>> list(ps) # [(), (0,), (1,), (0, 1)] # >>> ps = powerset(np.arange(2), nonempty=True) # >>> list(ps) # [(0,), (1,), (0, 1)] # >>> ps = powerset(np.arange(2), nonempty=True, reverse=True) # >>> list(ps) # [(1, 0), (1,), (0,)] # """ # iterable = list(iterable) # # if nonempty: # Don't include 0-length subsets # start = 1 # else: # start = 0 # # seq_sizes = range(start, len(iterable) + 1) # # if reverse: # seq_sizes = reversed(seq_sizes) # iterable.reverse() # # return chain.from_iterable(combinations(iterable, r) for r in seq_sizes) . Output only the next line.
mechanisms = powerset(s.node_indices)
Based on the snippet: <|code_start|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # test/test_connectivity/test_connectivity.py def test_get_inputs_from_cm(): # fmt: off cm = np.array([ [0, 1, 0], [1, 1, 1], [0, 0, 0], ]) # fmt: on <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from pyphi import connectivity and context (classes, functions, sometimes code) from other files: # Path: pyphi/connectivity.py # def apply_boundary_conditions_to_cm(external_indices, cm): # def get_inputs_from_cm(index, cm): # def get_outputs_from_cm(index, cm): # def causally_significant_nodes(cm): # def relevant_connections(n, _from, to): # def block_cm(cm): # def outputs_of(nodes): # def inputs_to(nodes): # def block_reducible(cm, nodes1, nodes2): # def _connected(cm, nodes, connection): # def is_strong(cm, nodes=None): # def is_weak(cm, nodes=None): # def is_full(cm, nodes1, nodes2): . Output only the next line.
assert connectivity.get_inputs_from_cm(0, cm) == (1,)
Here is a snippet: <|code_start|> [0.375, 0.375, 0.125, 0.125], ]) ) # fmt: on partition = ((0,), (1, 2)) grouping = (((0,), (1,)), ((0, 1), (2,))) coarse_grain = macro.CoarseGrain(partition, grouping) assert np.array_equal(coarse_grain.make_mapping(), [0, 1, 0, 1, 0, 1, 2, 3]) micro_tpm = np.zeros((8, 3)) + 0.5 macro_tpm = coarse_grain.macro_tpm(micro_tpm) assert np.array_equal(answer_tpm, macro_tpm) micro_tpm = np.zeros((8, 8)) + 0.125 macro_tpm = coarse_grain.macro_tpm(micro_tpm) assert np.array_equal(answer_tpm, macro_tpm) def test_make_macro_tpm_conditional_independence_check(): # fmt: off micro_tpm = np.array([ [1, 0.0, 0.0, 0], [0, 0.5, 0.5, 0], [0, 0.5, 0.5, 0], [0, 0.0, 0.0, 1], ]) # fmt: on partition = ((0,), (1,)) grouping = (((0,), (1,)), ((0,), (1,))) coarse_grain = macro.CoarseGrain(partition, grouping) <|code_end|> . Write the next line using the current file imports: import numpy as np import pytest from pyphi import convert, macro from pyphi.exceptions import ConditionallyDependentError and context from other files: # Path: pyphi/convert.py # def reverse_bits(i, n): # def be2le(i, n): # def nodes2indices(nodes): # def nodes2state(nodes): # def state2be_index(state): # def state2le_index(state): # def le_index2state(i, number_of_nodes): # def be_index2state(i, number_of_nodes): # def be2le_state_by_state(tpm): # def to_multidimensional(tpm): # def to_2dimensional(tpm): # def state_by_state2state_by_node(tpm): # def _deterministic_sbn2sbs(Sp, Sn, sbn_tpm): # def _unfold_nodewise_probabilities(Nn, Sn, sbn_row): # def _nondeterministic_sbn2sbs(Nn, Sn, sbn_tpm): # def state_by_node2state_by_state(tpm): # N = tpm.shape[0] # S = np.prod(tpm.shape[:-1]) # N = tpm.shape[-1] # S = tpm.shape[-1] # N = int(log2(S)) # # Path: pyphi/macro.py # _NUM_PRECOMPUTED_PARTITION_LISTS = 10 # def reindex(indices): # def rebuild_system_tpm(node_tpms): # def remove_singleton_dimensions(tpm): # def run_tpm(system, steps, blackbox): # def node_labels(self): # def nodes(self): # def pack(system): # def apply(self, system): # def __init__( # self, # network, # state, # nodes=None, # cut=None, # mice_cache=None, # time_scale=1, # blackbox=None, # coarse_grain=None, # ): # def _squeeze(system): # def _blackbox_partial_noise(blackbox, system): # def _blackbox_time(time_scale, blackbox, system): # def _blackbox_space(self, blackbox, system): # def _coarsegrain_space(coarse_grain, is_cut, system): # def cut_indices(self): # def cut_mechanisms(self): # def cut_node_labels(self): # def apply_cut(self, cut): # def potential_purviews(self, direction, mechanism, purviews=False): # def macro2micro(self, macro_indices): # def from_partition(partition, macro_indices): # def macro2blackbox_outputs(self, macro_indices): # def __repr__(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def micro_indices(self): # def macro_indices(self): # def __len__(self): # def reindex(self): # def macro_state(self, micro_state): # def make_mapping(self): # def macro_tpm_sbs(self, state_by_state_micro_tpm): # def macro_tpm(self, micro_tpm, check_independence=True): # def hidden_indices(self): # def micro_indices(self): # def macro_indices(self): # def __len__(self): # def outputs_of(self, partition_index): # def reindex(self): # def macro_state(self, micro_state): # def in_same_box(self, a, b): # def hidden_from(self, a, b): # def _partitions_list(N): # def all_partitions(indices): # def all_groupings(partition): # def all_coarse_grains(indices): # def all_coarse_grains_for_blackbox(blackbox): # def all_blackboxes(indices): # def __init__( # self, # network, # system, # macro_phi, # micro_phi, # coarse_grain, # time_scale=1, # blackbox=None, # ): # def __str__(self): # def emergence(self): # def coarse_graining(network, state, internal_indices): # def all_macro_systems( # network, state, do_blackbox=False, do_coarse_grain=False, time_scales=None # ): # def blackboxes(system): # def coarse_grains(blackbox, system): # def emergence( # network, state, do_blackbox=False, do_coarse_grain=True, time_scales=None # ): # def phi_by_grain(network, state): # def effective_info(network): # class SystemAttrs(namedtuple("SystemAttrs", ["tpm", "cm", "node_indices", "state"])): # class MacroSubsystem(Subsystem): # class CoarseGrain(namedtuple("CoarseGrain", ["partition", "grouping"])): # class Blackbox(namedtuple("Blackbox", ["partition", "output_indices"])): # class MacroNetwork: # # Path: pyphi/exceptions.py # class ConditionallyDependentError(ValueError): # """The TPM is conditionally dependent.""" , which may include functions, classes, or code. Output only the next line.
with pytest.raises(ConditionallyDependentError):
Here is a snippet: <|code_start|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # test_subsystem_cause_effect_info.py def test_cause_info(s): mechanism = (0, 1) purview = (0, 2) <|code_end|> . Write the next line using the current file imports: from pyphi.distance import hamming_emd and context from other files: # Path: pyphi/distance.py # @measures.register("EMD") # def hamming_emd(d1, d2): # """Return the Earth Mover's Distance between two distributions (indexed # by state, one dimension per node) using the Hamming distance between states # as the transportation cost function. # # Singleton dimensions are sqeezed out. # """ # N = d1.squeeze().ndim # d1, d2 = flatten(d1), flatten(d2) # return emd(d1, d2, _hamming_matrix(N)) , which may include functions, classes, or code. Output only the next line.
answer = hamming_emd(
Next line prediction: <|code_start|> return None order = "C" if big_endian else "F" # For efficiency, use `ravel` (which returns a view of the array) instead # of `np.flatten` (which copies the whole array). return repertoire.squeeze().ravel(order=order) def unflatten(repertoire, purview, N, big_endian=False): """Unflatten a repertoire. By default, the input is assumed to be in little-endian order. Args: repertoire (np.ndarray or None): A probability distribution. purview (Iterable[int]): The indices of the nodes whose states the probability is distributed over. N (int): The size of the network. Keyword Args: big_endian (boolean): If ``True``, assume the flat repertoire is in big-endian order. Returns: np.ndarray: The unflattened repertoire. """ order = "C" if big_endian else "F" return repertoire.reshape(repertoire_shape(purview, N), order=order) <|code_end|> . Use current file imports: (import numpy as np from .cache import cache) and context including class names, function names, or small code snippets from other files: # Path: pyphi/cache.py # def cache(cache={}, maxmem=config.MAXIMUM_CACHE_MEMORY_PERCENTAGE, typed=False): # """Memory-limited cache decorator. # # ``maxmem`` is a float between 0 and 100, inclusive, specifying the maximum # percentage of physical memory that the cache can use. # # If ``typed`` is ``True``, arguments of different types will be cached # separately. For example, f(3.0) and f(3) will be treated as distinct calls # with distinct results. # # Arguments to the cached function must be hashable. # # View the cache statistics named tuple (hits, misses, currsize) # with f.cache_info(). Clear the cache and statistics with f.cache_clear(). # Access the underlying function with f.__wrapped__. # """ # # Constants shared by all lru cache instances: # # Unique object used to signal cache misses. # sentinel = object() # # Build a key from the function arguments. # make_key = _make_key # # def decorating_function(user_function, hits=0, misses=0): # full = False # # Bound method to look up a key or return None. # cache_get = cache.get # # if not maxmem: # # def wrapper(*args, **kwds): # # Simple caching without memory limit. # nonlocal hits, misses # key = make_key(args, kwds, typed) # result = cache_get(key, sentinel) # if result is not sentinel: # hits += 1 # return result # result = user_function(*args, **kwds) # cache[key] = result # misses += 1 # return result # # else: # # def wrapper(*args, **kwds): # # Memory-limited caching. # nonlocal hits, misses, full # key = make_key(args, kwds, typed) # result = cache_get(key) # if result is not None: # hits += 1 # return result # result = user_function(*args, **kwds) # if not full: # cache[key] = result # # Cache is full if the total recursive usage is greater # # than the maximum allowed percentage. # current_process = psutil.Process(os.getpid()) # full = current_process.memory_percent() > maxmem # misses += 1 # return result # # def cache_info(): # """Report cache statistics.""" # return _CacheInfo(hits, misses, len(cache)) # # def cache_clear(): # """Clear the cache and cache statistics.""" # nonlocal hits, misses, full # cache.clear() # hits = misses = 0 # full = False # # wrapper.cache_info = cache_info # wrapper.cache_clear = cache_clear # return update_wrapper(wrapper, user_function) # # return decorating_function . Output only the next line.
@cache(cache={}, maxmem=None)
Based on the snippet: <|code_start|> def dumps(obj, **user_kwargs): """Serialize ``obj`` as JSON-formatted stream.""" return json.dumps(obj, **_encoder_kwargs(user_kwargs)) def dump(obj, fp, **user_kwargs): """Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a ``.write()``-supporting file-like object. """ return json.dump(obj, fp, **_encoder_kwargs(user_kwargs)) def _check_version(version): """Check whether the JSON version matches the PyPhi version.""" if version != pyphi.__version__: raise pyphi.exceptions.JSONVersionError( "Cannot load JSON from a different version of PyPhi. " "JSON version = {0}, current version = {1}.".format( version, pyphi.__version__ ) ) def _is_model(dct): """Check if ``dct`` is a PyPhi model serialization.""" return CLASS_KEY in dct <|code_end|> , predict the immediate next line with the help of imports: import json import numpy as np import pyphi from pyphi import cache and context (classes, functions, sometimes code) from other files: # Path: pyphi/cache.py # def cache(cache={}, maxmem=config.MAXIMUM_CACHE_MEMORY_PERCENTAGE, typed=False): # """Memory-limited cache decorator. # # ``maxmem`` is a float between 0 and 100, inclusive, specifying the maximum # percentage of physical memory that the cache can use. # # If ``typed`` is ``True``, arguments of different types will be cached # separately. For example, f(3.0) and f(3) will be treated as distinct calls # with distinct results. # # Arguments to the cached function must be hashable. # # View the cache statistics named tuple (hits, misses, currsize) # with f.cache_info(). Clear the cache and statistics with f.cache_clear(). # Access the underlying function with f.__wrapped__. # """ # # Constants shared by all lru cache instances: # # Unique object used to signal cache misses. # sentinel = object() # # Build a key from the function arguments. # make_key = _make_key # # def decorating_function(user_function, hits=0, misses=0): # full = False # # Bound method to look up a key or return None. # cache_get = cache.get # # if not maxmem: # # def wrapper(*args, **kwds): # # Simple caching without memory limit. # nonlocal hits, misses # key = make_key(args, kwds, typed) # result = cache_get(key, sentinel) # if result is not sentinel: # hits += 1 # return result # result = user_function(*args, **kwds) # cache[key] = result # misses += 1 # return result # # else: # # def wrapper(*args, **kwds): # # Memory-limited caching. # nonlocal hits, misses, full # key = make_key(args, kwds, typed) # result = cache_get(key) # if result is not None: # hits += 1 # return result # result = user_function(*args, **kwds) # if not full: # cache[key] = result # # Cache is full if the total recursive usage is greater # # than the maximum allowed percentage. # current_process = psutil.Process(os.getpid()) # full = current_process.memory_percent() > maxmem # misses += 1 # return result # # def cache_info(): # """Report cache statistics.""" # return _CacheInfo(hits, misses, len(cache)) # # def cache_clear(): # """Clear the cache and cache statistics.""" # nonlocal hits, misses, full # cache.clear() # hits = misses = 0 # full = False # # wrapper.cache_info = cache_info # wrapper.cache_clear = cache_clear # return update_wrapper(wrapper, user_function) # # return decorating_function . Output only the next line.
class _ObjectCache(cache.DictCache):
Using the snippet: <|code_start|> [1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1]] cm2 = [ [1, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 1]] cm3 = [[1] * 16] * 16 matrices = [cm0, cm1, cm2, cm3] class BenchmarkBlockCm(): params = [0, 1, 2, 3] def setup(self, m): self.cm = np.array(matrices[m]) def time_block_cm(self, m): <|code_end|> , determine the next line of code. You have imports: import numpy as np from pyphi import utils and context (class names, function names, or code) available: # Path: pyphi/utils.py # def state_of(nodes, network_state): # def all_states(n, big_endian=False): # def np_immutable(a): # def np_hash(a): # def __init__(self, array): # def __hash__(self): # def __eq__(self, other): # def __repr__(self): # def eq(x, y): # def combs(a, r): # def comb_indices(n, k): # def powerset(iterable, nonempty=False, reverse=False): # def load_data(directory, num): # def get_path(i): # pylint: disable=missing-docstring # def time_annotated(func, *args, **kwargs): # class np_hashable: . Output only the next line.
utils.block_cm(self.cm)
Here is a snippet: <|code_start|> """Default label for a node.""" return "n{}".format(index) def default_labels(indices): """Default labels for serveral nodes.""" return tuple(default_label(i) for i in indices) class NodeLabels(collections.abc.Sequence): """Text labels for nodes in a network. Labels can either be instantiated as a tuple of strings: >>> NodeLabels(('A', 'IN'), (0, 1)) NodeLabels(('A', 'IN')) Or, if all labels are a single character, as a string: >>> NodeLabels('AB', (0, 1)) NodeLabels(('A', 'B')) """ def __init__(self, labels, node_indices): if labels is None: labels = default_labels(node_indices) self.labels = tuple(label for label in labels) self.node_indices = node_indices <|code_end|> . Write the next line using the current file imports: import collections from pyphi import validate from pyphi.models import cmp and context from other files: # Path: pyphi/validate.py # def direction(direction, allow_bi=False): # def tpm(tpm, check_independence=True): # def conditionally_independent(tpm): # def connectivity_matrix(cm): # def node_labels(node_labels, node_indices): # def network(n): # def is_network(network): # def node_states(state): # def state_length(state, size): # def state_reachable(subsystem): # def cut(cut, node_indices): # def subsystem(s): # def time_scale(time_scale): # def partition(partition): # def coarse_grain(coarse_grain): # def blackbox(blackbox): # def blackbox_and_coarse_grain(blackbox, coarse_grain): # def relata(relata): # N = tpm.shape[-1] # # Path: pyphi/models/cmp.py # def sametype(func): # def wrapper(self, other): # pylint: disable=missing-docstring # def order_by(self): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def numpy_aware_eq(a, b): # def general_eq(a, b, attributes): # class Orderable: , which may include functions, classes, or code. Output only the next line.
validate.node_labels(self.labels, node_indices)
Here is a snippet: <|code_start|> """ def __init__(self, labels, node_indices): if labels is None: labels = default_labels(node_indices) self.labels = tuple(label for label in labels) self.node_indices = node_indices validate.node_labels(self.labels, node_indices) # Dicts mapping indices to labels and vice versa self._l2i = dict(zip(self.labels, self.node_indices)) self._i2l = dict(zip(self.node_indices, self.labels)) def __len__(self): return len(self.labels) def __iter__(self): return iter(self.labels) def __contains__(self, x): return x in self.labels def __getitem__(self, x): return self.labels[x] def __repr__(self): return "NodeLabels({})".format(self.labels) <|code_end|> . Write the next line using the current file imports: import collections from pyphi import validate from pyphi.models import cmp and context from other files: # Path: pyphi/validate.py # def direction(direction, allow_bi=False): # def tpm(tpm, check_independence=True): # def conditionally_independent(tpm): # def connectivity_matrix(cm): # def node_labels(node_labels, node_indices): # def network(n): # def is_network(network): # def node_states(state): # def state_length(state, size): # def state_reachable(subsystem): # def cut(cut, node_indices): # def subsystem(s): # def time_scale(time_scale): # def partition(partition): # def coarse_grain(coarse_grain): # def blackbox(blackbox): # def blackbox_and_coarse_grain(blackbox, coarse_grain): # def relata(relata): # N = tpm.shape[-1] # # Path: pyphi/models/cmp.py # def sametype(func): # def wrapper(self, other): # pylint: disable=missing-docstring # def order_by(self): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def numpy_aware_eq(a, b): # def general_eq(a, b, attributes): # class Orderable: , which may include functions, classes, or code. Output only the next line.
@cmp.sametype
Here is a snippet: <|code_start|> wait_for(is_init,timeout=60 * 10, sleep_duration=1) if self.is_replicaset_initialized(): log_info("Successfully initiated replica set cluster '%s'!" % self.id) else: msg = ("Timeout error: Initializing replicaset '%s' took " "longer than expected. This does not necessarily" " mean that it failed but it could have failed. " % self.id) raise MongoctlException(msg) ## add the admin user after the set has been initiated ## Wait for the server to become primary though (at MongoDB's end) def is_primary_for_real(): return primary_server.is_primary() log_info("Will now wait for the intended primary server to " "become primary.") wait_for(is_primary_for_real,timeout=60, sleep_duration=1) if not is_primary_for_real(): msg = ("Timeout error: Waiting for server '%s' to become " "primary took longer than expected. " "Please try again later." % primary_server.id) raise MongoctlException(msg) log_info("Server '%s' is primary now!" % primary_server.id) # setup cluster users <|code_end|> . Write the next line using the current file imports: import mongoctl.repository as repository from cluster import Cluster from mongoctl import users from base import DocumentWrapper from mongoctl.utils import * from bson import DBRef from mongoctl.config import get_cluster_member_alt_address_mapping from mongoctl.mongoctl_logging import log_verbose, log_error, log_db_command from mongoctl.prompt import prompt_confirm and context from other files: # Path: mongoctl/users.py # def parse_global_login_user_arg(username, password, server_id): # def get_global_login_user(server, dbname): # def setup_server_users(server): # def setup_cluster_users(cluster, primary_server): # def should_seed_db_users(server, dbname): # def setup_db_users(server, db, db_users): # def _mongo_add_user(server, db, username, password, read_only=False, # num_tries=1): # def list_database_users(server, db): # def setup_server_db_users(server, dbname, db_users): # def prepend_global_admin_user(other_users, server): # def setup_server_admin_users(server): # def setup_root_admin_user(server, admin_users): # def setup_server_local_users(server): # def read_seed_password(dbname, username): # def set_server_login_user(server, dbname, username, password): # def get_server_login_user(server, dbname): # def _get_server_login_record(server, create_new=True): # def is_system_user(username): # LOGIN_USERS = {} # # Path: mongoctl/config.py # def get_cluster_member_alt_address_mapping(): # return get_mongoctl_config_val('clusterMemberAltAddressesMapping', {}) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_error(msg): # get_logger().error(msg) # # def log_db_command(cmd): # log_info( "Executing db command %s" % utils.document_pretty_string(cmd)) , which may include functions, classes, or code. Output only the next line.
users.setup_cluster_users(self, primary_server)
Next line prediction: <|code_start|> def can_become_primary(self): return not self.is_arbiter() and self.get_priority() != 0 ########################################################################### def get_member_repl_config(self): # create the member repl config with host member_conf = {"host": self.get_host()} # Add the rest of the properties configured in the document # EXCEPT host/server ignore = ['host', 'server'] for key,value in self.__document__.items(): if key not in ignore : member_conf[key] = value self._apply_alt_address_mapping(member_conf) return member_conf ########################################################################### def _apply_alt_address_mapping(self, member_conf): # Not applicable to arbiters if self.is_arbiter(): return <|code_end|> . Use current file imports: (import mongoctl.repository as repository from cluster import Cluster from mongoctl import users from base import DocumentWrapper from mongoctl.utils import * from bson import DBRef from mongoctl.config import get_cluster_member_alt_address_mapping from mongoctl.mongoctl_logging import log_verbose, log_error, log_db_command from mongoctl.prompt import prompt_confirm) and context including class names, function names, or small code snippets from other files: # Path: mongoctl/users.py # def parse_global_login_user_arg(username, password, server_id): # def get_global_login_user(server, dbname): # def setup_server_users(server): # def setup_cluster_users(cluster, primary_server): # def should_seed_db_users(server, dbname): # def setup_db_users(server, db, db_users): # def _mongo_add_user(server, db, username, password, read_only=False, # num_tries=1): # def list_database_users(server, db): # def setup_server_db_users(server, dbname, db_users): # def prepend_global_admin_user(other_users, server): # def setup_server_admin_users(server): # def setup_root_admin_user(server, admin_users): # def setup_server_local_users(server): # def read_seed_password(dbname, username): # def set_server_login_user(server, dbname, username, password): # def get_server_login_user(server, dbname): # def _get_server_login_record(server, create_new=True): # def is_system_user(username): # LOGIN_USERS = {} # # Path: mongoctl/config.py # def get_cluster_member_alt_address_mapping(): # return get_mongoctl_config_val('clusterMemberAltAddressesMapping', {}) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_error(msg): # get_logger().error(msg) # # def log_db_command(cmd): # log_info( "Executing db command %s" % utils.document_pretty_string(cmd)) . Output only the next line.
tag_mapping = get_cluster_member_alt_address_mapping()
Based on the snippet: <|code_start|> ignore = ['host', 'server'] for key,value in self.__document__.items(): if key not in ignore : member_conf[key] = value self._apply_alt_address_mapping(member_conf) return member_conf ########################################################################### def _apply_alt_address_mapping(self, member_conf): # Not applicable to arbiters if self.is_arbiter(): return tag_mapping = get_cluster_member_alt_address_mapping() if not tag_mapping: return tags = member_conf.get("tags", {}) for tag_name, alt_address_prop in tag_mapping.items(): alt_address = self.get_server().get_property(alt_address_prop) # set the alt address if it is different than host if alt_address and alt_address != member_conf['host']: tags[tag_name] = alt_address else: <|code_end|> , predict the immediate next line with the help of imports: import mongoctl.repository as repository from cluster import Cluster from mongoctl import users from base import DocumentWrapper from mongoctl.utils import * from bson import DBRef from mongoctl.config import get_cluster_member_alt_address_mapping from mongoctl.mongoctl_logging import log_verbose, log_error, log_db_command from mongoctl.prompt import prompt_confirm and context (classes, functions, sometimes code) from other files: # Path: mongoctl/users.py # def parse_global_login_user_arg(username, password, server_id): # def get_global_login_user(server, dbname): # def setup_server_users(server): # def setup_cluster_users(cluster, primary_server): # def should_seed_db_users(server, dbname): # def setup_db_users(server, db, db_users): # def _mongo_add_user(server, db, username, password, read_only=False, # num_tries=1): # def list_database_users(server, db): # def setup_server_db_users(server, dbname, db_users): # def prepend_global_admin_user(other_users, server): # def setup_server_admin_users(server): # def setup_root_admin_user(server, admin_users): # def setup_server_local_users(server): # def read_seed_password(dbname, username): # def set_server_login_user(server, dbname, username, password): # def get_server_login_user(server, dbname): # def _get_server_login_record(server, create_new=True): # def is_system_user(username): # LOGIN_USERS = {} # # Path: mongoctl/config.py # def get_cluster_member_alt_address_mapping(): # return get_mongoctl_config_val('clusterMemberAltAddressesMapping', {}) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_error(msg): # get_logger().error(msg) # # def log_db_command(cmd): # log_info( "Executing db command %s" % utils.document_pretty_string(cmd)) . Output only the next line.
log_verbose("No alt address tag value created for alt address"
Given snippet: <|code_start|> # set the alt address if it is different than host if alt_address and alt_address != member_conf['host']: tags[tag_name] = alt_address else: log_verbose("No alt address tag value created for alt address" " mapping '%s=%s' for member \n%s" % (tag_name, alt_address_prop, self)) # set the tags property of the member config if there are any if tags: log_verbose("Member '%s' tags : %s" % (member_conf['host'], tags)) member_conf['tags'] = tags ########################################################################### def read_rs_config(self): try: server = self.get_server() return server.get_rs_config() except Exception, ex: log_exception(ex) return None ########################################################################### def is_valid(self): try: self.validate() return True except Exception, e: <|code_end|> , continue by predicting the next line. Consider current file imports: import mongoctl.repository as repository from cluster import Cluster from mongoctl import users from base import DocumentWrapper from mongoctl.utils import * from bson import DBRef from mongoctl.config import get_cluster_member_alt_address_mapping from mongoctl.mongoctl_logging import log_verbose, log_error, log_db_command from mongoctl.prompt import prompt_confirm and context: # Path: mongoctl/users.py # def parse_global_login_user_arg(username, password, server_id): # def get_global_login_user(server, dbname): # def setup_server_users(server): # def setup_cluster_users(cluster, primary_server): # def should_seed_db_users(server, dbname): # def setup_db_users(server, db, db_users): # def _mongo_add_user(server, db, username, password, read_only=False, # num_tries=1): # def list_database_users(server, db): # def setup_server_db_users(server, dbname, db_users): # def prepend_global_admin_user(other_users, server): # def setup_server_admin_users(server): # def setup_root_admin_user(server, admin_users): # def setup_server_local_users(server): # def read_seed_password(dbname, username): # def set_server_login_user(server, dbname, username, password): # def get_server_login_user(server, dbname): # def _get_server_login_record(server, create_new=True): # def is_system_user(username): # LOGIN_USERS = {} # # Path: mongoctl/config.py # def get_cluster_member_alt_address_mapping(): # return get_mongoctl_config_val('clusterMemberAltAddressesMapping', {}) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_error(msg): # get_logger().error(msg) # # def log_db_command(cmd): # log_info( "Executing db command %s" % utils.document_pretty_string(cmd)) which might include code, classes, or functions. Output only the next line.
log_error("%s" % e)
Predict the next line for this snippet: <|code_start|> return False ########################################################################### def initialize_replicaset(self, suggested_primary_server=None): log_info("Initializing replica set cluster '%s' %s..." % (self.id, "" if suggested_primary_server is None else "to contain only server '%s'" % suggested_primary_server.id)) ##### Determine primary server log_info("Determining which server should be primary...") primary_server = suggested_primary_server if primary_server is None: primary_member = self.suggest_primary_member() if primary_member is not None: primary_server = primary_member.get_server() if primary_server is None: raise MongoctlException("Unable to determine primary server." " At least one member server has" " to be online.") log_info("Selected server '%s' as primary." % primary_server.id) init_cmd = self.get_replicaset_init_all_db_command( suggested_primary_server) try: <|code_end|> with the help of current file imports: import mongoctl.repository as repository from cluster import Cluster from mongoctl import users from base import DocumentWrapper from mongoctl.utils import * from bson import DBRef from mongoctl.config import get_cluster_member_alt_address_mapping from mongoctl.mongoctl_logging import log_verbose, log_error, log_db_command from mongoctl.prompt import prompt_confirm and context from other files: # Path: mongoctl/users.py # def parse_global_login_user_arg(username, password, server_id): # def get_global_login_user(server, dbname): # def setup_server_users(server): # def setup_cluster_users(cluster, primary_server): # def should_seed_db_users(server, dbname): # def setup_db_users(server, db, db_users): # def _mongo_add_user(server, db, username, password, read_only=False, # num_tries=1): # def list_database_users(server, db): # def setup_server_db_users(server, dbname, db_users): # def prepend_global_admin_user(other_users, server): # def setup_server_admin_users(server): # def setup_root_admin_user(server, admin_users): # def setup_server_local_users(server): # def read_seed_password(dbname, username): # def set_server_login_user(server, dbname, username, password): # def get_server_login_user(server, dbname): # def _get_server_login_record(server, create_new=True): # def is_system_user(username): # LOGIN_USERS = {} # # Path: mongoctl/config.py # def get_cluster_member_alt_address_mapping(): # return get_mongoctl_config_val('clusterMemberAltAddressesMapping', {}) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_error(msg): # get_logger().error(msg) # # def log_db_command(cmd): # log_info( "Executing db command %s" % utils.document_pretty_string(cmd)) , which may contain function names, class names, or code. Output only the next line.
log_db_command(init_cmd)
Given snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # list clusters command ############################################################################### def list_clusters_command(parsed_options): clusters = repository.lookup_all_clusters() if not clusters or len(clusters) < 1: <|code_end|> , continue by predicting the next line. Consider current file imports: import mongoctl.repository as repository from mongoctl.mongoctl_logging import log_info from mongoctl.utils import to_string and context: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def to_string(thing): # return "" if thing is None else str(thing) which might include code, classes, or functions. Output only the next line.
log_info("No clusters configured")
Given snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # list clusters command ############################################################################### def list_clusters_command(parsed_options): clusters = repository.lookup_all_clusters() if not clusters or len(clusters) < 1: log_info("No clusters configured") return # sort clusters by id clusters = sorted(clusters, key=lambda c: c.id) bar = "-"*80 print bar formatter = "%-25s %-40s %s" print formatter % ("_ID", "DESCRIPTION", "MEMBERS") print bar for cluster in clusters: <|code_end|> , continue by predicting the next line. Consider current file imports: import mongoctl.repository as repository from mongoctl.mongoctl_logging import log_info from mongoctl.utils import to_string and context: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def to_string(thing): # return "" if thing is None else str(thing) which might include code, classes, or functions. Output only the next line.
desc = to_string(cluster.get_description())
Continue the code snippet: <|code_start|>############################################################################### # This is mongodb's default dbpath DEFAULT_DBPATH='/data/db' LOCK_FILE_NAME = "mongod.lock" ############################################################################### # MongodServer Class ############################################################################### class MongodServer(server.Server): ########################################################################### # Constructor ########################################################################### def __init__(self, server_doc): super(MongodServer, self).__init__(server_doc) ########################################################################### # Properties ########################################################################### def get_db_path(self): dbpath = self.get_cmd_option("dbpath") if not dbpath: dbpath = super(MongodServer, self).get_server_home() if not dbpath: dbpath = DEFAULT_DBPATH <|code_end|> . Use current file imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and context (classes, functions, or code) from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
return resolve_path(dbpath)
Next line prediction: <|code_start|> ########################################################################### def get_repl_lag(self, master_status): """ Given two 'members' elements from rs.status(), return lag between their optimes (in secs). """ member_status = self.get_member_rs_status() if not member_status: raise MongoctlException("Unable to determine replicaset status for" " member '%s'" % self.id) return get_member_repl_lag(member_status, master_status) ########################################################################### def get_environment_variables(self): env_vars = super(MongodServer, self).get_environment_variables() or {} # default TCMALLOC_AGGRESSIVE_DECOMMIT as needed if not set if "TCMALLOC_AGGRESSIVE_DECOMMIT" not in env_vars and self.needs_tcmalloc_aggressive_decommit(): log_info("Defaulting TCMALLOC_AGGRESSIVE_DECOMMIT=y") env_vars["TCMALLOC_AGGRESSIVE_DECOMMIT"] = "y" return env_vars ########################################################################### def needs_tcmalloc_aggressive_decommit(self): version = self.get_mongo_version_info() <|code_end|> . Use current file imports: (import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info) and context including class names, function names, or small code snippets from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
return self.is_wired_tiger() and version < make_version_info("3.2.10") and system_memory_size_gbs() < 30
Predict the next line after this snippet: <|code_start|> return member except (Exception,RuntimeError), e: log_debug("Cannot get member rs status from server '%s'." " cause: %s" % (self.id, e)) log_exception(e) return None ########################################################################### def is_primary(self): master_result = self.is_master_command() if master_result: return master_result.get("ismaster") ########################################################################### def is_secondary(self): master_result = self.is_master_command() if master_result: return master_result.get("secondary") ########################################################################### def is_master_command(self): try: if self.is_online(): result = self.db_command({"isMaster" : 1}, "admin") return result except(Exception, RuntimeError),e: <|code_end|> using the current file's imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and any relevant context from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
log_verbose("isMaster command failed on server '%s'. Cause %s" %
Based on the snippet: <|code_start|> def command_needs_auth(self, dbname, cmd): # isMaster command does not need auth if "isMaster" in cmd or "ismaster" in cmd: return False if 'shutdown' in cmd and self.is_arbiter_server(): return False # otherwise use default behavior return super(MongodServer, self).command_needs_auth(dbname, cmd) ########################################################################### def get_mongo_uri_template(self, db=None): if not db: if self.is_auth(): db = "/[dbname]" else: db = "" else: db = "/" + db creds = "[dbuser]:[dbpass]@" if self.is_auth() else "" return "mongodb://%s%s%s" % (creds, self.get_address_display(), db) ########################################################################### def get_rs_status(self): try: rs_status_cmd = SON([('replSetGetStatus', 1)]) rs_status = self.db_command(rs_status_cmd, 'admin') return rs_status except (Exception,RuntimeError), e: <|code_end|> , predict the immediate next line with the help of imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and context (classes, functions, sometimes code) from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
log_debug("Cannot get rs status from server '%s'. cause: %s" %
Next line prediction: <|code_start|> if "isMaster" in cmd or "ismaster" in cmd: return False if 'shutdown' in cmd and self.is_arbiter_server(): return False # otherwise use default behavior return super(MongodServer, self).command_needs_auth(dbname, cmd) ########################################################################### def get_mongo_uri_template(self, db=None): if not db: if self.is_auth(): db = "/[dbname]" else: db = "" else: db = "/" + db creds = "[dbuser]:[dbpass]@" if self.is_auth() else "" return "mongodb://%s%s%s" % (creds, self.get_address_display(), db) ########################################################################### def get_rs_status(self): try: rs_status_cmd = SON([('replSetGetStatus', 1)]) rs_status = self.db_command(rs_status_cmd, 'admin') return rs_status except (Exception,RuntimeError), e: log_debug("Cannot get rs status from server '%s'. cause: %s" % (self.id, e)) <|code_end|> . Use current file imports: (import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info) and context including class names, function names, or small code snippets from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
log_exception(e)
Given snippet: <|code_start|> ########################################################################### def has_joined_replica(self): master_result = self.is_master_command() if master_result: return (master_result.get("ismaster") or master_result.get("arbiterOnly") or master_result.get("secondary")) ########################################################################### def get_repl_lag(self, master_status): """ Given two 'members' elements from rs.status(), return lag between their optimes (in secs). """ member_status = self.get_member_rs_status() if not member_status: raise MongoctlException("Unable to determine replicaset status for" " member '%s'" % self.id) return get_member_repl_lag(member_status, master_status) ########################################################################### def get_environment_variables(self): env_vars = super(MongodServer, self).get_environment_variables() or {} # default TCMALLOC_AGGRESSIVE_DECOMMIT as needed if not set if "TCMALLOC_AGGRESSIVE_DECOMMIT" not in env_vars and self.needs_tcmalloc_aggressive_decommit(): <|code_end|> , continue by predicting the next line. Consider current file imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and context: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info which might include code, classes, or functions. Output only the next line.
log_info("Defaulting TCMALLOC_AGGRESSIVE_DECOMMIT=y")
Predict the next line for this snippet: <|code_start|> return master_result.get("secondary") ########################################################################### def is_master_command(self): try: if self.is_online(): result = self.db_command({"isMaster" : 1}, "admin") return result except(Exception, RuntimeError),e: log_verbose("isMaster command failed on server '%s'. Cause %s" % (self.id, e)) ########################################################################### def has_joined_replica(self): master_result = self.is_master_command() if master_result: return (master_result.get("ismaster") or master_result.get("arbiterOnly") or master_result.get("secondary")) ########################################################################### def get_repl_lag(self, master_status): """ Given two 'members' elements from rs.status(), return lag between their optimes (in secs). """ member_status = self.get_member_rs_status() if not member_status: <|code_end|> with the help of current file imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and context from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info , which may contain function names, class names, or code. Output only the next line.
raise MongoctlException("Unable to determine replicaset status for"
Continue the code snippet: <|code_start|> ########################################################################### def get_repl_lag(self, master_status): """ Given two 'members' elements from rs.status(), return lag between their optimes (in secs). """ member_status = self.get_member_rs_status() if not member_status: raise MongoctlException("Unable to determine replicaset status for" " member '%s'" % self.id) return get_member_repl_lag(member_status, master_status) ########################################################################### def get_environment_variables(self): env_vars = super(MongodServer, self).get_environment_variables() or {} # default TCMALLOC_AGGRESSIVE_DECOMMIT as needed if not set if "TCMALLOC_AGGRESSIVE_DECOMMIT" not in env_vars and self.needs_tcmalloc_aggressive_decommit(): log_info("Defaulting TCMALLOC_AGGRESSIVE_DECOMMIT=y") env_vars["TCMALLOC_AGGRESSIVE_DECOMMIT"] = "y" return env_vars ########################################################################### def needs_tcmalloc_aggressive_decommit(self): version = self.get_mongo_version_info() <|code_end|> . Use current file imports: import server from mongoctl.utils import resolve_path, system_memory_size_gbs from mongoctl.mongoctl_logging import log_verbose, log_debug, log_exception, \ log_warning, log_info from bson.son import SON from mongoctl.errors import MongoctlException from replicaset_cluster import ReplicaSetCluster, get_member_repl_lag from sharded_cluster import ShardedCluster from mongoctl.mongodb_version import make_version_info and context (classes, functions, or code) from other files: # Path: mongoctl/utils.py # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def system_memory_size_gbs(): # """ # credit https://stackoverflow.com/questions/22102999/get-total-physical-memory-in-python # :return: total system memory size in gbs # """ # # mem_bytes = psutil.virtual_memory().total # return mem_bytes/(1024.**3) # # Path: mongoctl/mongoctl_logging.py # def log_verbose(msg): # get_logger().log(VERBOSE, msg) # # def log_debug(msg): # get_logger().debug(msg) # # def log_exception(exception): # log_debug("EXCEPTION: %s" % exception) # log_debug(traceback.format_exc()) # # def log_warning(msg): # get_logger().warning(msg) # # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info . Output only the next line.
return self.is_wired_tiger() and version < make_version_info("3.2.10") and system_memory_size_gbs() < 30
Predict the next line after this snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # list servers command ############################################################################### def list_servers_command(parsed_options): servers = repository.lookup_all_servers() if not servers or len(servers) < 1: <|code_end|> using the current file's imports: import mongoctl.repository as repository from mongoctl.mongoctl_logging import log_info from mongoctl.utils import to_string and any relevant context from other files: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def to_string(thing): # return "" if thing is None else str(thing) . Output only the next line.
log_info("No servers have been configured.")
Here is a snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # list servers command ############################################################################### def list_servers_command(parsed_options): servers = repository.lookup_all_servers() if not servers or len(servers) < 1: log_info("No servers have been configured.") return servers = sorted(servers, key=lambda s: s.id) bar = "-"*80 print bar formatter = "%-25s %-40s %s" print formatter % ("_ID", "DESCRIPTION", "CONNECT TO") print bar for server in servers: print formatter % (server.id, <|code_end|> . Write the next line using the current file imports: import mongoctl.repository as repository from mongoctl.mongoctl_logging import log_info from mongoctl.utils import to_string and context from other files: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def to_string(thing): # return "" if thing is None else str(thing) , which may include functions, classes, or code. Output only the next line.
to_string(server.get_description()),
Given the code snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # print uri command ############################################################################### def print_uri_command(parsed_options): id = parsed_options.id db = parsed_options.db # check if the id is a server id server = repository.lookup_server(id) if server: print server.get_mongo_uri_template(db=db) else: cluster = repository.lookup_cluster(id) if cluster: print cluster.get_mongo_uri_template(db=db) else: <|code_end|> , generate the next line using the imports in this file: import mongoctl.repository as repository from mongoctl.errors import MongoctlException and context (functions, classes, or occasionally code) from other files: # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause . Output only the next line.
raise MongoctlException("Cannot find a server or a cluster with"
Given the following code snippet before the placeholder: <|code_start|> shutdown_success = mongo_stop_server(server, pid, force=False) if not can_stop_mongoly or not shutdown_success: log_verbose(" ... taking more forceful measures ... ") shutdown_success = \ prompt_or_force_stop_server(server, pid, force, try_mongo_force=can_stop_mongoly) if shutdown_success: log_info("Server '%s' has stopped." % server.id) else: raise MongoctlException("Unable to stop server '%s'." % server.id) ############################################################################### def step_down_if_needed(server, force): ## if server is a primary replica member then step down if server.is_primary(): if force: step_server_down(server, force) else: prompt_step_server_down(server, force) ############################################################################### def mongo_stop_server(server, pid, force=False): try: shutdown_cmd = SON( [('shutdown', 1),('force', force)]) log_info("\nSending the following command to %s:\n%s\n" % (server.get_connection_address(), <|code_end|> , predict the next line using imports from the current file: from bson.son import SON from mongoctl.utils import ( document_pretty_string, wait_for, kill_process, is_pid_alive ) from mongoctl.mongoctl_logging import * from mongoctl.errors import MongoctlException from start import server_stopped_predicate from mongoctl.prompt import prompt_execute_task import mongoctl.repository import mongoctl.objects.server and context including class names, function names, and sometimes code from other files: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) # # def wait_for(predicate, timeout=None, sleep_duration=2, grace=True): # start_time = now() # must_retry = may_retry = not predicate() # # if must_retry and grace: # # optimizing for predicates whose first invocations may be slooooooow # log_verbose("GRACE: First eval finished in %d secs - resetting timer." % # (now() - start_time)) # start_time = now() # # while must_retry and may_retry: # # must_retry = not predicate() # if must_retry: # net_time = now() - start_time # if timeout and net_time + sleep_duration > timeout: # may_retry = False # else: # left = "[-%d sec] " % (timeout - net_time) if timeout else "" # log_info("-- waiting %s--" % left) # time.sleep(sleep_duration) # # return not must_retry # # def kill_process(pid, force=False): # sig = signal.SIGKILL if force else signal.SIGTERM # try: # os.kill(pid, sig) # return True # except OSError: # return False # # def is_pid_alive(pid): # # try: # os.kill(pid,0) # return True # except OSError: # return False # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause . Output only the next line.
document_pretty_string(shutdown_cmd)))
Given the code snippet: <|code_start|> try_mongo_force=can_stop_mongoly) if shutdown_success: log_info("Server '%s' has stopped." % server.id) else: raise MongoctlException("Unable to stop server '%s'." % server.id) ############################################################################### def step_down_if_needed(server, force): ## if server is a primary replica member then step down if server.is_primary(): if force: step_server_down(server, force) else: prompt_step_server_down(server, force) ############################################################################### def mongo_stop_server(server, pid, force=False): try: shutdown_cmd = SON( [('shutdown', 1),('force', force)]) log_info("\nSending the following command to %s:\n%s\n" % (server.get_connection_address(), document_pretty_string(shutdown_cmd))) server.disconnecting_db_command(shutdown_cmd, "admin") log_info("Will now wait for server '%s' to stop." % server.id) # Check that the server has stopped stop_pred = server_stopped_predicate(server, pid) <|code_end|> , generate the next line using the imports in this file: from bson.son import SON from mongoctl.utils import ( document_pretty_string, wait_for, kill_process, is_pid_alive ) from mongoctl.mongoctl_logging import * from mongoctl.errors import MongoctlException from start import server_stopped_predicate from mongoctl.prompt import prompt_execute_task import mongoctl.repository import mongoctl.objects.server and context (functions, classes, or occasionally code) from other files: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) # # def wait_for(predicate, timeout=None, sleep_duration=2, grace=True): # start_time = now() # must_retry = may_retry = not predicate() # # if must_retry and grace: # # optimizing for predicates whose first invocations may be slooooooow # log_verbose("GRACE: First eval finished in %d secs - resetting timer." % # (now() - start_time)) # start_time = now() # # while must_retry and may_retry: # # must_retry = not predicate() # if must_retry: # net_time = now() - start_time # if timeout and net_time + sleep_duration > timeout: # may_retry = False # else: # left = "[-%d sec] " % (timeout - net_time) if timeout else "" # log_info("-- waiting %s--" % left) # time.sleep(sleep_duration) # # return not must_retry # # def kill_process(pid, force=False): # sig = signal.SIGKILL if force else signal.SIGTERM # try: # os.kill(pid, sig) # return True # except OSError: # return False # # def is_pid_alive(pid): # # try: # os.kill(pid,0) # return True # except OSError: # return False # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause . Output only the next line.
wait_for(stop_pred,timeout=MAX_SHUTDOWN_WAIT)
Given snippet: <|code_start|> return False else: return True except Exception, e: log_exception(e) log_error("Failed to gracefully stop server '%s'. Cause: %s" % (server.id, e)) return False ############################################################################### def force_stop_server(server, pid, try_mongo_force=True): success = False # try mongo force stop if server is still online if server.is_online() and try_mongo_force: success = mongo_stop_server(server, pid, force=True) if not success or not try_mongo_force: success = kill_stop_server(server, pid) return success ############################################################################### def kill_stop_server(server, pid): if pid is None: log_error("Cannot forcibly stop the server because the server's process" " ID cannot be determined; pid file '%s' does not exist." % server.get_pid_file_path()) return False log_info("Sending kill -9 (SIGKILL) signal to server '%s' (pid=%s)..." % (server.id, pid)) <|code_end|> , continue by predicting the next line. Consider current file imports: from bson.son import SON from mongoctl.utils import ( document_pretty_string, wait_for, kill_process, is_pid_alive ) from mongoctl.mongoctl_logging import * from mongoctl.errors import MongoctlException from start import server_stopped_predicate from mongoctl.prompt import prompt_execute_task import mongoctl.repository import mongoctl.objects.server and context: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) # # def wait_for(predicate, timeout=None, sleep_duration=2, grace=True): # start_time = now() # must_retry = may_retry = not predicate() # # if must_retry and grace: # # optimizing for predicates whose first invocations may be slooooooow # log_verbose("GRACE: First eval finished in %d secs - resetting timer." % # (now() - start_time)) # start_time = now() # # while must_retry and may_retry: # # must_retry = not predicate() # if must_retry: # net_time = now() - start_time # if timeout and net_time + sleep_duration > timeout: # may_retry = False # else: # left = "[-%d sec] " % (timeout - net_time) if timeout else "" # log_info("-- waiting %s--" % left) # time.sleep(sleep_duration) # # return not must_retry # # def kill_process(pid, force=False): # sig = signal.SIGKILL if force else signal.SIGTERM # try: # os.kill(pid, sig) # return True # except OSError: # return False # # def is_pid_alive(pid): # # try: # os.kill(pid,0) # return True # except OSError: # return False # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause which might include code, classes, or functions. Output only the next line.
kill_process(pid, force=True)
Predict the next line for this snippet: <|code_start|> log_error("Failed to gracefully stop server '%s'. Cause: %s" % (server.id, e)) return False ############################################################################### def force_stop_server(server, pid, try_mongo_force=True): success = False # try mongo force stop if server is still online if server.is_online() and try_mongo_force: success = mongo_stop_server(server, pid, force=True) if not success or not try_mongo_force: success = kill_stop_server(server, pid) return success ############################################################################### def kill_stop_server(server, pid): if pid is None: log_error("Cannot forcibly stop the server because the server's process" " ID cannot be determined; pid file '%s' does not exist." % server.get_pid_file_path()) return False log_info("Sending kill -9 (SIGKILL) signal to server '%s' (pid=%s)..." % (server.id, pid)) kill_process(pid, force=True) log_info("Will now wait for server '%s' (pid=%s) to die." % (server.id, pid)) wait_for(pid_dead_predicate(pid), timeout=MAX_SHUTDOWN_WAIT) <|code_end|> with the help of current file imports: from bson.son import SON from mongoctl.utils import ( document_pretty_string, wait_for, kill_process, is_pid_alive ) from mongoctl.mongoctl_logging import * from mongoctl.errors import MongoctlException from start import server_stopped_predicate from mongoctl.prompt import prompt_execute_task import mongoctl.repository import mongoctl.objects.server and context from other files: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) # # def wait_for(predicate, timeout=None, sleep_duration=2, grace=True): # start_time = now() # must_retry = may_retry = not predicate() # # if must_retry and grace: # # optimizing for predicates whose first invocations may be slooooooow # log_verbose("GRACE: First eval finished in %d secs - resetting timer." % # (now() - start_time)) # start_time = now() # # while must_retry and may_retry: # # must_retry = not predicate() # if must_retry: # net_time = now() - start_time # if timeout and net_time + sleep_duration > timeout: # may_retry = False # else: # left = "[-%d sec] " % (timeout - net_time) if timeout else "" # log_info("-- waiting %s--" % left) # time.sleep(sleep_duration) # # return not must_retry # # def kill_process(pid, force=False): # sig = signal.SIGKILL if force else signal.SIGTERM # try: # os.kill(pid, sig) # return True # except OSError: # return False # # def is_pid_alive(pid): # # try: # os.kill(pid,0) # return True # except OSError: # return False # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause , which may contain function names, class names, or code. Output only the next line.
if not is_pid_alive(pid):
Next line prediction: <|code_start|> elif server.is_server_pid_alive(): log_info("Unable to issue 'shutdown' command to server '%s'. The server is not responding." % server.id) can_stop_mongoly = False else: log_info("Server '%s' is not running." % server.id) return pid = server.get_pid() pid_disp = pid if pid else "[Cannot be determined]" log_info("Stopping server '%s' (pid=%s)..." % (server.id, pid_disp)) # log server activity stop server.log_server_activity("stop") # TODO: Enable this again when stabilized # step_down_if_needed(server, force) if can_stop_mongoly: log_verbose(" ... issuing db 'shutdown' command ... ") shutdown_success = mongo_stop_server(server, pid, force=False) if not can_stop_mongoly or not shutdown_success: log_verbose(" ... taking more forceful measures ... ") shutdown_success = \ prompt_or_force_stop_server(server, pid, force, try_mongo_force=can_stop_mongoly) if shutdown_success: log_info("Server '%s' has stopped." % server.id) else: <|code_end|> . Use current file imports: (from bson.son import SON from mongoctl.utils import ( document_pretty_string, wait_for, kill_process, is_pid_alive ) from mongoctl.mongoctl_logging import * from mongoctl.errors import MongoctlException from start import server_stopped_predicate from mongoctl.prompt import prompt_execute_task import mongoctl.repository import mongoctl.objects.server) and context including class names, function names, or small code snippets from other files: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) # # def wait_for(predicate, timeout=None, sleep_duration=2, grace=True): # start_time = now() # must_retry = may_retry = not predicate() # # if must_retry and grace: # # optimizing for predicates whose first invocations may be slooooooow # log_verbose("GRACE: First eval finished in %d secs - resetting timer." % # (now() - start_time)) # start_time = now() # # while must_retry and may_retry: # # must_retry = not predicate() # if must_retry: # net_time = now() - start_time # if timeout and net_time + sleep_duration > timeout: # may_retry = False # else: # left = "[-%d sec] " % (timeout - net_time) if timeout else "" # log_info("-- waiting %s--" % left) # time.sleep(sleep_duration) # # return not must_retry # # def kill_process(pid, force=False): # sig = signal.SIGKILL if force else signal.SIGTERM # try: # os.kill(pid, sig) # return True # except OSError: # return False # # def is_pid_alive(pid): # # try: # os.kill(pid,0) # return True # except OSError: # return False # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause . Output only the next line.
raise MongoctlException("Unable to stop server '%s'." %
Here is a snippet: <|code_start|># The MIT License # Copyright (c) 2012 ObjectLabs Corporation # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __author__ = 'aalkhatib' class VersionFunctionsTest(unittest.TestCase): def test_version_functions(self): <|code_end|> . Write the next line using the current file imports: import unittest from mongoctl.mongodb_version import make_version_info, is_valid_version and context from other files: # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # def is_valid_version(version_number): # return suggest_normalized_version(version_number) is not None , which may include functions, classes, or code. Output only the next line.
self.assertTrue(make_version_info("1.2.0") < make_version_info("1.2.1"))
Given the code snippet: <|code_start|># a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __author__ = 'aalkhatib' class VersionFunctionsTest(unittest.TestCase): def test_version_functions(self): self.assertTrue(make_version_info("1.2.0") < make_version_info("1.2.1")) self.assertFalse(make_version_info("1.2.0") < make_version_info("1.2.0")) self.assertFalse(make_version_info("1.2.0") < make_version_info("1.2.0C")) self.assertFalse(make_version_info("1.2.0-rc1") < make_version_info("1.2.0-rc0")) self.assertTrue(make_version_info("1.2.0-rc0") < make_version_info("1.2.0-rc1")) self.assertTrue(make_version_info("1.2.0-rc0") < make_version_info("1.2.0")) self.assertTrue(make_version_info("1.2.0-rc0") < make_version_info("1.2.1")) <|code_end|> , generate the next line using the imports in this file: import unittest from mongoctl.mongodb_version import make_version_info, is_valid_version and context (functions, classes, or occasionally code) from other files: # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # def is_valid_version(version_number): # return suggest_normalized_version(version_number) is not None . Output only the next line.
self.assertTrue(is_valid_version("1.0.1"))
Continue the code snippet: <|code_start|> shard_member.get_server().id == shard_id) or (shard_member.get_cluster() and shard_member.get_cluster().id == shard_id)): return shard_member ########################################################################### def get_config_db_address(self): if isinstance(self.config_servers, list): addresses = map(lambda s: s.get_address(), self.config_servers) return ",".join(addresses) elif isinstance(self.config_servers, ReplicaSetCluster): return self.config_servers.get_replica_address() ########################################################################### def get_shard_member_address(self, shard_member): if shard_member.get_server(): return shard_member.get_server().get_address() elif shard_member.get_cluster(): cluster_member_addresses = [] for cluster_member in shard_member.get_cluster().get_members(): cluster_member_addresses.append( cluster_member.get_server().get_address()) return "%s/%s" % (shard_member.get_cluster().id, ",".join(cluster_member_addresses)) ########################################################################### def configure_sharded_cluster(self): sh_list = self.list_shards() if sh_list and sh_list.get("shards"): <|code_end|> . Use current file imports: import mongoctl.repository as repository import time from cluster import Cluster from server import Server from replicaset_cluster import ReplicaSetCluster from base import DocumentWrapper from bson import DBRef from mongoctl.mongoctl_logging import log_info from mongoctl.utils import document_pretty_string and context (classes, functions, or code) from other files: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) . Output only the next line.
log_info("Shard cluster already configured. Will only be adding"
Based on the snippet: <|code_start|> cluster_member_addresses.append( cluster_member.get_server().get_address()) return "%s/%s" % (shard_member.get_cluster().id, ",".join(cluster_member_addresses)) ########################################################################### def configure_sharded_cluster(self): sh_list = self.list_shards() if sh_list and sh_list.get("shards"): log_info("Shard cluster already configured. Will only be adding" " new shards as needed...") for shard_member in self.shards: self.add_shard(shard_member.get_member_cluster_or_server()) ########################################################################### def add_shard(self, shard): log_info("Adding shard '%s' to ShardedCluster '%s' " % (shard.id, self.id)) if self.is_shard_configured(shard): log_info("Shard '%s' already added! Nothing to do..." % shard.id) return mongos = self.get_any_online_mongos() shard_member = self.get_shard_member(shard) cmd = self.get_add_shard_command(shard_member) configured_shards = self.list_shards() log_info("Current configured shards: \n%s" % <|code_end|> , predict the immediate next line with the help of imports: import mongoctl.repository as repository import time from cluster import Cluster from server import Server from replicaset_cluster import ReplicaSetCluster from base import DocumentWrapper from bson import DBRef from mongoctl.mongoctl_logging import log_info from mongoctl.utils import document_pretty_string and context (classes, functions, sometimes code) from other files: # Path: mongoctl/mongoctl_logging.py # def log_info(msg): # get_logger().info(msg) # # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) . Output only the next line.
document_pretty_string(configured_shards))
Given the following code snippet before the placeholder: <|code_start|>class VersionPreference(object): EXACT = "EXACT" MAJOR_GE = "MAJOR_GE" LATEST_STABLE = "LATEST_STABLE" EXACT_OR_MINOR = "EXACT_OR_MINOR" LATEST_MINOR = "LATEST_MINOR" DEFAULT = "DEFAULT" def extract_mongo_exe_options(parsed_args, supported_options): options_extract = {} # Iterating over parsed options dict # Yeah in a hacky way since there is no clean documented way of doing that # See http://bugs.python.org/issue11076 for more details # this should be changed when argparse provides a cleaner way for (option_name,option_val) in parsed_args.__dict__.items(): if option_name in supported_options and option_val is not None: options_extract[option_name] = option_val return options_extract ############################################################################### def get_mongo_executable(version_info, executable_name, version_check_pref=VersionPreference.EXACT): mongo_home = os.getenv(MONGO_HOME_ENV_VAR) <|code_end|> , predict the next line using imports from the current file: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context including class names, function names, and sometimes code from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
mongo_installs_dir = config.get_mongodb_installs_dir()
Predict the next line for this snippet: <|code_start|> exe_version_tuples = find_all_executables(executable_name) if len(exe_version_tuples) > 0: selected_exe = best_executable_match(executable_name, exe_version_tuples, version_info, version_check_pref= version_check_pref) if selected_exe is not None: log_info("Using %s at '%s' version '%s'..." % (executable_name, selected_exe.path, selected_exe.version)) return selected_exe ## ok nothing found at all log_error("Unable to find a compatible '%s' executable " "for version %s (edition %s). You may need to run 'mongoctl " "install-mongodb %s %s' to install it.\n\n" "Here is your enviroment:\n\n" "$PATH=%s\n\n" "$MONGO_HOME=%s\n\n" "mongoDBInstallationsDirectory=%s (in mongoctl.config)" % (executable_name, ver_disp, mongodb_edition, ver_disp, "--edition %s" % mongodb_edition if mongodb_edition != MongoDBEdition.COMMUNITY else "", os.getenv("PATH"), mongo_home, mongo_installs_dir)) <|code_end|> with the help of current file imports: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] , which may contain function names, class names, or code. Output only the next line.
raise MongoctlException("Unable to find a compatible '%s' executable." % executable_name)
Given the following code snippet before the placeholder: <|code_start|> # Return nothing if nothing compatible if len(compatible_exes) == 0: return None # find the best fit compatible_exes.sort(key=lambda t: t[1]) exe = compatible_exes[-1] return mongo_exe_object(exe[0], exe[1]) ############################################################################### def get_exe_version_tuples(executables): exe_ver_tuples = [] for mongo_exe in executables: try: exe_version = mongo_exe_version(mongo_exe) exe_ver_tuples.append((mongo_exe, exe_version)) except Exception, e: log_exception(e) log_verbose("Skipping executable '%s': %s" % (mongo_exe, e)) return exe_ver_tuples ############################################################################### def exe_version_tuples_to_strs(exe_ver_tuples): strs = [] for mongo_exe,exe_version in exe_ver_tuples: strs.append("%s = %s" % (mongo_exe, exe_version)) return "\n".join(strs) ############################################################################### def is_valid_mongo_exe(path): <|code_end|> , predict the next line using imports from the current file: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context including class names, function names, and sometimes code from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
return path is not None and is_exe(path)
Using the snippet: <|code_start|> log_info("Using %s at '%s' version '%s'..." % (executable_name, selected_exe.path, selected_exe.version)) return selected_exe ## ok nothing found at all log_error("Unable to find a compatible '%s' executable " "for version %s (edition %s). You may need to run 'mongoctl " "install-mongodb %s %s' to install it.\n\n" "Here is your enviroment:\n\n" "$PATH=%s\n\n" "$MONGO_HOME=%s\n\n" "mongoDBInstallationsDirectory=%s (in mongoctl.config)" % (executable_name, ver_disp, mongodb_edition, ver_disp, "--edition %s" % mongodb_edition if mongodb_edition != MongoDBEdition.COMMUNITY else "", os.getenv("PATH"), mongo_home, mongo_installs_dir)) raise MongoctlException("Unable to find a compatible '%s' executable." % executable_name) ############################################################################### def find_all_executables(executable_name): # create a list of all available executables found and then return the best # match if applicable executables_found = [] ####### Look in $PATH <|code_end|> , determine the next line of code. You have imports: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context (class names, function names, or code) available: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
path_executable = which(executable_name)
Given the following code snippet before the placeholder: <|code_start|> "for version %s (edition %s). You may need to run 'mongoctl " "install-mongodb %s %s' to install it.\n\n" "Here is your enviroment:\n\n" "$PATH=%s\n\n" "$MONGO_HOME=%s\n\n" "mongoDBInstallationsDirectory=%s (in mongoctl.config)" % (executable_name, ver_disp, mongodb_edition, ver_disp, "--edition %s" % mongodb_edition if mongodb_edition != MongoDBEdition.COMMUNITY else "", os.getenv("PATH"), mongo_home, mongo_installs_dir)) raise MongoctlException("Unable to find a compatible '%s' executable." % executable_name) ############################################################################### def find_all_executables(executable_name): # create a list of all available executables found and then return the best # match if applicable executables_found = [] ####### Look in $PATH path_executable = which(executable_name) if path_executable is not None: add_to_executables_found(executables_found, path_executable) #### Look in $MONGO_HOME if set mongo_home = os.getenv(MONGO_HOME_ENV_VAR) if mongo_home is not None: <|code_end|> , predict the next line using imports from the current file: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context including class names, function names, and sometimes code from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
mongo_home = resolve_path(mongo_home)
Here is a snippet: <|code_start|> exe_version = mongo_exe_version(mongo_exe) exe_ver_tuples.append((mongo_exe, exe_version)) except Exception, e: log_exception(e) log_verbose("Skipping executable '%s': %s" % (mongo_exe, e)) return exe_ver_tuples ############################################################################### def exe_version_tuples_to_strs(exe_ver_tuples): strs = [] for mongo_exe,exe_version in exe_ver_tuples: strs.append("%s = %s" % (mongo_exe, exe_version)) return "\n".join(strs) ############################################################################### def is_valid_mongo_exe(path): return path is not None and is_exe(path) ############################################################################### def get_mongo_home_exe(mongo_home, executable_name): return os.path.join(mongo_home, 'bin', executable_name) ############################################################################### def mongo_exe_version(mongo_exe): mongod_path = os.path.join(os.path.dirname(mongo_exe), "mongod") try: re_expr = "v?((([0-9]+)\.([0-9]+)\.([0-9]+))([^, ]*))" <|code_end|> . Write the next line using the current file imports: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] , which may include functions, classes, or code. Output only the next line.
vers_spew = execute_command([mongod_path, "--version"])
Using the snippet: <|code_start|> return "\n".join(strs) ############################################################################### def is_valid_mongo_exe(path): return path is not None and is_exe(path) ############################################################################### def get_mongo_home_exe(mongo_home, executable_name): return os.path.join(mongo_home, 'bin', executable_name) ############################################################################### def mongo_exe_version(mongo_exe): mongod_path = os.path.join(os.path.dirname(mongo_exe), "mongod") try: re_expr = "v?((([0-9]+)\.([0-9]+)\.([0-9]+))([^, ]*))" vers_spew = execute_command([mongod_path, "--version"]) # only take first line of spew vers_spew_line = vers_spew.split('\n')[0] vers_grep = re.findall(re_expr, vers_spew_line) help_spew = execute_command([mongod_path, "--help"]) full_version = vers_grep[-1][0] if "subscription" in vers_spew or "enterprise" in vers_spew: edition = MongoDBEdition.ENTERPRISE elif "SSL" in help_spew: edition = MongoDBEdition.COMMUNITY_SSL else: edition = MongoDBEdition.COMMUNITY <|code_end|> , determine the next line of code. You have imports: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and context (class names, function names, or code) available: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
result = make_version_info(full_version, edition=edition)
Predict the next line after this snippet: <|code_start|> LATEST_STABLE = "LATEST_STABLE" EXACT_OR_MINOR = "EXACT_OR_MINOR" LATEST_MINOR = "LATEST_MINOR" DEFAULT = "DEFAULT" def extract_mongo_exe_options(parsed_args, supported_options): options_extract = {} # Iterating over parsed options dict # Yeah in a hacky way since there is no clean documented way of doing that # See http://bugs.python.org/issue11076 for more details # this should be changed when argparse provides a cleaner way for (option_name,option_val) in parsed_args.__dict__.items(): if option_name in supported_options and option_val is not None: options_extract[option_name] = option_val return options_extract ############################################################################### def get_mongo_executable(version_info, executable_name, version_check_pref=VersionPreference.EXACT): mongo_home = os.getenv(MONGO_HOME_ENV_VAR) mongo_installs_dir = config.get_mongodb_installs_dir() version_number = version_info and version_info.version_number mongodb_edition = version_info and (version_info.edition or <|code_end|> using the current file's imports: import os import re import mongoctl.repository as repository from mongoctl.mongoctl_logging import * from mongoctl import config from mongoctl.errors import MongoctlException from mongoctl.utils import is_exe, which, resolve_path, execute_command from mongoctl.mongodb_version import make_version_info, MongoDBEdition from mongoctl.mongo_uri_tools import is_mongo_uri and any relevant context from other files: # Path: mongoctl/config.py # MONGOCTL_CONF_FILE_NAME = "mongoctl.config" # def set_config_root(root_path): # def get_mongoctl_config_val(key, default=None): # def set_mongoctl_config_val(key, value): # def get_generate_key_file_conf(default=None): # def get_database_repository_conf(): # def get_file_repository_conf(): # def get_mongodb_installs_dir(): # def set_mongodb_installs_dir(installs_dir): # def get_default_users(): # def get_cluster_member_alt_address_mapping(): # def to_full_config_path(path_or_url): # def get_mongoctl_config(): # def read_config_json(name, path_or_url): # def read_json_string(path_or_url, validate_exists=True): # # Path: mongoctl/errors.py # class MongoctlException(Exception): # def __init__(self, message, cause=None): # super(MongoctlException, self).__init__(message) # self._cause = cause # # Path: mongoctl/utils.py # def is_exe(fpath): # return os.path.isfile(fpath) and os.access(fpath, os.X_OK) # # def which(program): # # fpath, fname = os.path.split(program) # if fpath: # if is_exe(program): # return program # else: # for path in os.environ["PATH"].split(os.pathsep): # exe_file = os.path.join(path, program) # if is_exe(exe_file): # return exe_file # return None # # def resolve_path(path): # # handle file uris # path = path.replace("file://", "") # # # expand vars # path = os.path.expandvars(custom_expanduser(path)) # # Turn relative paths to absolute # try: # path = os.path.abspath(path) # except OSError, e: # # handle the case where cwd does not exist # if "No such file or directory" in str(e): # pass # else: # raise # # return path # # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] # # Path: mongoctl/mongodb_version.py # def make_version_info(version_number, edition=None): # if version_number is None: # return None # # version_number = version_number.strip() # version_number = version_number.replace("-pre-" , "-pre") # version_info = MongoDBVersionInfo(version_number, edition=edition) # # # validate version string # if not is_valid_version_info(version_info): # raise MongoctlException("Invalid version '%s." % version_info) # else: # return version_info # # class MongoDBEdition(): # COMMUNITY = "community" # COMMUNITY_SSL = "community_ssl" # ENTERPRISE = "enterprise" # # ALL = [COMMUNITY, COMMUNITY_SSL, ENTERPRISE] . Output only the next line.
MongoDBEdition.COMMUNITY)
Predict the next line for this snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # Document Wrapper Class ############################################################################### class DocumentWrapper(object): ########################################################################### # Constructor ########################################################################### def __init__(self, document): self.__document__ = document ########################################################################### # Overridden Methods ########################################################################### def __str__(self): <|code_end|> with the help of current file imports: from mongoctl.utils import document_pretty_string and context from other files: # Path: mongoctl/utils.py # def document_pretty_string(document): # return json.dumps(document, indent=4, default=json_util.default) , which may contain function names, class names, or code. Output only the next line.
return document_pretty_string(self.__document__)
Using the snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # CONSTS ############################################################################### DEFAULT_TAIL_LINES = 15 ############################################################################### # tail log command ############################################################################### def tail_log_command(parsed_options): <|code_end|> , determine the next line of code. You have imports: import os from mongoctl.processes import create_subprocess from mongoctl.mongoctl_logging import * from mongoctl import repository from mongoctl.utils import execute_command and context (class names, function names, or code) available: # Path: mongoctl/repository.py # DEFAULT_SERVERS_FILE = "servers.config" # DEFAULT_CLUSTERS_FILE = "clusters.config" # DEFAULT_SERVERS_COLLECTION = "servers" # DEFAULT_CLUSTERS_COLLECTION = "clusters" # DEFAULT_ACTIVITY_COLLECTION = "logs.server-activity" # LOOKUP_TYPE_MEMBER = "members" # LOOKUP_TYPE_CONFIG_SVR = "configServers" # LOOKUP_TYPE_SHARDS = "shards" # LOOKUP_TYPE_ANY = [LOOKUP_TYPE_CONFIG_SVR, LOOKUP_TYPE_MEMBER, # LOOKUP_TYPE_SHARDS] # MONGOD_SERVER_CLASS_NAME = "mongoctl.objects.mongod.MongodServer" # MONGOS_ROUTER_CLASS_NAME = "mongoctl.objects.mongos.MongosServer" # SERVER_TYPE_MAP = { # "Mongod": MONGOD_SERVER_CLASS_NAME, # "ConfigMongod": MONGOD_SERVER_CLASS_NAME, # "Mongos": MONGOS_ROUTER_CLASS_NAME, # # === XXX deprecated XXX === # "mongod": MONGOD_SERVER_CLASS_NAME, # XXX deprecated # "mongos": MONGOS_ROUTER_CLASS_NAME, # XXX deprecated # } # def get_mongoctl_database(): # def has_db_repository(): # def has_file_repository(): # def has_commandline_servers_or_clusters(): # def consulting_db_repository(): # def is_db_repository_online(): # def _db_repo_connect(): # def validate_repositories(): # def set_commandline_servers_and_clusters(servers_json_str, clusters_json_str): # def clear_repository_cache(): # def lookup_server(server_id): # def lookup_and_validate_server(server_id): # def db_lookup_server(server_id): # def config_lookup_server(server_id): # def lookup_all_servers(): # def db_lookup_all_servers(): # def lookup_and_validate_cluster(cluster_id): # def lookup_cluster(cluster_id): # def config_lookup_cluster(cluster_id): # def db_lookup_cluster(cluster_id): # def lookup_all_clusters(): # def db_lookup_all_clusters(): # def db_lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def db_lookup_cluster_by_shard(shard): # def db_lookup_sharded_cluster_by_config_replica(cluster): # def config_lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def config_lookup_cluster_by_shard(shard): # def config_lookup_sharded_cluster_by_config_replica(cluster): # def cluster_has_config_server(cluster, server): # def cluster_has_shard(cluster, shard): # def cluster_has_config_replica(cluster, conf_replica): # def get_configured_servers(): # def get_configured_clusters(): # def validate_cluster(cluster): # def validate_replicaset_cluster(cluster): # def validate_sharded_cluster(cluster): # def lookup_validate_cluster_by_server(server): # def lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def lookup_cluster_by_shard(shard): # def lookup_sharded_cluster_by_config_replica(cluster): # def validate_server(server): # def get_mongoctl_server_db_collection(): # def get_mongoctl_cluster_db_collection(): # def get_activity_collection(): # def new_server(server_doc): # def build_server_from_address(address): # def build_server_from_uri(uri): # def build_cluster_from_uri(uri): # def build_server_or_cluster_from_uri(uri): # def new_servers_dict(docs): # def new_cluster(cluster_doc): # def new_replicaset_clusters_dict(docs): # def new_replicaset_cluster_member(cluster_mem_doc): # def new_replicaset_cluster_member_list(docs_iteratable): # def replicaset_cluster_type(): # def sharded_cluster_type(): # # Path: mongoctl/utils.py # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] . Output only the next line.
server = repository.lookup_server(parsed_options.server)
Continue the code snippet: <|code_start|>__author__ = 'abdul' ############################################################################### # CONSTS ############################################################################### DEFAULT_TAIL_LINES = 15 ############################################################################### # tail log command ############################################################################### def tail_log_command(parsed_options): server = repository.lookup_server(parsed_options.server) server.validate_local_op("tail-log") log_path = server.get_log_file_path() # check if log file exists if os.path.exists(log_path): log_tailer = tail_server_log(server) log_tailer.communicate() else: log_info("Log file '%s' does not exist." % log_path) ############################################################################### def tail_server_log(server): try: logpath = server.get_log_file_path() # touch log file to make sure it exists log_verbose("Touching log file '%s'" % logpath) <|code_end|> . Use current file imports: import os from mongoctl.processes import create_subprocess from mongoctl.mongoctl_logging import * from mongoctl import repository from mongoctl.utils import execute_command and context (classes, functions, or code) from other files: # Path: mongoctl/repository.py # DEFAULT_SERVERS_FILE = "servers.config" # DEFAULT_CLUSTERS_FILE = "clusters.config" # DEFAULT_SERVERS_COLLECTION = "servers" # DEFAULT_CLUSTERS_COLLECTION = "clusters" # DEFAULT_ACTIVITY_COLLECTION = "logs.server-activity" # LOOKUP_TYPE_MEMBER = "members" # LOOKUP_TYPE_CONFIG_SVR = "configServers" # LOOKUP_TYPE_SHARDS = "shards" # LOOKUP_TYPE_ANY = [LOOKUP_TYPE_CONFIG_SVR, LOOKUP_TYPE_MEMBER, # LOOKUP_TYPE_SHARDS] # MONGOD_SERVER_CLASS_NAME = "mongoctl.objects.mongod.MongodServer" # MONGOS_ROUTER_CLASS_NAME = "mongoctl.objects.mongos.MongosServer" # SERVER_TYPE_MAP = { # "Mongod": MONGOD_SERVER_CLASS_NAME, # "ConfigMongod": MONGOD_SERVER_CLASS_NAME, # "Mongos": MONGOS_ROUTER_CLASS_NAME, # # === XXX deprecated XXX === # "mongod": MONGOD_SERVER_CLASS_NAME, # XXX deprecated # "mongos": MONGOS_ROUTER_CLASS_NAME, # XXX deprecated # } # def get_mongoctl_database(): # def has_db_repository(): # def has_file_repository(): # def has_commandline_servers_or_clusters(): # def consulting_db_repository(): # def is_db_repository_online(): # def _db_repo_connect(): # def validate_repositories(): # def set_commandline_servers_and_clusters(servers_json_str, clusters_json_str): # def clear_repository_cache(): # def lookup_server(server_id): # def lookup_and_validate_server(server_id): # def db_lookup_server(server_id): # def config_lookup_server(server_id): # def lookup_all_servers(): # def db_lookup_all_servers(): # def lookup_and_validate_cluster(cluster_id): # def lookup_cluster(cluster_id): # def config_lookup_cluster(cluster_id): # def db_lookup_cluster(cluster_id): # def lookup_all_clusters(): # def db_lookup_all_clusters(): # def db_lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def db_lookup_cluster_by_shard(shard): # def db_lookup_sharded_cluster_by_config_replica(cluster): # def config_lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def config_lookup_cluster_by_shard(shard): # def config_lookup_sharded_cluster_by_config_replica(cluster): # def cluster_has_config_server(cluster, server): # def cluster_has_shard(cluster, shard): # def cluster_has_config_replica(cluster, conf_replica): # def get_configured_servers(): # def get_configured_clusters(): # def validate_cluster(cluster): # def validate_replicaset_cluster(cluster): # def validate_sharded_cluster(cluster): # def lookup_validate_cluster_by_server(server): # def lookup_cluster_by_server(server, lookup_type=LOOKUP_TYPE_ANY): # def lookup_cluster_by_shard(shard): # def lookup_sharded_cluster_by_config_replica(cluster): # def validate_server(server): # def get_mongoctl_server_db_collection(): # def get_mongoctl_cluster_db_collection(): # def get_activity_collection(): # def new_server(server_doc): # def build_server_from_address(address): # def build_server_from_uri(uri): # def build_cluster_from_uri(uri): # def build_server_or_cluster_from_uri(uri): # def new_servers_dict(docs): # def new_cluster(cluster_doc): # def new_replicaset_clusters_dict(docs): # def new_replicaset_cluster_member(cluster_mem_doc): # def new_replicaset_cluster_member_list(docs_iteratable): # def replicaset_cluster_type(): # def sharded_cluster_type(): # # Path: mongoctl/utils.py # def execute_command(command, **kwargs): # # # Python 2.7+ : Use the new method because i think its better # if hasattr(subprocess, 'check_output'): # return subprocess.check_output(command,stderr=subprocess.STDOUT, **kwargs) # else: # Python 2.6 compatible, check_output is not available in 2.6 # return subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # **kwargs).communicate()[0] . Output only the next line.
execute_command(["touch", logpath])
Continue the code snippet: <|code_start|> if not self._group_message_proc: self._group_message_proc = Process(target=_write_message, args=( self._group_message_queue, self._terminator, self._encrypt_key, self._IV, get_group_msg_dir(), ) ) self._group_message_proc.start() return True else: return False def savePicture(self, content, format_): if content and format_: md5 = hashlib.md5() md5.update(content) pic_name = md5.hexdigest() path = os.path.join(get_picture_dir(),pic_name+"."+format_) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) with open(path,"wb") as output: output.write(content) return pic_name+"."+format_ else: return False def _write_message(queue, terminator, encrypt_key, IV, root_dir): <|code_end|> . Use current file imports: import os import time import hashlib from multiprocessing import Process, Queue from .encrypt import Encryptor from allchat.path import get_single_msg_dir, get_group_msg_dir, get_picture_dir, get_project_root and context (classes, functions, or code) from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_single_msg_dir(): # return os.path.join(get_project_root(),"Data","single_messages") # # def get_group_msg_dir(): # return os.path.join(get_project_root(),"Data","group_messages") # # def get_picture_dir(): # return os.path.join(get_project_root(),"Data","picture") # # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
encryptor = Encryptor(encrypt_key, IV)
Using the snippet: <|code_start|> root = get_project_root() conf_path = os.path.join(root, "conf", "blizzard.conf") if not os.path.exists(conf_path): self._init_config(conf_path) with open(conf_path,"rb") as conf: configs = conf.read() config_dict = dict(tuple(line.split(b"=")) for line in configs.split(b"\n")) self._encrypt_key = config_dict.get(b"encrypt_key") self._IV = config_dict.get(b"IV") def __stop_writing(self): if self._single_message_proc: self._single_message_queue.put(self._terminator) self._single_message_proc.join() if self._group_message_proc: self._group_message_queue.put(self._terminator) self._group_message_proc.join() def saveSingleMsg(self, sender, receiver, msg): if sender and receiver and isinstance(msg, list) and msg[0] and msg[1]: users = "&&".join(sorted([sender,receiver])) self._single_message_queue.put((sender,users,msg)) if not self._single_message_proc: self._single_message_proc = Process(target=_write_message, args=( self._single_message_queue, self._terminator, self._encrypt_key, self._IV, <|code_end|> , determine the next line of code. You have imports: import os import time import hashlib from multiprocessing import Process, Queue from .encrypt import Encryptor from allchat.path import get_single_msg_dir, get_group_msg_dir, get_picture_dir, get_project_root and context (class names, function names, or code) available: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_single_msg_dir(): # return os.path.join(get_project_root(),"Data","single_messages") # # def get_group_msg_dir(): # return os.path.join(get_project_root(),"Data","group_messages") # # def get_picture_dir(): # return os.path.join(get_project_root(),"Data","picture") # # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
get_single_msg_dir(),
Predict the next line after this snippet: <|code_start|> def saveSingleMsg(self, sender, receiver, msg): if sender and receiver and isinstance(msg, list) and msg[0] and msg[1]: users = "&&".join(sorted([sender,receiver])) self._single_message_queue.put((sender,users,msg)) if not self._single_message_proc: self._single_message_proc = Process(target=_write_message, args=( self._single_message_queue, self._terminator, self._encrypt_key, self._IV, get_single_msg_dir(), ) ) self._single_message_proc.start() return True else: return False def saveGroupMsg(self, sender, group_id, msg): if sender and group_id and isinstance(msg, list) and msg[0] and msg[1]: self._group_message_queue.put((sender,str(group_id),msg)) if not self._group_message_proc: self._group_message_proc = Process(target=_write_message, args=( self._group_message_queue, self._terminator, self._encrypt_key, self._IV, <|code_end|> using the current file's imports: import os import time import hashlib from multiprocessing import Process, Queue from .encrypt import Encryptor from allchat.path import get_single_msg_dir, get_group_msg_dir, get_picture_dir, get_project_root and any relevant context from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_single_msg_dir(): # return os.path.join(get_project_root(),"Data","single_messages") # # def get_group_msg_dir(): # return os.path.join(get_project_root(),"Data","group_messages") # # def get_picture_dir(): # return os.path.join(get_project_root(),"Data","picture") # # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
get_group_msg_dir(),
Given the following code snippet before the placeholder: <|code_start|> ) ) self._single_message_proc.start() return True else: return False def saveGroupMsg(self, sender, group_id, msg): if sender and group_id and isinstance(msg, list) and msg[0] and msg[1]: self._group_message_queue.put((sender,str(group_id),msg)) if not self._group_message_proc: self._group_message_proc = Process(target=_write_message, args=( self._group_message_queue, self._terminator, self._encrypt_key, self._IV, get_group_msg_dir(), ) ) self._group_message_proc.start() return True else: return False def savePicture(self, content, format_): if content and format_: md5 = hashlib.md5() md5.update(content) pic_name = md5.hexdigest() <|code_end|> , predict the next line using imports from the current file: import os import time import hashlib from multiprocessing import Process, Queue from .encrypt import Encryptor from allchat.path import get_single_msg_dir, get_group_msg_dir, get_picture_dir, get_project_root and context including class names, function names, and sometimes code from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_single_msg_dir(): # return os.path.join(get_project_root(),"Data","single_messages") # # def get_group_msg_dir(): # return os.path.join(get_project_root(),"Data","group_messages") # # def get_picture_dir(): # return os.path.join(get_project_root(),"Data","picture") # # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
path = os.path.join(get_picture_dir(),pic_name+"."+format_)
Given the following code snippet before the placeholder: <|code_start|># -*- coding:utf-8 -*- class MessageSaver(object): def __init__(self): self._single_message_queue = Queue() self._group_message_queue = Queue() self._get_config() self._terminator = "\nquit\n" self._single_message_proc = None self._group_message_proc = None def _init_config(self, conf_path): if not os.path.exists(os.path.dirname(conf_path)): os.makedirs(os.path.dirname(conf_path)) with open(conf_path,"wb") as conf: encrypt_key = b"=".join((b"encrypt_key",os.urandom(16))) IV = b"=".join((b"IV",os.urandom(16))) conf.write(b"\n".join((encrypt_key,IV))) def _get_config(self): <|code_end|> , predict the next line using imports from the current file: import os import time import hashlib from multiprocessing import Process, Queue from .encrypt import Encryptor from allchat.path import get_single_msg_dir, get_group_msg_dir, get_picture_dir, get_project_root and context including class names, function names, and sometimes code from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_single_msg_dir(): # return os.path.join(get_project_root(),"Data","single_messages") # # def get_group_msg_dir(): # return os.path.join(get_project_root(),"Data","group_messages") # # def get_picture_dir(): # return os.path.join(get_project_root(),"Data","picture") # # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
root = get_project_root()
Continue the code snippet: <|code_start|>#!/usr/bin/env python #coding:utf-8 """ Author: --<alen-alex> Purpose: provide a message content retrieval interface to web server, retrieve from /data directory Created: 2014/11/4 """ #---------------------------------------------------------------------- def getMessages(directory, date): """retrieve the messages stored in files param: directory: the place where files should be searched from; param: date: the date of files to retrieve, format by "yyyy-mm-dd"; """ try: query_year, query_month, query_day = date.split("-") except ValueError: return ("Wrong date format", 404) file_ = os.path.join(directory,query_year,query_month,query_day+".bin") if not os.path.exists(file_): return ("File does not exist", 404) messages = _read_file(file_) return json.JSONEncoder().encode(messages) #---------------------------------------------------------------------- def _read_file(file_path): """""" key,IV = _get_encrypt_key() <|code_end|> . Use current file imports: import os import json from .encrypt import Encryptor from allchat.path import get_project_root and context (classes, functions, or code) from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) . Output only the next line.
encryptor = Encryptor(key,IV)
Here is a snippet: <|code_start|> try: query_year, query_month, query_day = date.split("-") except ValueError: return ("Wrong date format", 404) file_ = os.path.join(directory,query_year,query_month,query_day+".bin") if not os.path.exists(file_): return ("File does not exist", 404) messages = _read_file(file_) return json.JSONEncoder().encode(messages) #---------------------------------------------------------------------- def _read_file(file_path): """""" key,IV = _get_encrypt_key() encryptor = Encryptor(key,IV) messages = list() with open(file_path,"rb") as output: sep = b"\0\1\2\3\4"*2 lines = output.read().rstrip(sep) for line in lines.split(sep): try: line = encryptor.DecryptStr(line) messages.append(line.split("\t\t")) except Exception as e: print(e) return messages #---------------------------------------------------------------------- def _get_encrypt_key(): """""" <|code_end|> . Write the next line using the current file imports: import os import json from .encrypt import Encryptor from allchat.path import get_project_root and context from other files: # Path: allchat/filestore/encrypt.py # class Encryptor(object): # def __init__(self, key, IV): # self.key = key # self.IV = IV # self.blocksize = 16 # # def EncryptStr(self,content): # if sys.version_info.major == 2: # content = content.encode("utf-8") # elif sys.version_info.major == 3: # content = bytes(content,"utf-8") # while len(content)%self.blocksize != 0: # content += b"\0" # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # return obj.encrypt(content) # # def DecryptStr(self,content): # obj = AES.new(self.key,AES.MODE_CBC,self.IV) # content = obj.decrypt(content).strip(b"\0") # return content.decode("utf-8") # # Path: allchat/path.py # def get_project_root(): # return os.path.dirname(os.path.dirname(__file__)) , which may include functions, classes, or code. Output only the next line.
root = get_project_root()
Using the snippet: <|code_start|># -*- coding: utf-8 -*- def authorized(func): @wraps(func) def action(*args, **kwargs): token = request.headers.get('token', None) account = session.get('account', None) if token and account: <|code_end|> , determine the next line of code. You have imports: from flask import request, make_response, session from allchat.database.sql import get_session from allchat.database.models import UserAuth from functools import wraps and context (class names, function names, or code) available: # Path: allchat/database/sql.py # def get_session(): # return db.session # # Path: allchat/database/models.py # class UserAuth(db.Model): # __tablename__ = "userauth" # __table_args__ = { # 'mysql_engine': 'InnoDB', # 'mysql_charset': 'utf8', # 'mysql_collate': 'utf8_bin' # } # # id = db.Column(db.Integer, primary_key = True) # account = db.Column(db.String(50), index = True, unique = True, nullable = False) # password = db.Column(db.String(64), nullable = False) # salt = db.Column(db.String(16), nullable = False) # prev_token = db.Column(db.String(32)) # token = db.Column(db.String(32)) # created = db.Column(db.DateTime(timezone = True), nullable = False) # updated = db.Column(db.DateTime(timezone = True), nullable = False) # deleted = db.Column(db.Boolean, nullable = False, default = False) # # # def __init__(self, account, password): # self.account = account # self.salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) # self.password = hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest() # self.token = None # self.prev_token = None # self.created = datetime.datetime.utcnow() # self.updated = self.created # self.deleted = False # # def is_authenticated(self, password): # if self.deleted: # return False # if self.password == hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest(): # # db.session.begin(subtransactions=True) # # try: # # self.prev_token = self.token # # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # # self.updated = datetime.datetime.utcnow() # # db.session.add(self) # # db.session.commit() # # except: # # db.session.rollback() # # return False # return True # else: # return False # def is_token(self, token): # if self.deleted or (token is None): # return False # if token == self.token: # return True # else: # return False # def is_prev_token(self, token): # if self.deleted or (token is None): # return False # if token == self.prev_token: # return True # else: # return False # def is_token_timeout(self): # now = datetime.datetime.utcnow() # return (now - self.updated).seconds >= 86400 # def fresh(self, token = None): # if (self.deleted == False) and (self.is_token(token) or token is None): # db.session.begin(subtransactions=True) # try: # self.prev_token = self.token # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # return True # # def clear(self): # db.session.begin(subtransactions=True) # try: # self.prev_token = self.token # self.token = None # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # def modify(self, password, new): # if self.is_authenticated(password): # db.session.begin(subtransactions=True) # try: # self.password = hashlib.sha256((self.salt+new).encode("utf-8")).hexdigest() # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # return True # else: # return False # def delete(self): # if self.deleted: # return True # db.session.begin(subtransactions=True) # try: # self.deleted = True # self.prev_token = None # self.token = None # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # return True # # # def activate(self, password = None): # if not self.deleted: # return True # if password is None: # db.session.begin(subtransactions=True) # try: # self.deleted = False # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # return True # if password == hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest(): # db.session.begin(subtransactions=True) # try: # self.deleted = False # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # else: # return False # return True . Output only the next line.
db_session = get_session()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- def authorized(func): @wraps(func) def action(*args, **kwargs): token = request.headers.get('token', None) account = session.get('account', None) if token and account: db_session = get_session() try: <|code_end|> , predict the next line using imports from the current file: from flask import request, make_response, session from allchat.database.sql import get_session from allchat.database.models import UserAuth from functools import wraps and context including class names, function names, and sometimes code from other files: # Path: allchat/database/sql.py # def get_session(): # return db.session # # Path: allchat/database/models.py # class UserAuth(db.Model): # __tablename__ = "userauth" # __table_args__ = { # 'mysql_engine': 'InnoDB', # 'mysql_charset': 'utf8', # 'mysql_collate': 'utf8_bin' # } # # id = db.Column(db.Integer, primary_key = True) # account = db.Column(db.String(50), index = True, unique = True, nullable = False) # password = db.Column(db.String(64), nullable = False) # salt = db.Column(db.String(16), nullable = False) # prev_token = db.Column(db.String(32)) # token = db.Column(db.String(32)) # created = db.Column(db.DateTime(timezone = True), nullable = False) # updated = db.Column(db.DateTime(timezone = True), nullable = False) # deleted = db.Column(db.Boolean, nullable = False, default = False) # # # def __init__(self, account, password): # self.account = account # self.salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) # self.password = hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest() # self.token = None # self.prev_token = None # self.created = datetime.datetime.utcnow() # self.updated = self.created # self.deleted = False # # def is_authenticated(self, password): # if self.deleted: # return False # if self.password == hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest(): # # db.session.begin(subtransactions=True) # # try: # # self.prev_token = self.token # # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # # self.updated = datetime.datetime.utcnow() # # db.session.add(self) # # db.session.commit() # # except: # # db.session.rollback() # # return False # return True # else: # return False # def is_token(self, token): # if self.deleted or (token is None): # return False # if token == self.token: # return True # else: # return False # def is_prev_token(self, token): # if self.deleted or (token is None): # return False # if token == self.prev_token: # return True # else: # return False # def is_token_timeout(self): # now = datetime.datetime.utcnow() # return (now - self.updated).seconds >= 86400 # def fresh(self, token = None): # if (self.deleted == False) and (self.is_token(token) or token is None): # db.session.begin(subtransactions=True) # try: # self.prev_token = self.token # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # return True # # def clear(self): # db.session.begin(subtransactions=True) # try: # self.prev_token = self.token # self.token = None # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # def modify(self, password, new): # if self.is_authenticated(password): # db.session.begin(subtransactions=True) # try: # self.password = hashlib.sha256((self.salt+new).encode("utf-8")).hexdigest() # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # return True # else: # return False # def delete(self): # if self.deleted: # return True # db.session.begin(subtransactions=True) # try: # self.deleted = True # self.prev_token = None # self.token = None # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except Exception: # db.session.rollback() # return False # return True # # # def activate(self, password = None): # if not self.deleted: # return True # if password is None: # db.session.begin(subtransactions=True) # try: # self.deleted = False # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # return True # if password == hashlib.sha256((self.salt+password).encode("utf-8")).hexdigest(): # db.session.begin(subtransactions=True) # try: # self.deleted = False # self.prev_token = None # self.token = ''.join(random.sample(string.ascii_letters + string.digits, 32)) # self.updated = datetime.datetime.utcnow() # db.session.add(self) # db.session.commit() # except: # db.session.rollback() # return False # else: # return False # return True . Output only the next line.
auth = db_session.query(UserAuth).filter(UserAuth.account == account).one()
Predict the next line for this snippet: <|code_start|> class SignerTest(TestCase): fixtures = ["cybersource-test.yaml"] def test_sign(self): profile = get_sa_profile() <|code_end|> with the help of current file imports: from django.test import TestCase from django.test.client import RequestFactory from ..signature import SecureAcceptanceSigner from .factories import get_sa_profile and context from other files: # Path: src/cybersource/signature.py # class SecureAcceptanceSigner(object): # def __init__(self, secret_key): # self.secret_key = secret_key # # def sign(self, data, signed_fields): # key = self.secret_key.encode("utf-8") # msg_raw = self._build_message(data, signed_fields).encode("utf-8") # msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) # return base64.b64encode(msg_hmac.digest()) # # def verify_request(self, request): # # Ensure the signature is valid and that this request can be trusted # signed_field_names = request.POST.get("signed_field_names") # if not signed_field_names: # raise SuspiciousOperation("Request has no fields to verify") # signed_field_names = signed_field_names.split(",") # signature_given = request.POST["signature"].encode("utf-8") # signature_calc = self.sign(request.POST, signed_field_names) # return signature_given == signature_calc # # def _build_message(self, data, signed_fields): # parts = [] # for field in signed_fields: # parts.append("%s=%s" % (field, data.get(field, ""))) # return ",".join(parts) # # Path: src/cybersource/tests/factories.py # def get_sa_profile(): # return SecureAcceptanceProfile.get_profile("testserver") , which may contain function names, class names, or code. Output only the next line.
signer = SecureAcceptanceSigner(profile.secret_key)
Given the following code snippet before the placeholder: <|code_start|> class SignerTest(TestCase): fixtures = ["cybersource-test.yaml"] def test_sign(self): <|code_end|> , predict the next line using imports from the current file: from django.test import TestCase from django.test.client import RequestFactory from ..signature import SecureAcceptanceSigner from .factories import get_sa_profile and context including class names, function names, and sometimes code from other files: # Path: src/cybersource/signature.py # class SecureAcceptanceSigner(object): # def __init__(self, secret_key): # self.secret_key = secret_key # # def sign(self, data, signed_fields): # key = self.secret_key.encode("utf-8") # msg_raw = self._build_message(data, signed_fields).encode("utf-8") # msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) # return base64.b64encode(msg_hmac.digest()) # # def verify_request(self, request): # # Ensure the signature is valid and that this request can be trusted # signed_field_names = request.POST.get("signed_field_names") # if not signed_field_names: # raise SuspiciousOperation("Request has no fields to verify") # signed_field_names = signed_field_names.split(",") # signature_given = request.POST["signature"].encode("utf-8") # signature_calc = self.sign(request.POST, signed_field_names) # return signature_given == signature_calc # # def _build_message(self, data, signed_fields): # parts = [] # for field in signed_fields: # parts.append("%s=%s" % (field, data.get(field, ""))) # return ",".join(parts) # # Path: src/cybersource/tests/factories.py # def get_sa_profile(): # return SecureAcceptanceProfile.get_profile("testserver") . Output only the next line.
profile = get_sa_profile()
Given snippet: <|code_start|> "req_transaction_uuid": str(randrange(100000000000, 999999999999)), "request_token": "Ahj/7wSR8sYxolZgxwyeIkG7lw3ZNnDmLNjMqcSPOS4lfDoTAFLiV8OhM0glqN4vpQyaSZbpAd0+3AnI+WMY0SswY4ZPAAAALRaM", "req_merchant_secure_data4": encrypt_session_id(session_id), "score_bin_country": "US", "score_card_issuer": "JPMORGAN CHASE BANK, N.A.", "score_card_scheme": "VISA CREDIT", "score_host_severity": "1", "score_internet_info": "FREE-EM^MM-IPBC", "score_ip_city": "new york", "score_ip_country": "us", "score_ip_routing_method": "fixed", "score_ip_state": "ny", "score_model_used": "default", "score_rcode": "1", "score_reason_code": "480", "score_return_code": "1070000", "score_rflag": "SOK", "score_rmsg": "score service was successful", "score_score_result": "0", "score_time_local": "10:06:36", "transaction_id": str(randrange(0, 99999999999999999999)), "utf8": "✓", } return data def sign_reply_data(data): profile = get_sa_profile() fields = list(data.keys()) data["signature"] = ( <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import datetime from random import randrange from ..signature import SecureAcceptanceSigner from ..models import SecureAcceptanceProfile from ..actions import encrypt_session_id import uuid and context: # Path: src/cybersource/signature.py # class SecureAcceptanceSigner(object): # def __init__(self, secret_key): # self.secret_key = secret_key # # def sign(self, data, signed_fields): # key = self.secret_key.encode("utf-8") # msg_raw = self._build_message(data, signed_fields).encode("utf-8") # msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) # return base64.b64encode(msg_hmac.digest()) # # def verify_request(self, request): # # Ensure the signature is valid and that this request can be trusted # signed_field_names = request.POST.get("signed_field_names") # if not signed_field_names: # raise SuspiciousOperation("Request has no fields to verify") # signed_field_names = signed_field_names.split(",") # signature_given = request.POST["signature"].encode("utf-8") # signature_calc = self.sign(request.POST, signed_field_names) # return signature_given == signature_calc # # def _build_message(self, data, signed_fields): # parts = [] # for field in signed_fields: # parts.append("%s=%s" % (field, data.get(field, ""))) # return ",".join(parts) # # Path: src/cybersource/models.py # class SecureAcceptanceProfile(models.Model): # hostname = models.CharField( # _("Hostname"), # max_length=100, # blank=True, # unique=True, # help_text=_( # "When the request matches this hostname, this profile will be used." # ), # ) # profile_id = models.CharField(_("Profile ID"), max_length=50, unique=True) # access_key = models.CharField(_("Access Key"), max_length=50) # secret_key = EncryptedTextField(_("Secret Key")) # is_default = models.BooleanField( # _("Is Default Profile?"), # default=False, # help_text=_( # "If no profile can be found for a request's hostname, the default profile will be used." # ), # ) # # class Meta: # verbose_name = _("Secure Acceptance Profile") # verbose_name_plural = _("Secure Acceptance Profiles") # # @classmethod # def get_profile(cls, hostname): # # Lambda function to get profiles whilst catching cryptography exceptions (in-case the Fernet key # # unexpectedly changed, the data somehow got corrupted, etc). # def _get_safe(**filters): # try: # return cls.objects.filter(**filters).first() # except InvalidToken: # logger.exception( # "Caught InvalidToken exception while retrieving profile" # ) # return None # # # Try to get the profile for the given hostname # profile = _get_safe(hostname__iexact=hostname) # if profile: # return profile # # # Fall back to the default profile # profile = _get_safe(is_default=True) # if profile: # return profile # # # No default profile exists, so try and get something out of settings. # if ( # hasattr(settings, "CYBERSOURCE_PROFILE") # and hasattr(settings, "CYBERSOURCE_ACCESS") # and hasattr(settings, "CYBERSOURCE_SECRET") # ): # profile = SecureAcceptanceProfile() # profile.hostname = "" # profile.profile_id = settings.CYBERSOURCE_PROFILE # profile.access_key = settings.CYBERSOURCE_ACCESS # profile.secret_key = settings.CYBERSOURCE_SECRET # profile.is_default = True # profile.save() # logger.info( # "Created SecureAcceptanceProfile from Django settings: {}".format( # profile # ) # ) # return profile # # # Out of options—raise an exception. # raise cls.DoesNotExist() # # def save(self, *args, **kwargs): # if self.is_default: # self.__class__._default_manager.filter(is_default=True).update( # is_default=False # ) # return super().save(*args, **kwargs) # # def __str__(self): # return _( # "Secure Acceptance Profile hostname=%(hostname)s, profile_id=%(profile_id)s" # ) % dict(hostname=self.hostname, profile_id=self.profile_id) # # Path: src/cybersource/actions.py # def encrypt_session_id(session_id): # fernet = EncryptedTextField().fernet # session_id_bytes = force_bytes(session_id) # encrypted_bytes = fernet.encrypt(session_id_bytes) # encrypted_str = force_str(encrypted_bytes) # return encrypted_str which might include code, classes, or functions. Output only the next line.
SecureAcceptanceSigner(profile.secret_key).sign(data, fields).decode("utf8")
Continue the code snippet: <|code_start|> self.assertEqual(lines.count(), 1) line = lines[0] self.assertEqual(line.quantity, quantity) self.assertEqual(line.product_id, product_id) payment_events = order.payment_events.filter(event_type__name="Authorise") self.assertEqual(payment_events.count(), 1) self.assertEqual(payment_events[0].amount, order.total_incl_tax) payment_sources = order.sources.all() self.assertEqual(payment_sources.count(), 1) self.assertEqual(payment_sources[0].currency, order.currency) self.assertEqual(payment_sources[0].amount_allocated, order.total_incl_tax) self.assertEqual(payment_sources[0].amount_debited, D("0.00")) self.assertEqual(payment_sources[0].amount_refunded, D("0.00")) transactions = payment_sources[0].transactions.all() self.assertEqual(transactions.count(), 1) self.assertEqual(transactions[0].txn_type, "Authorise") self.assertEqual(transactions[0].amount, order.total_incl_tax) self.assertEqual(transactions[0].status, status) self.assertEqual(transactions[0].log.order, order) self.assertEqual(transactions[0].log.req_reference_number, order.number) self.assertEqual(transactions[0].token.card_last4, card_last4) self.assertEqual(transactions[0].token.log.order, order) self.assertEqual(transactions[0].token.log.req_reference_number, order.number) self.assertEqual(len(mail.outbox), 1) <|code_end|> . Use current file imports: from unittest import skipUnless, mock from decimal import Decimal as D from django.conf import settings from django.core import mail from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from oscar.core.loading import get_model from oscar.test import factories from rest_framework import status from rest_framework.test import APITestCase from cybersource.models import CyberSourceReply from ..constants import DECISION_REVIEW, DECISION_ACCEPT from . import factories as cs_factories import datetime import uuid and context (classes, functions, or code) from other files: # Path: src/cybersource/constants.py # DECISION_REVIEW = "REVIEW" # # DECISION_ACCEPT = "ACCEPT" . Output only the next line.
if status == DECISION_REVIEW:
Continue the code snippet: <|code_start|> # Mask Card data token_resp_data["req_card_number"] = ( "xxxxxxxxxxxx" + token_resp_data["req_card_number"][-4:] ) token_resp_data.pop("req_card_cvn", None) # Add auth fields token_resp_data["auth_amount"] = token_request_data.get("amount", "0.00") token_resp_data["auth_avs_code"] = "Y" token_resp_data["auth_avs_code_raw"] = "Y" token_resp_data["auth_code"] = "00000D" token_resp_data["auth_cv_result"] = "M" token_resp_data["auth_cv_result_raw"] = "M" token_resp_data["auth_response"] = "85" token_resp_data["auth_time"] = datetime.datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%SZ" ) token_resp_data["decision"] = "ACCEPT" token_resp_data["message"] = "Request was processed successfully." token_resp_data["payment_token"] = get_random_string(16) token_resp_data["reason_code"] = "100" token_resp_data["request_token"] = get_random_string(80) token_resp_data["transaction_id"] = get_random_string( 22, allowed_chars="0123456789" ) # Sign and return data cs_factories.sign_reply_data(token_resp_data) token_resp_data["utf8"] = "✓" return token_resp_data def check_finished_order( <|code_end|> . Use current file imports: from unittest import skipUnless, mock from decimal import Decimal as D from django.conf import settings from django.core import mail from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from oscar.core.loading import get_model from oscar.test import factories from rest_framework import status from rest_framework.test import APITestCase from cybersource.models import CyberSourceReply from ..constants import DECISION_REVIEW, DECISION_ACCEPT from . import factories as cs_factories import datetime import uuid and context (classes, functions, or code) from other files: # Path: src/cybersource/constants.py # DECISION_REVIEW = "REVIEW" # # DECISION_ACCEPT = "ACCEPT" . Output only the next line.
self, number, product_id, quantity=1, status=DECISION_ACCEPT, card_last4="1111"
Given the following code snippet before the placeholder: <|code_start|> req_bill_to_surname = NullCharField(max_length=255) req_card_expiry_date = NullCharField(max_length=10) req_reference_number = NullCharField(max_length=128) req_transaction_type = NullCharField(max_length=20) req_transaction_uuid = NullCharField(max_length=40) request_token = NullCharField(max_length=200) transaction_id = NullCharField(max_length=64) # Timestamps date_modified = models.DateTimeField(_("Date Modified"), auto_now=True) date_created = models.DateTimeField(_("Date Received"), auto_now_add=True) class Meta: verbose_name = _("CyberSource Reply") verbose_name_plural = _("CyberSource Replies") ordering = ("date_created",) def __str__(self): return _("CyberSource Reply %(created)s") % dict(created=self.date_created) @property def signed_date_time(self): try: return dateutil.parser.parse(self.data["signed_date_time"]) except (AttributeError, ValueError, KeyError): return self.date_created def get_decision(self): # Accept if self.reason_code in (100,): <|code_end|> , predict the next line using imports from the current file: from cryptography.fernet import InvalidToken from django.conf import settings from django.db import models from django.contrib.postgres.fields import HStoreField from django.utils.translation import gettext_lazy as _ from django.utils import timezone from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import NullCharField from fernet_fields import EncryptedTextField from .constants import ( DECISION_ACCEPT, DECISION_REVIEW, DECISION_DECLINE, DECISION_ERROR, ) import dateutil.parser import logging and context including class names, function names, and sometimes code from other files: # Path: src/cybersource/constants.py # DECISION_ACCEPT = "ACCEPT" # # DECISION_REVIEW = "REVIEW" # # DECISION_DECLINE = "DECLINE" # # DECISION_ERROR = "ERROR" . Output only the next line.
return DECISION_ACCEPT