text
stringlengths
4
1.02M
meta
dict
from unittest import skipUnless from django.forms import ValidationError from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.tests.utils import HAS_SPATIALREFSYS from django.test import SimpleTestCase from django.utils import six from django.utils.html import escape if HAS_SPATIALREFSYS: from django.contrib.gis import forms from django.contrib.gis.geos import GEOSGeometry @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "GeometryFieldTest needs gdal support and a spatial database") class GeometryFieldTest(SimpleTestCase): def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): self.assertRaises(ValidationError, fld.clean, bad_default) def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0000001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry should be transformed to 32140. cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)') self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol)) def test_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() with six.assertRaisesRegex(self, forms.ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertIsNone(fld.clean(None)) def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) # but rejected by `clean` self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)') def test_to_python(self): """ Testing to_python returns a correct GEOSGeometry object or a ValidationError """ fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) # but raises a ValidationError for any other string for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): self.assertRaises(forms.ValidationError, fld.to_python, wkt) @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "SpecializedFieldTest needs gdal support and a spatial database") class SpecializedFieldTest(SimpleTestCase): def setUp(self): self.geometries = { 'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), 'multipoint': GEOSGeometry("SRID=4326;MULTIPOINT(" "(13.18634033203125 14.504356384277344)," "(13.207969665527 14.490966796875)," "(13.177070617675 14.454917907714))"), 'linestring': GEOSGeometry("SRID=4326;LINESTRING(" "-8.26171875 -0.52734375," "-7.734375 4.21875," "6.85546875 3.779296875," "5.44921875 -3.515625)"), 'multilinestring': GEOSGeometry("SRID=4326;MULTILINESTRING(" "(-16.435546875 -2.98828125," "-17.2265625 2.98828125," "-0.703125 3.515625," "-1.494140625 -3.33984375)," "(-8.0859375 -5.9765625," "8.525390625 -8.7890625," "12.392578125 -0.87890625," "10.01953125 7.646484375))"), 'polygon': GEOSGeometry("SRID=4326;POLYGON(" "(-1.669921875 6.240234375," "-3.8671875 -0.615234375," "5.9765625 -3.955078125," "18.193359375 3.955078125," "9.84375 9.4921875," "-1.669921875 6.240234375))"), 'multipolygon': GEOSGeometry("SRID=4326;MULTIPOLYGON(" "((-17.578125 13.095703125," "-17.2265625 10.8984375," "-13.974609375 10.1953125," "-13.359375 12.744140625," "-15.732421875 13.7109375," "-17.578125 13.095703125))," "((-8.525390625 5.537109375," "-8.876953125 2.548828125," "-5.888671875 1.93359375," "-5.09765625 4.21875," "-6.064453125 6.240234375," "-8.525390625 5.537109375)))"), 'geometrycollection': GEOSGeometry("SRID=4326;GEOMETRYCOLLECTION(" "POINT(5.625 -0.263671875)," "POINT(6.767578125 -3.603515625)," "POINT(8.525390625 0.087890625)," "POINT(8.0859375 -2.13134765625)," "LINESTRING(" "6.273193359375 -1.175537109375," "5.77880859375 -1.812744140625," "7.27294921875 -2.230224609375," "7.657470703125 -1.25244140625))"), } def assertMapWidget(self, form_instance): """ Make sure the MapWidget js is passed in the form media and a MapWidget is actually created """ self.assertTrue(form_instance.is_valid()) rendered = form_instance.as_p() self.assertIn('new MapWidget(options);', rendered) self.assertIn('gis/js/OLMapWidget.js', str(form_instance.media)) def assertTextarea(self, geom, rendered): """Makes sure the wkt and a textarea are in the content""" self.assertIn('<textarea ', rendered) self.assertIn('required', rendered) self.assertIn(geom.wkt, rendered) def test_pointfield(self): class PointForm(forms.Form): p = forms.PointField() geom = self.geometries['point'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) invalid = PointForm(data={'p': 'some invalid geom'}) self.assertFalse(invalid.is_valid()) self.assertTrue('Invalid geometry value' in str(invalid.errors)) for invalid in [geo for key, geo in self.geometries.items() if key != 'point']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_multipointfield(self): class PointForm(forms.Form): p = forms.MultiPointField() geom = self.geometries['multipoint'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multipoint']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_linestringfield(self): class LineStringForm(forms.Form): l = forms.LineStringField() geom = self.geometries['linestring'] form = LineStringForm(data={'l': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'linestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_multilinestringfield(self): class LineStringForm(forms.Form): l = forms.MultiLineStringField() geom = self.geometries['multilinestring'] form = LineStringForm(data={'l': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multilinestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_polygonfield(self): class PolygonForm(forms.Form): p = forms.PolygonField() geom = self.geometries['polygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'polygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_multipolygonfield(self): class PolygonForm(forms.Form): p = forms.MultiPolygonField() geom = self.geometries['multipolygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'multipolygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_geometrycollectionfield(self): class GeometryForm(forms.Form): g = forms.GeometryCollectionField() geom = self.geometries['geometrycollection'] form = GeometryForm(data={'g': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(GeometryForm().is_valid()) for invalid in [geo for key, geo in self.geometries.items() if key != 'geometrycollection']: self.assertFalse(GeometryForm(data={'g': invalid.wkt}).is_valid()) def test_osm_widget(self): class PointForm(forms.Form): p = forms.PointField(widget=forms.OSMWidget) geom = self.geometries['point'] form = PointForm(data={'p': geom}) rendered = form.as_p() self.assertIn("OpenStreetMap (Mapnik)", rendered) self.assertIn("id: 'id_p',", rendered) @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "CustomGeometryWidgetTest needs gdal support and a spatial database") class CustomGeometryWidgetTest(SimpleTestCase): def test_custom_serialization_widget(self): class CustomGeometryWidget(forms.BaseGeometryWidget): template_name = 'gis/openlayers.html' deserialize_called = 0 def serialize(self, value): return value.json if value else '' def deserialize(self, value): self.deserialize_called += 1 return GEOSGeometry(value) class PointForm(forms.Form): p = forms.PointField(widget=CustomGeometryWidget) point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)") form = PointForm(data={'p': point}) self.assertIn(escape(point.json), form.as_p()) CustomGeometryWidget.called = 0 widget = form.fields['p'].widget # Force deserialize use due to a string value self.assertIn(escape(point.json), widget.render('p', point.json)) self.assertEqual(widget.deserialize_called, 1) form = PointForm(data={'p': point.json}) self.assertTrue(form.is_valid()) # Ensure that resulting geometry has srid set self.assertEqual(form.cleaned_data['p'].srid, 4326)
{ "content_hash": "93f49fb9d9b9c7307e6514749bb1d55d", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 106, "avg_line_length": 46.01724137931034, "alnum_prop": 0.5617085050580742, "repo_name": "ericholscher/django", "id": "ca28fb503c04382fe82db5b9b1da4694759ba127", "size": "13345", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "django/contrib/gis/tests/test_geoforms.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "51177" }, { "name": "JavaScript", "bytes": "102377" }, { "name": "Python", "bytes": "9011891" }, { "name": "Shell", "bytes": "12137" } ], "symlink_target": "" }
import os import logging from .scm import git from . import exceptions from .python3_compat import basestring from pkg_resources import parse_version _all_exposed_sources = {} _logger = logging.getLogger("pydeploy.sources") def _exposed(thing): _all_exposed_sources[thing.__name__] = thing return thing class Source(object): def checkout(self, env, path=None): raise NotImplementedError() # pragma: no cover def install(self, env, reinstall): raise NotImplementedError() # pragma: no cover def get_signature(self): raise NotImplementedError() # pragma: no cover def get_name(self): raise NotImplementedError() # pragma: no cover def resolve_constraints(self, constraints): raise NotImplementedError() # pragma: no cover @classmethod def from_anything(cls, source): if not isinstance(source, Source): if not isinstance(source, basestring): raise ValueError(source) return cls.from_string(source) return source @classmethod def from_string(cls, source): if os.path.exists(os.path.expanduser(source)): return Path(source) try: return SCM(source) except InvalidSCMURL: pass return EasyInstall(source) class SignedSingleParam(Source): def __init__(self, param): super(SignedSingleParam, self).__init__() self._param = param def get_signature(self): return repr(self) def get_name(self): return self._param def __repr__(self): return "{0}({1})".format(type(self).__name__, self._param) class SCMSource(Source): _DEFAULT_BRANCH = None def __init__(self, url, branch=None): super(SCMSource, self).__init__() if branch is None: branch = self._DEFAULT_BRANCH self._url = url self._branch = branch def __repr__(self): return "{0}({1})".format(type(self).__name__, self.get_name()) def get_name(self): return '{0}@{1}'.format(self._url, self._branch) def get_signature(self): return repr(self) @classmethod def from_string(cls, s): if '@' in s: repo_url, branch_name = s.split("@", 1) else: repo_url = s branch_name = None return cls(repo_url, branch_name) @classmethod def get_prefix(cls): raise NotImplementedError() # pragma: no cover @_exposed class Git(SCMSource): _DEFAULT_BRANCH = 'master' def install(self, env, reinstall): checkout_path = self.checkout(env) Path(checkout_path, name=self._url).install(env, reinstall) def checkout(self, env, path=None): if path is None: path = env.get_checkout_cache().get_checkout_path(self._url) git.clone_to_or_update(self._url, branch=self._branch, path=path) git.reset_submodules(path=path) return path @classmethod def get_prefix(cls): return 'git://' def resolve_constraints(self, constraints): if len(constraints) > 1: raise NotImplementedError() # pragma: no cover [(constraint_type, version)] = constraints remote_refs = git.get_remote_references_dict(self._url) if constraint_type == '==': ref = self._get_version_ref(remote_refs, version) elif constraint_type in (">=", ">"): ref = self._get_version_ref_from_minimal(remote_refs, version, inclusive = (constraint_type == '>=')) else: raise NotImplementedError() # pragma: no cover if ref is None: raise exceptions.RequiredVersionNotFound("Could not find version {0}".format(version)) _logger.info("Found match for %s%s on %s: %s", constraint_type, version, self._url, ref) return Git(self._url, branch=ref) def _get_version_ref(self, remote_refs, version): version = self._normalize_version(version) for remote_ref, normalized in self._iter_normalized_versions(remote_refs): if normalized == version: return remote_ref.to_ref_name() return None def _get_version_ref_from_minimal(self, remote_refs, version, inclusive): version = self._normalize_version(version) for remote_ref, normalized in self._iter_normalized_versions(remote_refs): if inclusive: matches = normalized >= version else: matches = normalized > version if matches: return remote_ref.to_ref_name() if git.Branch('master') in remote_refs: return git.Branch('master') return None def _iter_normalized_versions(self, collection): for ref_name in collection: normalized = self._normalize_version(ref_name) if normalized is None: continue yield ref_name, normalized def _normalize_version(self, version): if version.startswith("v") or version.startswith("V"): version = version[1:] return parse_version(version) @_exposed class Path(SignedSingleParam): def __init__(self, path, name=None): super(Path, self).__init__(path) self._param = os.path.expanduser(self._param) self._name = name if name is not None else self._param def install(self, env, reinstall): env.installer.install_unpacked_package(self._param, name=self._name, reinstall=reinstall) def checkout(self, env, path=None): if path is not None: raise NotImplementedError() return self._param @_exposed class PIP(SignedSingleParam): def install(self, env, reinstall): env.execute_pip_install(self._param, reinstall=reinstall) @_exposed class EasyInstall(SignedSingleParam): def install(self, env, reinstall): env.execute_easy_install(self._param, reinstall=reinstall) @_exposed class URL(PIP): pass class InvalidSCMURL(ValueError): pass @_exposed def SCM(source): for source_class in _KNOWN_SCMS: if source.startswith(source_class.get_prefix()): return source_class.from_string(source) raise InvalidSCMURL("Unsupported SCM source: {0!r}".format(source)) _KNOWN_SCMS = [Git] def get_all_sources_dict(): return _all_exposed_sources
{ "content_hash": "d06aee602ea3cd76e4fd8eb8e6b4c04b", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 113, "avg_line_length": 35.60112359550562, "alnum_prop": 0.6204828783335964, "repo_name": "vmalloc/pydeploy", "id": "e0462d34a27d80a895d3b82f2751c6f1ec7847a7", "size": "6337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pydeploy/sources.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "79314" } ], "symlink_target": "" }
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller, NoPolling from msrestazure.polling.arm_polling import ARMPolling from .. import models class RoutesOperations(object): """RoutesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client API version. Constant value: "2015-06-15". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2015-06-15" self.config = config def _delete_initial( self, resource_group_name, route_table_name, route_name, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.delete.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def delete( self, resource_group_name, route_table_name, route_name, custom_headers=None, raw=False, polling=True, **operation_config): """Deletes the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns None or ClientRawResponse<None> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._delete_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} def get( self, resource_group_name, route_table_name, route_name, custom_headers=None, raw=False, **operation_config): """Gets the specified route from a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: Route or ClientRawResponse if raw=true :rtype: ~azure.mgmt.network.v2015_06_15.models.Route or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.get.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('Route', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} def _create_or_update_initial( self, resource_group_name, route_table_name, route_name, route_parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.create_or_update.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'routeName': self._serialize.url("route_name", route_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(route_parameters, 'Route') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('Route', response) if response.status_code == 201: deserialized = self._deserialize('Route', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, route_table_name, route_name, route_parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Creates or updates a route in the specified route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param route_name: The name of the route. :type route_name: str :param route_parameters: Parameters supplied to the create or update route operation. :type route_parameters: ~azure.mgmt.network.v2015_06_15.models.Route :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns Route or ClientRawResponse<Route> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2015_06_15.models.Route] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.network.v2015_06_15.models.Route]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, route_table_name=route_table_name, route_name=route_name, route_parameters=route_parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('Route', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}'} def list( self, resource_group_name, route_table_name, custom_headers=None, raw=False, **operation_config): """Gets all routes in a route table. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_table_name: The name of the route table. :type route_table_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of Route :rtype: ~azure.mgmt.network.v2015_06_15.models.RoutePaged[~azure.mgmt.network.v2015_06_15.models.Route] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.RoutePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.RoutePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes'}
{ "content_hash": "9f4243361af742d94f0145cff23d1f96", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 185, "avg_line_length": 47.05337078651685, "alnum_prop": 0.6457524923885141, "repo_name": "lmazuel/azure-sdk-for-python", "id": "f159fb5fad517ed75f141231fca58afe4870b982", "size": "17225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2015_06_15/operations/routes_operations.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
from .error import Error, ErrorException from .auto_rest_swagger_bat_service_enums import ( Colors, ) __all__ = [ 'Error', 'ErrorException', 'Colors', ]
{ "content_hash": "445b1be8442a6c68db61857cd2e90c8f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 50, "avg_line_length": 18.444444444444443, "alnum_prop": 0.6506024096385542, "repo_name": "csmengwan/autorest", "id": "0652fe4bac9e45ff2705f9b4b50d2f328bcfba97", "size": "640", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "13761" }, { "name": "C#", "bytes": "10517556" }, { "name": "CSS", "bytes": "110" }, { "name": "HTML", "bytes": "274" }, { "name": "Java", "bytes": "4684473" }, { "name": "JavaScript", "bytes": "4658203" }, { "name": "PowerShell", "bytes": "5703" }, { "name": "Python", "bytes": "2237671" }, { "name": "Ruby", "bytes": "232025" }, { "name": "Shell", "bytes": "142" }, { "name": "TypeScript", "bytes": "179577" } ], "symlink_target": "" }
from traits.api import Any, List # ============= standard library imports ======================== # ============= local library imports ========================== from pychron.core.helpers.strtools import to_bool from pychron.core.ui.progress_dialog import myProgressDialog from pychron.envisage.initialization.initialization_parser import InitializationParser from pychron.globals import globalv from pychron.hardware.core.i_core_device import ICoreDevice from pychron.loggable import Loggable class InitializerError(BaseException): pass class Initializer(Loggable): name = "Initializer" _init_list = List _parser = Any _pd = Any def add_initialization(self, a): """ """ self.debug("add initialization {}".format(a)) self._init_list.append(a) def run(self, application=None): self._parser = InitializationParser() self.info("Initialization Path: {}".format(self._parser.path)) self.application = application ok = True self.info("Running Initializer") nsteps = ( sum([self._get_nsteps(idict["plugin_name"]) for idict in self._init_list]) + 1 ) pd = self._setup_progress(nsteps) try: for idict in self._init_list: ok = self._run(**idict) if not ok: break msg = "Complete" if ok else "Failed" self.info("Initialization {}".format(msg)) pd.close() except BaseException as e: import traceback traceback.print_exc() self.debug("Initializer Exception: {}".format(e)) raise e return ok def info(self, msg, **kw): pd = self._pd if pd is not None: offset = pd.get_value() if offset == pd.max - 1: pd.max += 1 pd.change_message(msg) super(Initializer, self).info(msg, **kw) def _run(self, name=None, manager=None, plugin_name=None): parser = self._parser if manager is not None: self.info("Manager loading {}".format(name)) manager.application = self.application manager.load() else: return False managers = [] if plugin_name: mp = self._get_plugin(plugin_name) else: mp, name = self._get_plugin_by_name(name) if mp is not None: if not globalv.ignore_initialization_required: if not self._check_required(mp): return False managers = parser.get_managers(mp) if managers: self.info("loading managers - {}".format(", ".join(managers))) manager.name = name self._load_managers(manager, managers, plugin_name) self._load_elements(mp, manager, name, plugin_name) if manager is not None: self.info("finish {} loading".format(name)) manager.finish_loading() return True def _load_elements(self, element, manager, name, plugin_name): mp = element parser = self._parser devices = parser.get_devices(mp) flags = parser.get_flags(mp) timed_flags = parser.get_timed_flags(mp) valve_flags = parser.get_valve_flags(mp, element=True) valve_flags_attrs = [] if valve_flags: for vf in valve_flags: vs = vf.find("valves") if vs: vs = vs.split(",") valve_flags_attrs.append((vf.text.strip(), vs)) if devices: self.info("loading devices - {}".format(", ".join(devices))) self._load_devices(manager, name, devices, plugin_name) if flags: self.info("loading flags - {}".format(", ".join(flags))) self._load_flags(manager, flags) if timed_flags: self.info("loading timed flags - {}".format(",".join(timed_flags))) self._load_timed_flags(manager, timed_flags) if valve_flags_attrs: self.info("loading valve flags - {}".format(",".join(valve_flags_attrs))) self._load_valve_flags(manager, valve_flags_attrs) # loaders def _load_flags(self, manager, flags): for f in flags: self.info("loading {}".format(f)) manager.add_flag(f) def _load_timed_flags(self, manager, flags): for f in flags: self.info("loading {}".format(f)) manager.add_timed_flag(f) def _load_valve_flags(self, manager, flags): for f, v in flags: self.info("loading {}, valves={}".format(f, v)) manager.add_valve_flag(f, v) def _load_devices( self, manager, name, devices, plugin_name, ): """ """ devs = [] if manager is None: return for device in devices: if not device: continue pdev = self._parser.get_device(name, device, plugin_name, element=True) dev_class = pdev.find("klass") if dev_class is not None: dev_class = dev_class.text.strip() try: dev = getattr(manager, device) if dev is None: dev = manager.create_device(device, dev_class=dev_class) else: if dev_class and dev.__class__.__name__ != dev_class: dev = manager.create_device( device, dev_class=dev_class, obj=dev ) except AttributeError: dev = manager.create_device(device, dev_class=dev_class) if dev is None: self.warning("No device for {}".format(device)) continue self.info("loading {}".format(dev.name)) dev.application = self.application if dev.load(): # register the device if self.application is not None: # display with the HardwareManager self.info("Register device name={}, {}".format(dev.name, dev)) self.application.register_service( ICoreDevice, dev, {"display": True} ) devs.append(dev) self.info("opening {}".format(dev.name)) if not dev.open(prefs=self.device_prefs): self.info("failed connecting to {}".format(dev.name)) else: self.info("failed loading {}".format(dev.name)) for od in devs: self.info("Initializing {}".format(od.name)) result = od.initialize(progress=self._pd) if result is not True: self.warning("Failed setting up communications to {}".format(od.name)) od.set_simulation(True) elif result is None: self.debug( "{} initialize function does not return a boolean".format(od.name) ) raise NotImplementedError od.application = self.application od.post_initialize() manager.devices.append(od) def _load_managers(self, manager, managers, plugin_name): for mi in managers: man = None self.info("load {}".format(mi)) try: man = getattr(manager, mi) if man is None: man = manager.create_manager(mi) except AttributeError as e: self.warning(e) try: man = manager.create_manager(mi) except InitializerError: import traceback traceback.print_exc() if man is None: self.debug("trouble creating manager {}".format(mi)) continue if self.application is not None: # register this manager as a service man.application = self.application self.application.register_service(type(man), man) man.load() element = self._get_manager(mi, plugin_name) if not globalv.ignore_initialization_required: if not self._check_required(element): return False self._load_elements(element, man, mi, plugin_name) self.info("finish {} loading".format(mi)) man.finish_loading() # helpers def _setup_progress(self, n): """ n: int, initialize progress dialog with n steps return a myProgressDialog object """ pd = myProgressDialog( max=n, message="Welcome", position=(100, 100), size=(500, 50) ) self._pd = pd self._pd.open() return pd def _check_required(self, subtree): # check the subtree has all required devices enabled devs = self._parser.get_devices(subtree, all_=True, element=True) for di in devs: required = True req = self._parser.get_parameter(di, "required") if req: required = to_bool(req) enabled = to_bool(di.get("enabled")) if required and not enabled: name = di.text.strip().upper() msg = """Device {} is REQUIRED but is not ENABLED. Do you want to quit to enable {} in the Initialization File?""".format( name, name ) result = self.confirmation_dialog(msg, title="Quit Pychron") if result: raise InitializerError() return True def _get_manager(self, name, plugin_name): parser = self._parser man = parser.get_manager(name, plugin_name) return man def _get_plugin(self, name): parser = self._parser mp = parser.get_plugin(name) return mp def _get_nsteps(self, plugin_name): parser = self._parser mp = self._get_plugin(plugin_name) ns = 0 if mp is not None: ns += 2 * (len(parser.get_managers(mp)) + 1) ns += 3 * (len(parser.get_devices(mp)) + 1) ns += len(parser.get_flags(mp)) + 1 ns += len(parser.get_timed_flags(mp)) + 1 return ns # ========================= EOF ===================================
{ "content_hash": "87699687f978fec0388f9837bea405a0", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 86, "avg_line_length": 31.24925816023739, "alnum_prop": 0.5194188586079195, "repo_name": "NMGRL/pychron", "id": "dacc3684fa88c5c65b1c77dde5cb1b3d21cdd965", "size": "11331", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "pychron/envisage/initialization/initializer.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "128" }, { "name": "C++", "bytes": "3706" }, { "name": "CSS", "bytes": "263" }, { "name": "Cython", "bytes": "1692" }, { "name": "Fortran", "bytes": "455875" }, { "name": "HTML", "bytes": "46796" }, { "name": "Mako", "bytes": "412" }, { "name": "Processing", "bytes": "11421" }, { "name": "Python", "bytes": "10773692" }, { "name": "Shell", "bytes": "1003" } ], "symlink_target": "" }
import inspect import logging import weakref import ray.ray_constants as ray_constants import ray._raylet import ray.signature as signature import ray.worker from ray.util.placement_group import PlacementGroup, \ check_placement_group_index from ray import ActorClassID, Language from ray._raylet import PythonFunctionDescriptor from ray import cross_language logger = logging.getLogger(__name__) def method(*args, **kwargs): """Annotate an actor method. .. code-block:: python @ray.remote class Foo: @ray.method(num_returns=2) def bar(self): return 1, 2 f = Foo.remote() _, _ = f.bar.remote() Args: num_returns: The number of object refs that should be returned by invocations of this actor method. """ assert len(args) == 0 assert len(kwargs) == 1 assert "num_returns" in kwargs num_returns = kwargs["num_returns"] def annotate_method(method): method.__ray_num_returns__ = num_returns return method return annotate_method # Create objects to wrap method invocations. This is done so that we can # invoke methods with actor.method.remote() instead of actor.method(). class ActorMethod: """A class used to invoke an actor method. Note: This class only keeps a weak ref to the actor, unless it has been passed to a remote function. This avoids delays in GC of the actor. Attributes: _actor: A handle to the actor. _method_name: The name of the actor method. _num_returns: The default number of return values that the method invocation should return. _decorator: An optional decorator that should be applied to the actor method invocation (as opposed to the actor method execution) before invoking the method. The decorator must return a function that takes in two arguments ("args" and "kwargs"). In most cases, it should call the function that was passed into the decorator and return the resulting ObjectRefs. For an example, see "test_decorated_method" in "python/ray/tests/test_actor.py". """ def __init__(self, actor, method_name, num_returns, decorator=None, hardref=False): self._actor_ref = weakref.ref(actor) self._method_name = method_name self._num_returns = num_returns # This is a decorator that is used to wrap the function invocation (as # opposed to the function execution). The decorator must return a # function that takes in two arguments ("args" and "kwargs"). In most # cases, it should call the function that was passed into the decorator # and return the resulting ObjectRefs. self._decorator = decorator # Acquire a hard ref to the actor, this is useful mainly when passing # actor method handles to remote functions. if hardref: self._actor_hard_ref = actor else: self._actor_hard_ref = None def __call__(self, *args, **kwargs): raise TypeError("Actor methods cannot be called directly. Instead " f"of running 'object.{self._method_name}()', try " f"'object.{self._method_name}.remote()'.") def remote(self, *args, **kwargs): return self._remote(args, kwargs) def options(self, **options): """Convenience method for executing an actor method call with options. Same arguments as func._remote(), but returns a wrapped function that a non-underscore .remote() can be called on. Examples: # The following two calls are equivalent. >>> actor.my_method._remote(args=[x, y], name="foo", num_returns=2) >>> actor.my_method.options(name="foo", num_returns=2).remote(x, y) """ func_cls = self class FuncWrapper: def remote(self, *args, **kwargs): return func_cls._remote(args=args, kwargs=kwargs, **options) return FuncWrapper() def _remote(self, args=None, kwargs=None, name="", num_returns=None): if num_returns is None: num_returns = self._num_returns def invocation(args, kwargs): actor = self._actor_hard_ref or self._actor_ref() if actor is None: raise RuntimeError("Lost reference to actor") return actor._actor_method_call( self._method_name, args=args, kwargs=kwargs, name=name, num_returns=num_returns) # Apply the decorator if there is one. if self._decorator is not None: invocation = self._decorator(invocation) return invocation(args, kwargs) def __getstate__(self): return { "actor": self._actor_ref(), "method_name": self._method_name, "num_returns": self._num_returns, "decorator": self._decorator, } def __setstate__(self, state): self.__init__( state["actor"], state["method_name"], state["num_returns"], state["decorator"], hardref=True) class ActorClassMethodMetadata(object): """Metadata for all methods in an actor class. This data can be cached. Attributes: methods: The actor methods. decorators: Optional decorators that should be applied to the method invocation function before invoking the actor methods. These can be set by attaching the attribute "__ray_invocation_decorator__" to the actor method. signatures: The signatures of the methods. num_returns: The default number of return values for each actor method. """ _cache = {} # This cache will be cleared in ray.disconnect() def __init__(self): class_name = type(self).__name__ raise TypeError(f"{class_name} can not be constructed directly, " f"instead of running '{class_name}()', " f"try '{class_name}.create()'") @classmethod def reset_cache(cls): cls._cache.clear() @classmethod def create(cls, modified_class, actor_creation_function_descriptor): # Try to create an instance from cache. cached_meta = cls._cache.get(actor_creation_function_descriptor) if cached_meta is not None: return cached_meta # Create an instance without __init__ called. self = cls.__new__(cls) actor_methods = inspect.getmembers(modified_class, ray.utils.is_function_or_method) self.methods = dict(actor_methods) # Extract the signatures of each of the methods. This will be used # to catch some errors if the methods are called with inappropriate # arguments. self.decorators = {} self.signatures = {} self.num_returns = {} for method_name, method in actor_methods: # Whether or not this method requires binding of its first # argument. For class and static methods, we do not want to bind # the first argument, but we do for instance methods is_bound = (ray.utils.is_class_method(method) or ray.utils.is_static_method(modified_class, method_name)) # Print a warning message if the method signature is not # supported. We don't raise an exception because if the actor # inherits from a class that has a method whose signature we # don't support, there may not be much the user can do about it. self.signatures[method_name] = signature.extract_signature( method, ignore_first=not is_bound) # Set the default number of return values for this method. if hasattr(method, "__ray_num_returns__"): self.num_returns[method_name] = (method.__ray_num_returns__) else: self.num_returns[method_name] = ( ray_constants.DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS) if hasattr(method, "__ray_invocation_decorator__"): self.decorators[method_name] = ( method.__ray_invocation_decorator__) # Update cache. cls._cache[actor_creation_function_descriptor] = self return self class ActorClassMetadata: """Metadata for an actor class. Attributes: language: The actor language, e.g. Python, Java. modified_class: The original class that was decorated (with some additional methods added like __ray_terminate__). actor_creation_function_descriptor: The function descriptor for the actor creation task. class_id: The ID of this actor class. class_name: The name of this class. num_cpus: The default number of CPUs required by the actor creation task. num_gpus: The default number of GPUs required by the actor creation task. memory: The heap memory quota for this actor. object_store_memory: The object store memory quota for this actor. resources: The default resources required by the actor creation task. last_export_session_and_job: A pair of the last exported session and job to help us to know whether this function was exported. This is an imperfect mechanism used to determine if we need to export the remote function again. It is imperfect in the sense that the actor class definition could be exported multiple times by different workers. method_meta: The actor method metadata. """ def __init__(self, language, modified_class, actor_creation_function_descriptor, class_id, max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type): self.language = language self.modified_class = modified_class self.actor_creation_function_descriptor = \ actor_creation_function_descriptor self.class_name = actor_creation_function_descriptor.class_name self.is_cross_language = language != Language.PYTHON self.class_id = class_id self.max_restarts = max_restarts self.max_task_retries = max_task_retries self.num_cpus = num_cpus self.num_gpus = num_gpus self.memory = memory self.object_store_memory = object_store_memory self.resources = resources self.accelerator_type = accelerator_type self.last_export_session_and_job = None self.method_meta = ActorClassMethodMetadata.create( modified_class, actor_creation_function_descriptor) class ActorClass: """An actor class. This is a decorated class. It can be used to create actors. Attributes: __ray_metadata__: Contains metadata for the actor. """ def __init__(cls, name, bases, attr): """Prevents users from directly inheriting from an ActorClass. This will be called when a class is defined with an ActorClass object as one of its base classes. To intentionally construct an ActorClass, use the '_ray_from_modified_class' classmethod. Raises: TypeError: Always. """ for base in bases: if isinstance(base, ActorClass): raise TypeError( f"Attempted to define subclass '{name}' of actor " f"class '{base.__ray_metadata__.class_name}'. " "Inheriting from actor classes is " "not currently supported. You can instead " "inherit from a non-actor base class and make " "the derived class an actor class (with " "@ray.remote).") # This shouldn't be reached because one of the base classes must be # an actor class if this was meant to be subclassed. assert False, ("ActorClass.__init__ should not be called. Please use " "the @ray.remote decorator instead.") def __call__(self, *args, **kwargs): """Prevents users from directly instantiating an ActorClass. This will be called instead of __init__ when 'ActorClass()' is executed because an is an object rather than a metaobject. To properly instantiated a remote actor, use 'ActorClass.remote()'. Raises: Exception: Always. """ raise TypeError("Actors cannot be instantiated directly. " f"Instead of '{self.__ray_metadata__.class_name}()', " f"use '{self.__ray_metadata__.class_name}.remote()'.") @classmethod def _ray_from_modified_class(cls, modified_class, class_id, max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type): for attribute in [ "remote", "_remote", "_ray_from_modified_class", "_ray_from_function_descriptor", ]: if hasattr(modified_class, attribute): logger.warning("Creating an actor from class " f"{modified_class.__name__} overwrites " f"attribute {attribute} of that class") # Make sure the actor class we are constructing inherits from the # original class so it retains all class properties. class DerivedActorClass(cls, modified_class): pass name = f"ActorClass({modified_class.__name__})" DerivedActorClass.__module__ = modified_class.__module__ DerivedActorClass.__name__ = name DerivedActorClass.__qualname__ = name # Construct the base object. self = DerivedActorClass.__new__(DerivedActorClass) # Actor creation function descriptor. actor_creation_function_descriptor = \ PythonFunctionDescriptor.from_class( modified_class.__ray_actor_class__) self.__ray_metadata__ = ActorClassMetadata( Language.PYTHON, modified_class, actor_creation_function_descriptor, class_id, max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type) return self @classmethod def _ray_from_function_descriptor( cls, language, actor_creation_function_descriptor, max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type): self = ActorClass.__new__(ActorClass) self.__ray_metadata__ = ActorClassMetadata( language, None, actor_creation_function_descriptor, None, max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type) return self def remote(self, *args, **kwargs): """Create an actor. Args: args: These arguments are forwarded directly to the actor constructor. kwargs: These arguments are forwarded directly to the actor constructor. Returns: A handle to the newly created actor. """ return self._remote(args=args, kwargs=kwargs) def options(self, args=None, kwargs=None, num_cpus=None, num_gpus=None, memory=None, object_store_memory=None, resources=None, accelerator_type=None, max_concurrency=None, max_restarts=None, max_task_retries=None, name=None, lifetime=None, placement_group=None, placement_group_bundle_index=-1): """Configures and overrides the actor instantiation parameters. The arguments are the same as those that can be passed to :obj:`ray.remote`. Examples: .. code-block:: python @ray.remote(num_cpus=2, resources={"CustomResource": 1}) class Foo: def method(self): return 1 # Class Foo will require 1 cpu instead of 2. # It will also require no custom resources. Bar = Foo.options(num_cpus=1, resources=None) """ actor_cls = self class ActorOptionWrapper: def remote(self, *args, **kwargs): return actor_cls._remote( args=args, kwargs=kwargs, num_cpus=num_cpus, num_gpus=num_gpus, memory=memory, object_store_memory=object_store_memory, resources=resources, accelerator_type=accelerator_type, max_concurrency=max_concurrency, max_restarts=max_restarts, max_task_retries=max_task_retries, name=name, lifetime=lifetime, placement_group=placement_group, placement_group_bundle_index=placement_group_bundle_index) return ActorOptionWrapper() def _remote(self, args=None, kwargs=None, num_cpus=None, num_gpus=None, memory=None, object_store_memory=None, resources=None, accelerator_type=None, max_concurrency=None, max_restarts=None, max_task_retries=None, name=None, lifetime=None, placement_group=None, placement_group_bundle_index=-1): """Create an actor. This method allows more flexibility than the remote method because resource requirements can be specified and override the defaults in the decorator. Args: args: The arguments to forward to the actor constructor. kwargs: The keyword arguments to forward to the actor constructor. num_cpus: The number of CPUs required by the actor creation task. num_gpus: The number of GPUs required by the actor creation task. memory: Restrict the heap memory usage of this actor. object_store_memory: Restrict the object store memory used by this actor when creating objects. resources: The custom resources required by the actor creation task. max_concurrency: The max number of concurrent calls to allow for this actor. This only works with direct actor calls. The max concurrency defaults to 1 for threaded execution, and 1000 for asyncio execution. Note that the execution order is not guaranteed when max_concurrency > 1. name: The globally unique name for the actor, which can be used to retrieve the actor via ray.get_actor(name) as long as the actor is still alive. lifetime: Either `None`, which defaults to the actor will fate share with its creator and will be deleted once its refcount drops to zero, or "detached", which means the actor will live as a global object independent of the creator. placement_group: the placement group this actor belongs to, or None if it doesn't belong to any group. placement_group_bundle_index: the index of the bundle if the actor belongs to a placement group, which may be -1 to specify any available bundle. Returns: A handle to the newly created actor. """ if args is None: args = [] if kwargs is None: kwargs = {} meta = self.__ray_metadata__ actor_has_async_methods = len( inspect.getmembers( meta.modified_class, predicate=inspect.iscoroutinefunction)) > 0 is_asyncio = actor_has_async_methods if max_concurrency is None: if is_asyncio: max_concurrency = 1000 else: max_concurrency = 1 if max_concurrency < 1: raise ValueError("max_concurrency must be >= 1") worker = ray.worker.global_worker worker.check_connected() if name is not None: if not isinstance(name, str): raise TypeError( f"name must be None or a string, got: '{type(name)}'.") if name == "": raise ValueError("Actor name cannot be an empty string.") # Check whether the name is already taken. # TODO(edoakes): this check has a race condition because two drivers # could pass the check and then create the same named actor. We should # instead check this when we create the actor, but that's currently an # async call. if name is not None: try: ray.get_actor(name) except ValueError: # Name is not taken. pass else: raise ValueError( f"The name {name} is already taken. Please use " "a different name or get the existing actor using " f"ray.get_actor('{name}')") if lifetime is None: detached = False elif lifetime == "detached": detached = True else: raise ValueError("lifetime must be either `None` or 'detached'") if placement_group is None: placement_group = PlacementGroup.empty() check_placement_group_index(placement_group, placement_group_bundle_index) # Set the actor's default resources if not already set. First three # conditions are to check that no resources were specified in the # decorator. Last three conditions are to check that no resources were # specified when _remote() was called. if (meta.num_cpus is None and meta.num_gpus is None and meta.resources is None and meta.accelerator_type is None and num_cpus is None and num_gpus is None and resources is None and accelerator_type is None): # In the default case, actors acquire no resources for # their lifetime, and actor methods will require 1 CPU. cpus_to_use = ray_constants.DEFAULT_ACTOR_CREATION_CPU_SIMPLE actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SIMPLE else: # If any resources are specified (here or in decorator), then # all resources are acquired for the actor's lifetime and no # resources are associated with methods. cpus_to_use = (ray_constants.DEFAULT_ACTOR_CREATION_CPU_SPECIFIED if meta.num_cpus is None else meta.num_cpus) actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SPECIFIED # LOCAL_MODE cannot handle cross_language if worker.mode == ray.LOCAL_MODE: assert not meta.is_cross_language, \ "Cross language ActorClass cannot be executed locally." # Export the actor. if not meta.is_cross_language and (meta.last_export_session_and_job != worker.current_session_and_job): # If this actor class was not exported in this session and job, # we need to export this function again, because current GCS # doesn't have it. meta.last_export_session_and_job = (worker.current_session_and_job) # After serialize / deserialize modified class, the __module__ # of modified class will be ray.cloudpickle.cloudpickle. # So, here pass actor_creation_function_descriptor to make # sure export actor class correct. worker.function_actor_manager.export_actor_class( meta.modified_class, meta.actor_creation_function_descriptor, meta.method_meta.methods.keys()) resources = ray.utils.resources_from_resource_arguments( cpus_to_use, meta.num_gpus, meta.memory, meta.object_store_memory, meta.resources, meta.accelerator_type, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type) # If the actor methods require CPU resources, then set the required # placement resources. If actor_placement_resources is empty, then # the required placement resources will be the same as resources. actor_placement_resources = {} assert actor_method_cpu in [0, 1] if actor_method_cpu == 1: actor_placement_resources = resources.copy() actor_placement_resources["CPU"] += 1 if meta.is_cross_language: creation_args = cross_language.format_args(worker, args, kwargs) else: function_signature = meta.method_meta.signatures["__init__"] creation_args = signature.flatten_args(function_signature, args, kwargs) actor_id = worker.core_worker.create_actor( meta.language, meta.actor_creation_function_descriptor, creation_args, max_restarts or meta.max_restarts, max_task_retries or meta.max_task_retries, resources, actor_placement_resources, max_concurrency, detached, name if name is not None else "", is_asyncio, placement_group.id, placement_group_bundle_index, # Store actor_method_cpu in actor handle's extension data. extension_data=str(actor_method_cpu)) actor_handle = ActorHandle( meta.language, actor_id, meta.method_meta.decorators, meta.method_meta.signatures, meta.method_meta.num_returns, actor_method_cpu, meta.actor_creation_function_descriptor, worker.current_session_and_job, original_handle=True) return actor_handle class ActorHandle: """A handle to an actor. The fields in this class are prefixed with _ray_ to hide them from the user and to avoid collision with actor method names. An ActorHandle can be created in three ways. First, by calling .remote() on an ActorClass. Second, by passing an actor handle into a task (forking the ActorHandle). Third, by directly serializing the ActorHandle (e.g., with cloudpickle). Attributes: _ray_actor_language: The actor language. _ray_actor_id: Actor ID. _ray_method_decorators: Optional decorators for the function invocation. This can be used to change the behavior on the invocation side, whereas a regular decorator can be used to change the behavior on the execution side. _ray_method_signatures: The signatures of the actor methods. _ray_method_num_returns: The default number of return values for each method. _ray_actor_method_cpus: The number of CPUs required by actor methods. _ray_original_handle: True if this is the original actor handle for a given actor. If this is true, then the actor will be destroyed when this handle goes out of scope. _ray_is_cross_language: Whether this actor is cross language. _ray_actor_creation_function_descriptor: The function descriptor of the actor creation task. """ def __init__(self, language, actor_id, method_decorators, method_signatures, method_num_returns, actor_method_cpus, actor_creation_function_descriptor, session_and_job, original_handle=False): self._ray_actor_language = language self._ray_actor_id = actor_id self._ray_original_handle = original_handle self._ray_method_decorators = method_decorators self._ray_method_signatures = method_signatures self._ray_method_num_returns = method_num_returns self._ray_actor_method_cpus = actor_method_cpus self._ray_session_and_job = session_and_job self._ray_is_cross_language = language != Language.PYTHON self._ray_actor_creation_function_descriptor = \ actor_creation_function_descriptor self._ray_function_descriptor = {} if not self._ray_is_cross_language: assert isinstance(actor_creation_function_descriptor, PythonFunctionDescriptor) module_name = actor_creation_function_descriptor.module_name class_name = actor_creation_function_descriptor.class_name for method_name in self._ray_method_signatures.keys(): function_descriptor = PythonFunctionDescriptor( module_name, method_name, class_name) self._ray_function_descriptor[ method_name] = function_descriptor method = ActorMethod( self, method_name, self._ray_method_num_returns[method_name], decorator=self._ray_method_decorators.get(method_name)) setattr(self, method_name, method) def __del__(self): # Mark that this actor handle has gone out of scope. Once all actor # handles are out of scope, the actor will exit. worker = ray.worker.global_worker if worker.connected and hasattr(worker, "core_worker"): worker.core_worker.remove_actor_handle_reference( self._ray_actor_id) def _actor_method_call(self, method_name, args=None, kwargs=None, name="", num_returns=None): """Method execution stub for an actor handle. This is the function that executes when `actor.method_name.remote(*args, **kwargs)` is called. Instead of executing locally, the method is packaged as a task and scheduled to the remote actor instance. Args: method_name: The name of the actor method to execute. args: A list of arguments for the actor method. kwargs: A dictionary of keyword arguments for the actor method. name (str): The name to give the actor method call task. num_returns (int): The number of return values for the method. Returns: object_refs: A list of object refs returned by the remote actor method. """ worker = ray.worker.global_worker args = args or [] kwargs = kwargs or {} if self._ray_is_cross_language: list_args = cross_language.format_args(worker, args, kwargs) function_descriptor = \ cross_language.get_function_descriptor_for_actor_method( self._ray_actor_language, self._ray_actor_creation_function_descriptor, method_name) else: function_signature = self._ray_method_signatures[method_name] if not args and not kwargs and not function_signature: list_args = [] else: list_args = signature.flatten_args(function_signature, args, kwargs) function_descriptor = self._ray_function_descriptor[method_name] if worker.mode == ray.LOCAL_MODE: assert not self._ray_is_cross_language,\ "Cross language remote actor method " \ "cannot be executed locally." object_refs = worker.core_worker.submit_actor_task( self._ray_actor_language, self._ray_actor_id, function_descriptor, list_args, name, num_returns, self._ray_actor_method_cpus) if len(object_refs) == 1: object_refs = object_refs[0] elif len(object_refs) == 0: object_refs = None return object_refs def __getattr__(self, item): if not self._ray_is_cross_language: raise AttributeError(f"'{type(self).__name__}' object has " f"no attribute '{item}'") if item in ["__ray_terminate__", "__ray_checkpoint__"]: class FakeActorMethod(object): def __call__(self, *args, **kwargs): raise TypeError( "Actor methods cannot be called directly. Instead " "of running 'object.{}()', try 'object.{}.remote()'.". format(item, item)) def remote(self, *args, **kwargs): logger.warning(f"Actor method {item} is not " "supported by cross language.") return FakeActorMethod() return ActorMethod( self, item, ray_constants. # Currently, we use default num returns DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS, # Currently, cross-lang actor method not support decorator decorator=None) # Make tab completion work. def __dir__(self): return self._ray_method_signatures.keys() def __repr__(self): return (f"Actor(" f"{self._ray_actor_creation_function_descriptor.class_name}," f"{self._actor_id.hex()})") @property def _actor_id(self): return self._ray_actor_id def _serialization_helper(self): """This is defined in order to make pickling work. Returns: A dictionary of the information needed to reconstruct the object. """ worker = ray.worker.global_worker worker.check_connected() if hasattr(worker, "core_worker"): # Non-local mode state = worker.core_worker.serialize_actor_handle( self._ray_actor_id) else: # Local mode state = ({ "actor_language": self._ray_actor_language, "actor_id": self._ray_actor_id, "method_decorators": self._ray_method_decorators, "method_signatures": self._ray_method_signatures, "method_num_returns": self._ray_method_num_returns, "actor_method_cpus": self._ray_actor_method_cpus, "actor_creation_function_descriptor": self. _ray_actor_creation_function_descriptor, }, None) return state @classmethod def _deserialization_helper(cls, state, outer_object_ref=None): """This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. outer_object_ref: The ObjectRef that the serialized actor handle was contained in, if any. This is used for counting references to the actor handle. """ worker = ray.worker.global_worker worker.check_connected() if hasattr(worker, "core_worker"): # Non-local mode return worker.core_worker.deserialize_and_register_actor_handle( state, outer_object_ref) else: # Local mode return cls( # TODO(swang): Accessing the worker's current task ID is not # thread-safe. state["actor_language"], state["actor_id"], state["method_decorators"], state["method_signatures"], state["method_num_returns"], state["actor_method_cpus"], state["actor_creation_function_descriptor"], worker.current_session_and_job) def __reduce__(self): """This code path is used by pickling but not by Ray forking.""" state = self._serialization_helper() return ActorHandle._deserialization_helper, (state) def modify_class(cls): # cls has been modified. if hasattr(cls, "__ray_actor_class__"): return cls # Give an error if cls is an old-style class. if not issubclass(cls, object): raise TypeError( "The @ray.remote decorator cannot be applied to old-style " "classes. In Python 2, you must declare the class with " "'class ClassName(object):' instead of 'class ClassName:'.") # Modify the class to have an additional method that will be used for # terminating the worker. class Class(cls): __ray_actor_class__ = cls # The original actor class def __ray_terminate__(self): worker = ray.worker.global_worker if worker.mode != ray.LOCAL_MODE: ray.actor.exit_actor() Class.__module__ = cls.__module__ Class.__name__ = cls.__name__ if not ray.utils.is_function_or_method(getattr(Class, "__init__", None)): # Add __init__ if it does not exist. # Actor creation will be executed with __init__ together. # Assign an __init__ function will avoid many checks later on. def __init__(self): pass Class.__init__ = __init__ return Class def make_actor(cls, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type, max_restarts, max_task_retries): Class = modify_class(cls) if max_restarts is None: max_restarts = 0 if max_task_retries is None: max_task_retries = 0 infinite_restart = max_restarts == -1 if not infinite_restart: if max_restarts < 0: raise ValueError("max_restarts must be an integer >= -1 " "-1 indicates infinite restarts") else: # Make sure we don't pass too big of an int to C++, causing # an overflow. max_restarts = min(max_restarts, ray_constants.MAX_INT64_VALUE) if max_restarts == 0 and max_task_retries != 0: raise ValueError( "max_task_retries cannot be set if max_restarts is 0.") return ActorClass._ray_from_modified_class( Class, ActorClassID.from_random(), max_restarts, max_task_retries, num_cpus, num_gpus, memory, object_store_memory, resources, accelerator_type) def exit_actor(): """Intentionally exit the current actor. This function is used to disconnect an actor and exit the worker. Raises: Exception: An exception is raised if this is a driver or this worker is not an actor. """ worker = ray.worker.global_worker if worker.mode == ray.WORKER_MODE and not worker.actor_id.is_nil(): # Intentionally disconnect the core worker from the raylet so the # raylet won't push an error message to the driver. ray.disconnect() # Disconnect global state from GCS. ray.state.state.disconnect() # Set a flag to indicate this is an intentional actor exit. This # reduces log verbosity. exit = SystemExit(0) exit.is_ray_terminate = True raise exit assert False, "This process should have terminated." else: raise TypeError("exit_actor called on a non-actor worker.")
{ "content_hash": "e9324dfc4bf9be54dc629b61197528bf", "timestamp": "", "source": "github", "line_count": 999, "max_line_length": 79, "avg_line_length": 40.34134134134134, "alnum_prop": 0.5834842807870773, "repo_name": "robertnishihara/ray", "id": "a2a90d8738c2b3dc447546ed66595c6b69aecc0f", "size": "40301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/ray/actor.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "82909" }, { "name": "C++", "bytes": "3971373" }, { "name": "CSS", "bytes": "8025" }, { "name": "Cython", "bytes": "179979" }, { "name": "Dockerfile", "bytes": "6468" }, { "name": "Go", "bytes": "23139" }, { "name": "HTML", "bytes": "30414" }, { "name": "Java", "bytes": "1248954" }, { "name": "JavaScript", "bytes": "444" }, { "name": "Jupyter Notebook", "bytes": "1615" }, { "name": "Makefile", "bytes": "2205" }, { "name": "Python", "bytes": "6567694" }, { "name": "Shell", "bytes": "102477" }, { "name": "Starlark", "bytes": "231513" }, { "name": "TypeScript", "bytes": "147793" } ], "symlink_target": "" }
import progressbar import re import time from utils import get_log LOG = get_log(__name__) # Maximum Bytes Per Packet CHUNK_SIZE = 512 * 1024 # B class FileLikeProxy: def __init__(self, transfer_object, callback, speed_limit='1mb'): self.__callback = callback if callback else lambda size, length, obj_id, name: True self.resp = transfer_object['resource'].get_ref_image( transfer_object['id']) self.length = ( self.resp.length if self.resp.length else transfer_object['size']) self.id = transfer_object['id'] self.name = transfer_object['name'] self.percent = self.length / 100 self.res = 0 self.delta = 0 self.buffer = '' self.prev_send_time = 0 self.speed_limit = self.__parse_speed_limit(speed_limit) if self.speed_limit != 0: self.read = self.speed_limited_read def __parse_speed_limit(self, speed_limit): if speed_limit is '-': return 0 array = filter(None, re.split(r'(\d+)', speed_limit)) mult = { 'b': 1, 'kb': 1024, 'mb': 1024 * 1024, }[array[1].lower()] return int(array[0]) * mult def read(self, *args, **kwargs): res = self.resp.read(*args, **kwargs) self.__trigger_callback(len(res)) return res def speed_limited_read(self, *args, **kwargs): if len(self.buffer) < CHUNK_SIZE: self.buffer += self.resp.read(*args, **kwargs) res = self.buffer[0:CHUNK_SIZE] self.buffer = self.buffer[CHUNK_SIZE::] self.__trigger_callback(len(res)) cur_send_time = time.time() sleep_time = float(len(res)) / self.speed_limit sleep_time -= cur_send_time - self.prev_send_time time.sleep(max((0, sleep_time))) self.prev_send_time = cur_send_time return res def __trigger_callback(self, len_data): self.delta += len_data if self.delta == len_data: msg = 'Download file {}({}): '.format(self.name, self.id) self.bar = progressbar.ProgressBar( widgets=[ msg, progressbar.Bar(left='[', marker='=', right=']'), progressbar.Percentage() ] ).start() self.res += len_data if (self.delta > self.percent) or (len_data == 0): self.bar.update(self.res * 100 / self.length) self.delta = 0 if len_data == 0: self.bar.finish() def close(self): self.resp.close() def isclosed(self): return self.resp.isclosed() def begin(self): return self.resp.begin() def getheader(self, *args, **kwargs): res = self.resp.getheader(*args, **kwargs) return res
{ "content_hash": "690ec9f86e71b233b39103983f2531ee", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 91, "avg_line_length": 31.451612903225808, "alnum_prop": 0.5305982905982906, "repo_name": "roman-verchikov/CloudFerry", "id": "584072f4cdbc4fed76361973b5b4f2239c694155", "size": "3501", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cloudferrylib/utils/file_like_proxy.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2615" }, { "name": "Python", "bytes": "852519" }, { "name": "Ruby", "bytes": "6098" }, { "name": "Shell", "bytes": "37495" } ], "symlink_target": "" }
from Tkinter import * class BoothDisplay: root = None font = "Courier" font_size = 46 def __init__(self): self.root = Tk() self.root.configure(background="black") self.parent = Frame(root) self.root.overrideredirect(True) self.root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight())) self.root.focus_set() # self.root.bind("<Escape>", lambda e: e.widget.quit()) def display(self): self.parent.pack(expand=1) def displayReadyMessage(self): msg = Label(self.parent, text="Push the Red Button", anchor=CENTER, justify=CENTER, fg="white", bg="black", font=(self.font, self.font_size)).pack()
{ "content_hash": "1bff3c133acf19636cab7b86597e3a03", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 101, "avg_line_length": 30.035714285714285, "alnum_prop": 0.5338882282996433, "repo_name": "brookshire/rpi-photobooth", "id": "2905767509009a1a26d7b438f619e2885e9a61b8", "size": "841", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "photobooth/display.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "9049" } ], "symlink_target": "" }
from import_export import fields, resources class GamesPlayedResource(resources.Resource): game = fields.Field(attribute='game__name', column_name='game') time = fields.Field(attribute='time', column_name='time (hours)') num_players = fields.Field(attribute='num_players', column_name='num_players') class Meta: export_order = ['game', 'time', 'num_players'] def dehydrate_game(self, obj): return obj['game__name'] def dehydrate_time(self, obj): return obj['time'].total_seconds() / 3600 def dehydrate_num_players(self, obj): return obj['num_players']
{ "content_hash": "eebc128ad1d24447ab546b80d71458b1", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 82, "avg_line_length": 30.95, "alnum_prop": 0.6607431340872375, "repo_name": "sergei-maertens/discord-bot", "id": "f6ce91df7885060a3351415e76d916d6060d5cc9", "size": "619", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "bot/plugins/stats/resources.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1069" }, { "name": "HTML", "bytes": "165" }, { "name": "Python", "bytes": "87711" }, { "name": "Shell", "bytes": "896" } ], "symlink_target": "" }
"""Subclasses of information.""" from .models import Info class Gene(Info): """A gene.""" __mapper_args__ = {"polymorphic_identity": "gene"} class Meme(Info): """A meme.""" __mapper_args__ = {"polymorphic_identity": "meme"} class State(Info): """A state.""" __mapper_args__ = {"polymorphic_identity": "state"} class TrackingEvent(Info): """A state.""" __mapper_args__ = {"polymorphic_identity": "tracking"}
{ "content_hash": "7d7b11752af81434d9f5944a16631dab", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 58, "avg_line_length": 16.74074074074074, "alnum_prop": 0.584070796460177, "repo_name": "Dallinger/Dallinger", "id": "fdcce33a439ad4de5a820414afcca5b859ec7270", "size": "452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dallinger/information.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2204" }, { "name": "Dockerfile", "bytes": "4288" }, { "name": "HTML", "bytes": "62909" }, { "name": "JavaScript", "bytes": "49602" }, { "name": "Jinja", "bytes": "4871" }, { "name": "Procfile", "bytes": "88" }, { "name": "Python", "bytes": "1131695" }, { "name": "Ruby", "bytes": "1769" }, { "name": "Shell", "bytes": "2905" } ], "symlink_target": "" }
import numpy as np import pandas as pd from keras.models import Model from keras.layers import Dense, Embedding, Input from keras.layers import LSTM, Bidirectional, GlobalMaxPool1D, Dropout, Conv1D, MaxPooling1D, Flatten from keras.preprocessing import text, sequence max_features = 2000 maxlen = 450 train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") train = train.sample(frac=1) list_sentences_train = train["comment_text"].fillna("NULL").values list_classes = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"] y = train[list_classes].values list_sentences_test = test["comment_text"].fillna("NULL").values tokenizer = text.Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(list_sentences_train)) list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train) list_tokenized_test = tokenizer.texts_to_sequences(list_sentences_test) X_t = sequence.pad_sequences(list_tokenized_train, maxlen=maxlen) X_te = sequence.pad_sequences(list_tokenized_test, maxlen=maxlen) def get_CNN_model(): embed_size = 128 inp = Input(shape=(maxlen,)) x = Embedding(max_features, embed_size)(inp) x = Conv1D(filters=64, kernel_size=3, padding='same', activation='relu')(x) x = MaxPooling1D(pool_size=2)(x) x = Flatten()(x) x = Dense(250, activation='sigmoid')(x) x = Dense(6, activation="sigmoid")(x) model = Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) return model model = get_CNN_model() batch_size = 64 epochs = 2 model.fit(X_t, y, batch_size=batch_size, epochs=epochs, validation_split=0.1) y_test = model.predict(X_te) sample_submission = pd.read_csv("sample_submission.csv") sample_submission[list_classes] = y_test sample_submission.to_csv("results.csv", index=False)
{ "content_hash": "1eae16d3c5f2a83a49edcf9c72ce76e8", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 101, "avg_line_length": 33.535714285714285, "alnum_prop": 0.7140575079872205, "repo_name": "AhmedHani/Kaggle-Machine-Learning-Competitions", "id": "8ed607e4f9cd71c0d366d0ff42395be02de4b524", "size": "1878", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Medium/Toxic Comment Classification Challenge/playground.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "139524" }, { "name": "Python", "bytes": "46606" } ], "symlink_target": "" }
from __future__ import division import chainer import chainer.functions as F import chainer.links as L import numpy as np from chainercv.experimental.links.model.fcis import FCIS from chainercv.functions import ps_roi_average_pooling_2d from chainercv.links import Conv2DBNActiv from chainercv.links.model.faster_rcnn.region_proposal_network import \ RegionProposalNetwork from chainercv.links.model.faster_rcnn.utils.loc2bbox import loc2bbox from chainercv.links.model.resnet.resblock import ResBlock from chainercv.links import ResNet101 from chainercv import utils class FCISResNet101(FCIS): """FCIS based on ResNet101. When you specify the path of a pre-trained chainer model serialized as a :obj:`.npz` file in the constructor, this chain model automatically initializes all the parameters with it. When a string in prespecified set is provided, a pretrained model is loaded from weights distributed on the Internet. The list of pretrained models supported are as follows: * :obj:`sbd`: Loads weights trained with the trainval split of Semantic \ Boundaries Dataset. For descriptions on the interface of this model, please refer to :class:`~chainercv.experimental.links.model.fcis.FCIS`. :class:`~chainercv.experimental.links.model.fcis.FCISResNet101` supports finer control on random initializations of weights by arguments :obj:`resnet_initialW`, :obj:`rpn_initialW` and :obj:`head_initialW`. It accepts a callable that takes an array and edits its values. If :obj:`None` is passed as an initializer, the default initializer is used. Args: n_fg_class (int): The number of classes excluding the background. pretrained_model (str): The destination of the pre-trained chainer model serialized as a :obj:`.npz` file. If this is one of the strings described above, it automatically loads weights stored under a directory :obj:`$CHAINER_DATASET_ROOT/pfnet/chainercv/models/`, where :obj:`$CHAINER_DATASET_ROOT` is set as :obj:`$HOME/.chainer/dataset` unless you specify another value by modifying the environment variable. min_size (int): A preprocessing paramter for :meth:`prepare`. max_size (int): A preprocessing paramter for :meth:`prepare`. roi_size (int): Height and width of the feature maps after Position Sensitive RoI pooling. group_size (int): Group height and width for Position Sensitive ROI pooling. ratios (list of floats): This is ratios of width to height of the anchors. anchor_scales (list of numbers): This is areas of anchors. Those areas will be the product of the square of an element in :obj:`anchor_scales` and the original area of the reference window. loc_normalize_mean (tuple of four floats): Mean values of localization estimates. loc_normalize_std (tupler of four floats): Standard deviation of localization estimates. iter2 (bool): if the value is set :obj:`True`, Position Sensitive ROI pooling is executed twice. In the second time, Position Sensitive ROI pooling uses improved ROIs by the localization parameters calculated in the first time. resnet_initialW (callable): Initializer for the layers corresponding to the ResNet101 layers. rpn_initialW (callable): Initializer for Region Proposal Network layers. head_initialW (callable): Initializer for the head layers. proposal_creator_params (dict): Key valued paramters for :class:`~chainercv.links.model.faster_rcnn.ProposalCreator`. """ _models = { 'sbd': { 'param': {'n_fg_class': 20}, 'url': 'https://chainercv-models.preferred.jp/' 'fcis_resnet101_sbd_trained_2018_06_22.npz', 'cv2': True }, 'sbd_converted': { 'param': {'n_fg_class': 20}, 'url': 'https://chainercv-models.preferred.jp/' 'fcis_resnet101_sbd_converted_2018_07_02.npz', 'cv2': True }, 'coco': { 'param': {'n_fg_class': 80}, 'url': 'https://chainercv-models.preferred.jp/' 'fcis_resnet101_coco_trained_2019_01_30.npz', 'cv2': True }, 'coco_converted': { 'param': {'n_fg_class': 80}, 'url': 'https://chainercv-models.preferred.jp/' 'fcis_resnet101_coco_converted_2019_01_30.npz', 'cv2': True } } feat_stride = 16 proposal_creator_params = { 'nms_thresh': 0.7, 'n_train_pre_nms': 6000, 'n_train_post_nms': 300, 'n_test_pre_nms': 6000, 'n_test_post_nms': 300, 'force_cpu_nms': False, 'min_size': 16 } def __init__( self, n_fg_class=None, pretrained_model=None, min_size=600, max_size=1000, roi_size=21, group_size=7, ratios=[0.5, 1, 2], anchor_scales=[8, 16, 32], loc_normalize_mean=(0.0, 0.0, 0.0, 0.0), loc_normalize_std=(0.2, 0.2, 0.5, 0.5), iter2=True, resnet_initialW=None, rpn_initialW=None, head_initialW=None, proposal_creator_params=None): param, path = utils.prepare_pretrained_model( {'n_fg_class': n_fg_class}, pretrained_model, self._models) if rpn_initialW is None: rpn_initialW = chainer.initializers.Normal(0.01) if resnet_initialW is None and pretrained_model: resnet_initialW = chainer.initializers.constant.Zero() if proposal_creator_params is not None: self.proposal_creator_params = proposal_creator_params extractor = ResNet101Extractor( initialW=resnet_initialW) rpn = RegionProposalNetwork( 1024, 512, ratios=ratios, anchor_scales=anchor_scales, feat_stride=self.feat_stride, initialW=rpn_initialW, proposal_creator_params=self.proposal_creator_params) head = FCISResNet101Head( param['n_fg_class'] + 1, roi_size=roi_size, group_size=group_size, spatial_scale=1. / self.feat_stride, loc_normalize_mean=loc_normalize_mean, loc_normalize_std=loc_normalize_std, iter2=iter2, initialW=head_initialW) mean = np.array([123.15, 115.90, 103.06], dtype=np.float32)[:, None, None] super(FCISResNet101, self).__init__( extractor, rpn, head, mean, min_size, max_size, loc_normalize_mean, loc_normalize_std) if path == 'imagenet': self._copy_imagenet_pretrained_resnet() elif path: chainer.serializers.load_npz(path, self) def _copy_imagenet_pretrained_resnet(self): def _copy_conv2dbn(src, dst): dst.conv.W.array = src.conv.W.array if src.conv.b is not None and dst.conv.b is not None: dst.conv.b.array = src.conv.b.array dst.bn.gamma.array = src.bn.gamma.array dst.bn.beta.array = src.bn.beta.array dst.bn.avg_var = src.bn.avg_var dst.bn.avg_mean = src.bn.avg_mean def _copy_bottleneck(src, dst): if hasattr(src, 'residual_conv'): _copy_conv2dbn(src.residual_conv, dst.residual_conv) _copy_conv2dbn(src.conv1, dst.conv1) _copy_conv2dbn(src.conv2, dst.conv2) _copy_conv2dbn(src.conv3, dst.conv3) def _copy_resblock(src, dst): for layer_name in src.layer_names: _copy_bottleneck( getattr(src, layer_name), getattr(dst, layer_name)) pretrained_model = ResNet101(arch='he', pretrained_model='imagenet') _copy_conv2dbn(pretrained_model.conv1, self.extractor.conv1) _copy_resblock(pretrained_model.res2, self.extractor.res2) _copy_resblock(pretrained_model.res3, self.extractor.res3) _copy_resblock(pretrained_model.res4, self.extractor.res4) _copy_resblock(pretrained_model.res5, self.extractor.res5) class ResNet101Extractor(chainer.Chain): """ResNet101 Extractor for FCIS ResNet101 implementation. This class is used as an extractor for FCISResNet101. This outputs feature maps. Dilated convolution is used in the C5 stage. Args: initialW: Initializer for ResNet101 extractor. """ def __init__(self, initialW=None): super(ResNet101Extractor, self).__init__() if initialW is None: initialW = chainer.initializers.HeNormal() kwargs = { 'initialW': initialW, 'bn_kwargs': {'eps': 1e-5}, 'stride_first': True } with self.init_scope(): # ResNet self.conv1 = Conv2DBNActiv( 3, 64, 7, 2, 3, nobias=True, initialW=initialW) self.pool1 = lambda x: F.max_pooling_2d(x, ksize=3, stride=2) self.res2 = ResBlock(3, 64, 64, 256, 1, **kwargs) self.res3 = ResBlock(4, 256, 128, 512, 2, **kwargs) self.res4 = ResBlock(23, 512, 256, 1024, 2, **kwargs) self.res5 = ResBlock(3, 1024, 512, 2048, 1, 2, **kwargs) def forward(self, x): """Forward the chain. Args: x (~chainer.Variable): 4D image variable. """ with chainer.using_config('train', False): h = self.pool1(self.conv1(x)) h = self.res2(h) h.unchain_backward() h = self.res3(h) res4 = self.res4(h) res5 = self.res5(res4) return res4, res5 class FCISResNet101Head(chainer.Chain): """FCIS Head for ResNet101 based implementation. This class is used as a head for FCIS. This outputs class-agnostice segmentation scores, class-agnostic localizations and classification based on feature maps in the given RoIs. Args: n_class (int): The number of classes possibly including the background. roi_size (int): Height and width of the feature maps after Position Sensitive RoI pooling. group_size (int): Group height and width for Position Sensitive ROI pooling. spatial_scale (float): Scale of the roi is resized. loc_normalize_mean (tuple of four floats): Mean values of localization estimates. loc_normalize_std (tupler of four floats): Standard deviation of localization estimates. iter2 (bool): if the value is set :obj:`True`, Position Sensitive ROI pooling is executed twice. In the second time, Position Sensitive ROI pooling uses improved ROIs by the localization parameters calculated in the first time. initialW (callable): Initializer for the layers. """ def __init__( self, n_class, roi_size, group_size, spatial_scale, loc_normalize_mean, loc_normalize_std, iter2, initialW=None ): super(FCISResNet101Head, self).__init__() if initialW is None: initialW = chainer.initializers.Normal(0.01) self.n_class = n_class self.spatial_scale = spatial_scale self.group_size = group_size self.roi_size = roi_size self.loc_normalize_mean = loc_normalize_mean self.loc_normalize_std = loc_normalize_std self.iter2 = iter2 with self.init_scope(): self.conv1 = L.Convolution2D( 2048, 1024, 1, 1, 0, initialW=initialW) self.cls_seg = L.Convolution2D( 1024, group_size * group_size * n_class * 2, 1, 1, 0, initialW=initialW) self.ag_loc = L.Convolution2D( 1024, group_size * group_size * 2 * 4, 1, 1, 0, initialW=initialW) def forward(self, x, rois, roi_indices, img_size, gt_roi_labels=None): """Forward the chain. We assume that there are :math:`N` batches. Args: x (~chainer.Variable): 4D image variable. rois (array): A bounding box array containing coordinates of proposal boxes. This is a concatenation of bounding box arrays from multiple images in the batch. Its shape is :math:`(R', 4)`. Given :math:`R_i` proposed RoIs from the :math:`i` th image, :math:`R' = \\sum _{i=1} ^ N R_i`. roi_indices (array): An array containing indices of images to which bounding boxes correspond to. Its shape is :math:`(R',)`. img_size (tuple of int): A tuple containing image size. """ h = F.relu(self.conv1(x)) h_cls_seg = self.cls_seg(h) h_ag_loc = self.ag_loc(h) # PSROI pooling and regression roi_ag_seg_scores, roi_ag_locs, roi_cls_scores = self._pool( h_cls_seg, h_ag_loc, rois, roi_indices, gt_roi_labels) if self.iter2: # 2nd Iteration # get rois2 for more precise prediction roi_ag_locs = roi_ag_locs.array mean = self.xp.array(self.loc_normalize_mean) std = self.xp.array(self.loc_normalize_std) roi_locs = roi_ag_locs[:, 1, :] roi_locs = (roi_locs * std + mean).astype(np.float32) rois2 = loc2bbox(rois, roi_locs) rois2[:, 0::2] = self.xp.clip(rois2[:, 0::2], 0, img_size[0]) rois2[:, 1::2] = self.xp.clip(rois2[:, 1::2], 0, img_size[1]) # PSROI pooling and regression roi_ag_seg_scores2, roi_ag_locs2, roi_cls_scores2 = self._pool( h_cls_seg, h_ag_loc, rois2, roi_indices, gt_roi_labels) # concat 1st and 2nd iteration results rois = self.xp.concatenate((rois, rois2)) roi_indices = self.xp.concatenate((roi_indices, roi_indices)) roi_ag_seg_scores = F.concat( (roi_ag_seg_scores, roi_ag_seg_scores2), axis=0) roi_ag_locs = F.concat( (roi_ag_locs, roi_ag_locs2), axis=0) roi_cls_scores = F.concat( (roi_cls_scores, roi_cls_scores2), axis=0) return roi_ag_seg_scores, roi_ag_locs, roi_cls_scores, \ rois, roi_indices def _pool( self, h_cls_seg, h_ag_loc, rois, roi_indices, gt_roi_labels): # PSROI Pooling # shape: (n_roi, n_class, 2, roi_size, roi_size) roi_cls_ag_seg_scores = ps_roi_average_pooling_2d( h_cls_seg, rois, roi_indices, (self.n_class * 2, self.roi_size, self.roi_size), self.spatial_scale, self.group_size) roi_cls_ag_seg_scores = F.reshape( roi_cls_ag_seg_scores, (-1, self.n_class, 2, self.roi_size, self.roi_size)) # shape: (n_roi, 2*4, roi_size, roi_size) roi_ag_loc_scores = ps_roi_average_pooling_2d( h_ag_loc, rois, roi_indices, (2 * 4, self.roi_size, self.roi_size), self.spatial_scale, self.group_size) # shape: (n_roi, n_class) roi_cls_scores = F.average( F.max(roi_cls_ag_seg_scores, axis=2), axis=(2, 3)) # Bbox Regression # shape: (n_roi, 2, 4) roi_ag_locs = F.average(roi_ag_loc_scores, axis=(2, 3)) roi_ag_locs = F.reshape(roi_ag_locs, (-1, 2, 4)) # Mask Regression # shape: (n_roi, n_class, 2, roi_size, roi_size) if gt_roi_labels is None: max_cls_indices = roi_cls_scores.array.argmax(axis=1) else: max_cls_indices = gt_roi_labels # shape: (n_roi, 2, roi_size, roi_size) roi_ag_seg_scores = roi_cls_ag_seg_scores[ self.xp.arange(len(max_cls_indices)), max_cls_indices] return roi_ag_seg_scores, roi_ag_locs, roi_cls_scores
{ "content_hash": "baca248824dce6c4407366d6601d6bee", "timestamp": "", "source": "github", "line_count": 402, "max_line_length": 79, "avg_line_length": 40.12686567164179, "alnum_prop": 0.5919657801748187, "repo_name": "yuyu2172/chainercv", "id": "cf7a7883e322f9caabadbbc069030b9f76ddf6c6", "size": "16131", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "chainercv/experimental/links/model/fcis/fcis_resnet101.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3080" }, { "name": "Python", "bytes": "1201052" }, { "name": "Shell", "bytes": "10815" } ], "symlink_target": "" }
""" WSGI config for base springstertestapp. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "springstertestapp.settings.production") application = get_wsgi_application()
{ "content_hash": "c5d93202fcff00af3bfe2782b2abb101", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 78, "avg_line_length": 26.4375, "alnum_prop": 0.7754137115839244, "repo_name": "Mitso/springstertestapp", "id": "35abbc9807444c082d44d9b78480a4e0adfbdba1", "size": "423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "springstertestapp/wsgi.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "128710" }, { "name": "HTML", "bytes": "138391" }, { "name": "JavaScript", "bytes": "9716" }, { "name": "Python", "bytes": "183268" }, { "name": "Shell", "bytes": "563" } ], "symlink_target": "" }
"""Python sample demonstrating use of the Google Genomics Pipelines API. This sample demonstrates a pipeline that uses Bioconductor to analyze files in Google Cloud Storage. This pipeline is run in an "ephemeral" manner; no call to pipelines.create() is necessary. No pipeline is persisted in the pipelines list. """ import pprint import time from oauth2client.client import GoogleCredentials from apiclient.discovery import build PROJECT_ID='**FILL IN PROJECT ID**' BUCKET='**FILL IN BUCKET**' # Output will be written underneath gs://<BUCKET>/<PREFIX>/ PREFIX='pipelines-api-examples/bioconductor' # Update this path if you uploaded the script elsewhere in Cloud Storage. SCRIPT='gs://%s/%s/script.R' % (BUCKET, PREFIX) # This script will poll for completion of the pipeline. POLL_INTERVAL_SECONDS = 20 # Create the genomics service. credentials = GoogleCredentials.get_application_default() service = build('genomics', 'v1alpha2', credentials=credentials) # Run the pipeline. operation = service.pipelines().run(body={ # The ephemeralPipeline provides the template for the pipeline. # The pipelineArgs provide the inputs specific to this run. 'ephemeralPipeline' : { 'projectId': PROJECT_ID, 'name': 'Bioconductor: count overlaps in a BAM', 'description': 'This sample demonstrates a subset of the vignette https://bioconductor.org/packages/release/bioc/vignettes/BiocParallel/inst/doc/Introduction_To_BiocParallel.pdf.', # Define the resources needed for this pipeline. 'resources' : { # Specify default VM parameters for the pipeline. 'minimumCpuCores': 1, # TODO: remove this when the API has a default. 'minimumRamGb': 3.75, # TODO: remove this when the API has a default. # Create a data disk that is attached to the VM and destroyed when the # pipeline terminates. 'disks': [ { 'name': 'data', 'autoDelete': True, # Within the docker container, specify a mount point for the disk. # The pipeline input argument below will specify that inputs should be # written to this disk. 'mountPoint': '/mnt/data', # Specify a default size and type. 'sizeGb': 100, # TODO: remove this when the API has a default 'type': 'PERSISTENT_HDD', # TODO: remove this when the API has a default } ], }, # Specify the docker image to use along with the command. See # http://www.bioconductor.org/help/docker/ for more detail. 'docker' : { 'imageName': 'bioconductor/release_core', # Change into the directory in which the script and input reside. Then # run the R script in batch mode to completion. 'cmd': '/bin/bash -c "cd /mnt/data/ ; R CMD BATCH script.R"', }, 'inputParameters' : [ { 'name': 'script', 'description': 'Cloud Storage path to the R script to run.', 'localCopy': { 'path': 'script.R', 'disk': 'data' } }, { 'name': 'bamFile', 'description': 'Cloud Storage path to the BAM file.', 'localCopy': { 'path': 'input.bam', 'disk': 'data' } }, { 'name': 'indexFile', 'description': 'Cloud Storage path to the BAM index file.', 'localCopy': { 'path': 'input.bam.bai', 'disk': 'data' } } ], 'outputParameters' : [ { 'name': 'outputFile', 'description': 'Cloud Storage path for where to write the result.', 'localCopy': { 'path': 'overlapsCount.tsv', 'disk': 'data' } }, { 'name': 'rBatchLogFile', 'description': 'Cloud Storage path for where to write the R batch log file.', 'localCopy': { 'path': 'script.Rout', 'disk': 'data' } } ] }, 'pipelineArgs' : { 'projectId': PROJECT_ID, # Here we use a very tiny BAM as an example but this pipeline could be invoked in # a loop to kick off parallel execution of this pipeline on, for example, all the # 1000 Genomes phase 3 BAMs in # gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/phase3/data/*/alignment/*.mapped.ILLUMINA.bwa.*.low_coverage.20120522.bam' # emitting a distinct output file for each result. Then you can: # gsutil cat gs://<BUCKET>/<PREFIX>/output/*tsv > allOverlapsCount.tsv # to create the final consolidated TSV file. 'inputs': { 'script': SCRIPT, 'bamFile': 'gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/technical/pilot3_exon_targetted_GRCh37_bams/data/NA06986/alignment/NA06986.chromMT.ILLUMINA.bwa.CEU.exon_targetted.20100311.bam', 'indexFile': 'gs://genomics-public-data/ftp-trace.ncbi.nih.gov/1000genomes/ftp/technical/pilot3_exon_targetted_GRCh37_bams/data/NA06986/alignment/NA06986.chromMT.ILLUMINA.bwa.CEU.exon_targetted.20100311.bam.bai' }, # Pass the user-specified Cloud Storage destination for pipeline output. 'outputs': { # The R script explicitly writes out one file of results. 'outputFile': 'gs://%s/%s/output/overlapsCount.tsv' % (BUCKET, PREFIX), # R, when run in batch mode, writes console output to a file. 'rBatchLogFile': 'gs://%s/%s/output/script.Rout' % (BUCKET, PREFIX) }, # Pass the user-specified Cloud Storage destination for pipeline logging. 'logging': { 'gcsPath': 'gs://%s/%s/logging' % (BUCKET, PREFIX) }, # TODO: remove this when the API has a default 'serviceAccount': { 'email': 'default', 'scopes': [ 'https://www.googleapis.com/auth/compute', 'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/genomics' ] } } }).execute() # Emit the result of the pipeline run submission and poll for completion. pp = pprint.PrettyPrinter(indent=2) pp.pprint(operation) operation_name = operation['name'] print print "Polling for completion of operation" while not operation['done']: print "Operation not complete. Sleeping %d seconds" % (POLL_INTERVAL_SECONDS) time.sleep(POLL_INTERVAL_SECONDS) operation = service.operations().get(name=operation_name).execute() print print "Operation complete" print pp.pprint(operation)
{ "content_hash": "98044e4160a784ed0a90b334c2e668bc", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 217, "avg_line_length": 37.101190476190474, "alnum_prop": 0.6613187871009145, "repo_name": "mbookman/pipelines-api-examples", "id": "40f3f7d2d55e9b0433f41f20c23e2baf14e8b12f", "size": "6849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bioconductor/run_bioconductor.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "62065" }, { "name": "R", "bytes": "1753" }, { "name": "Shell", "bytes": "35774" } ], "symlink_target": "" }
from absl import app, flags from easydict import EasyDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from datasets import MNISTDataset from cleverhans.torch.attacks.fast_gradient_method import fast_gradient_method from cleverhans.torch.attacks.projected_gradient_descent import ( projected_gradient_descent, ) FLAGS = flags.FLAGS class CNN(torch.nn.Module): """Basic CNN architecture.""" def __init__(self, in_channels=1): super(CNN, self).__init__() self.conv1 = nn.Conv2d( in_channels, 64, 8, 1 ) # (batch_size, 3, 28, 28) --> (batch_size, 64, 21, 21) self.conv2 = nn.Conv2d( 64, 128, 6, 2 ) # (batch_size, 64, 21, 21) --> (batch_size, 128, 8, 8) self.conv3 = nn.Conv2d( 128, 128, 5, 1 ) # (batch_size, 128, 8, 8) --> (batch_size, 128, 4, 4) self.fc1 = nn.Linear( 128 * 4 * 4, 128 ) # (batch_size, 128, 4, 4) --> (batch_size, 2048) self.fc2 = nn.Linear(128, 10) # (batch_size, 128) --> (batch_size, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = x.view(-1, 128 * 4 * 4) x = self.fc1(x) x = self.fc2(x) return x class PyNet(nn.Module): """CNN architecture. This is the same MNIST model from pytorch/examples/mnist repository""" def __init__(self, in_channels=1): super(PyNet, self).__init__() self.conv1 = nn.Conv2d(in_channels, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) output = F.log_softmax(x, dim=1) return output def ld_mnist(): """Load training and test data.""" train_transforms = torchvision.transforms.Compose( [torchvision.transforms.ToTensor()] ) test_transforms = torchvision.transforms.Compose( [torchvision.transforms.ToTensor()] ) # Load MNIST dataset train_dataset = MNISTDataset(root="/tmp/data", transform=train_transforms) test_dataset = MNISTDataset( root="/tmp/data", train=False, transform=test_transforms ) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=128, shuffle=True, num_workers=2 ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=128, shuffle=False, num_workers=2 ) return EasyDict(train=train_loader, test=test_loader) def main(_): # Load training and test data data = ld_mnist() # Instantiate model, loss, and optimizer for training if FLAGS.model == "cnn": net = CNN(in_channels=1) elif FLAGS.model == "pynet": net = PyNet(in_channels=1) else: raise NotImplementedError device = "cuda" if torch.cuda.is_available() else "cpu" if device == "cuda": net = net.cuda() loss_fn = torch.nn.CrossEntropyLoss(reduction="mean") optimizer = torch.optim.Adam(net.parameters(), lr=1e-3) # Train vanilla model net.train() for epoch in range(1, FLAGS.nb_epochs + 1): train_loss = 0.0 for x, y in data.train: x, y = x.to(device), y.to(device) if FLAGS.adv_train: # Replace clean example with adversarial example for adversarial training x = projected_gradient_descent(net, x, FLAGS.eps, 0.01, 40, np.inf) optimizer.zero_grad() loss = loss_fn(net(x), y) loss.backward() optimizer.step() train_loss += loss.item() print( "epoch: {}/{}, train loss: {:.3f}".format( epoch, FLAGS.nb_epochs, train_loss ) ) # Evaluate on clean and adversarial data net.eval() report = EasyDict(nb_test=0, correct=0, correct_fgm=0, correct_pgd=0) for x, y in data.test: x, y = x.to(device), y.to(device) x_fgm = fast_gradient_method(net, x, FLAGS.eps, np.inf) x_pgd = projected_gradient_descent(net, x, FLAGS.eps, 0.01, 40, np.inf) _, y_pred = net(x).max(1) # model prediction on clean examples _, y_pred_fgm = net(x_fgm).max( 1 ) # model prediction on FGM adversarial examples _, y_pred_pgd = net(x_pgd).max( 1 ) # model prediction on PGD adversarial examples report.nb_test += y.size(0) report.correct += y_pred.eq(y).sum().item() report.correct_fgm += y_pred_fgm.eq(y).sum().item() report.correct_pgd += y_pred_pgd.eq(y).sum().item() print( "test acc on clean examples (%): {:.3f}".format( report.correct / report.nb_test * 100.0 ) ) print( "test acc on FGM adversarial examples (%): {:.3f}".format( report.correct_fgm / report.nb_test * 100.0 ) ) print( "test acc on PGD adversarial examples (%): {:.3f}".format( report.correct_pgd / report.nb_test * 100.0 ) ) if __name__ == "__main__": flags.DEFINE_integer("nb_epochs", 8, "Number of epochs.") flags.DEFINE_float("eps", 0.3, "Total epsilon for FGM and PGD attacks.") flags.DEFINE_bool( "adv_train", False, "Use adversarial training (on PGD adversarial examples)." ) flags.DEFINE_enum("model", "cnn", ["cnn", "pynet"], "Choose model type.") app.run(main)
{ "content_hash": "c85b400ba9af69f7d8fc42784b8546f7", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 95, "avg_line_length": 32.26373626373626, "alnum_prop": 0.5696525885558583, "repo_name": "cleverhans-lab/cleverhans", "id": "559b5a4aec27eb9f8c67c8e25549e7e2c3d6bfec", "size": "5872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tutorials/torch/mnist_tutorial.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "242" }, { "name": "HTML", "bytes": "64" }, { "name": "Makefile", "bytes": "836" }, { "name": "Python", "bytes": "1016809" }, { "name": "Shell", "bytes": "2831" } ], "symlink_target": "" }
''' Created on 17.09.2014 Utility classes for datapoints and converters to ROOT graphics objects @author: markusfasel ''' from ROOT import TGraph, TGraphAsymmErrors import math class Datapoint: """ Representation of data for a single point """ def __init__(self, x, y, dx): """ Constructor """ self.__x = x self.__y = y self.__dx = dx self.__upperErrors = {} self.__lowerErrors = {} def AddErrorSource(self, name, lower, upper): """ Add error to the datapoint """ self.__upperErrors[name] = upper self.__lowerErrors[name] = lower def GetX(self): """ Access to x-value of the data point """ return self.__x def GetY(self): """ Access to y-value of the data point """ return self.__y def GetLowerErrorForSource(self, name): """ Access to lower error for a given error source """ if name == "total": return self.GetTotalLowerError() if not name in self.__lowerErrors.keys(): return 0 return self.__lowerErrors[name] def GetUpperErrorForSource(self, name): """ Access to upper error for a given error source """ if name == "total": return self.GetTotalUpperError() if not name in self.__upperErrors.keys(): return 0 return self.__upperErrors[name] def GetUpperLimitForSource(self, source): """ Access to upper limit under a given error source """ return self.__y + self.GetUpperErrorForSource(source) def GetLowerLimitForSource(self, source): """ Access to lower limit under a given error source """ return self.__y - self.GetLowerErrorForSource(source) def GetRelativeLowerError(self, source): return self.GetLowerErrorForSource(source)/self.__y def GetRelativeUpperError(self, source): return self.GetUpperErrorForSource(source)/self.__y def GetDX(self): """ Access to uncertainty in x direction """ return self.__dx def GetTotalLowerError(self): """ calculate total error as quadratic sum of the single components """ sumofsquares = 0 for error in self.__lowerErrors.values(): sumofsquares += math.pow(error, 2) return math.sqrt(sumofsquares) def GetTotalUpperError(self): """ calculate total error as quadratic sum of the single components """ sumofsquares = 0 for error in self.__lowerErrors.values(): sumofsquares += math.pow(error, 2) return math.sqrt(sumofsquares) def __eq__(self, other): return self.__x == other.__x def __lt__(self, other): return self.__x < other.__x def __le__(self, other): return self.__x <= other.__x def __gt__(self, other): return self.__x > other.__x def __ge__(self, other): return self.__x >= other.__x def __ne__(self, other): return self.__x != other.x def __str__(self): """ Create string representation of the point """ result = "%f +- %f GeV/c: %e" %(self.__x, self.__dx, self.__y) for source in self.__lowerErrors.keys(): result += " + %e - %e (%s)" %(self.__upperErrors[source], self.__lowerErrors[source], source) if len(self.__lowerErrors): result += " [+ %e -%e (total)]" %(self.GetTotalUpperError(), self.GetTotalLowerError()) return result def Print(self): """ Print point representation """ print str(self) class DataCollection: """ Collection of data points """ def __init__(self, name): ''' Constructor ''' self.__name = name self._pointlist = [] def AddDataPoint(self, point): self._pointlist.append(point) def AddDataXY(self, x, y): self._pointlist.append(Datapoint(x, y, 0.)) def AddDataWithErrors(self, x, y, dx, dy): point = Datapoint(x,y,dx), point.AddErrorSource("error", dy, dy) self._pointlist.append(point) def GetPointList(self): return self._pointlist def MakeErrorGraphForSource(self, source): result = TGraphAsymmErrors() counter = 0 for point in sorted(self._pointlist): result.SetPoint(counter, point.GetX(), point.GetY()) result.SetPointError(counter, point.GetDX(), point.GetDX(), point.GetLowerErrorForSource(source), point.GetUpperErrorForSource(source)) counter += 1 return result def MakeLimitCurve(self, source, direction): result = TGraph() counter = 0 for point in self._pointlist: error = 0 if direction == "upper": error = point.GetUpperErrorForSource(source) elif direction == "lower": error = -1. * point.GetLowerErrorForSource(source) elif direction == "cental": error = 0 result.SetPoint(counter, point.GetX(), point.GetY() + error) counter += 1 return result def Print(self): print "Data collection :s" %(self.__name) print "=====================================================================" for point in sorted(self._pointlist): point.Print()
{ "content_hash": "0d7951f502098eb06fc8c0403e42b814", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 147, "avg_line_length": 29.132653061224488, "alnum_prop": 0.5353765323992995, "repo_name": "matplo/rootutils", "id": "6f29fee1b13c655905164d7b2ae2c6d18e353b04", "size": "5710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/2.7/DataCollection.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "554757" }, { "name": "Roff", "bytes": "1130" }, { "name": "Shell", "bytes": "4927" } ], "symlink_target": "" }
""" Simple utility for setting configuration values from the command line. Sample usage: $ setconfig FOO_SUPPORT=y BAR_BITS=8 Note: Symbol names should not be prefixed with 'CONFIG_'. The exit status on errors is 1. The default input/output configuration file is '.config'. A different filename can be passed in the KCONFIG_CONFIG environment variable. When overwriting a configuration file, the old version is saved to <filename>.old (e.g. .config.old). """ import argparse import sys import kconfiglib def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument( "--kconfig", default="Kconfig", help="Top-level Kconfig file (default: Kconfig)") parser.add_argument( "--no-check-exists", dest="check_exists", action="store_false", help="Ignore assignments to non-existent symbols instead of erroring " "out") parser.add_argument( "--no-check-value", dest="check_value", action="store_false", help="Ignore assignments that didn't \"take\" (where the symbol got a " "different value, e.g. due to unsatisfied dependencies) instead " "of erroring out") parser.add_argument( "assignments", metavar="ASSIGNMENT", nargs="*", help="A 'NAME=value' assignment") args = parser.parse_args() kconf = kconfiglib.Kconfig(args.kconfig, suppress_traceback=True) print(kconf.load_config()) for arg in args.assignments: if "=" not in arg: sys.exit("error: no '=' in assignment: '{}'".format(arg)) name, value = arg.split("=", 1) if name not in kconf.syms: if not args.check_exists: continue sys.exit("error: no symbol '{}' in configuration".format(name)) sym = kconf.syms[name] if not sym.set_value(value): sys.exit("error: '{}' is an invalid value for the {} symbol {}" .format(value, kconfiglib.TYPE_TO_STR[sym.orig_type], name)) if args.check_value and sym.str_value != value: sys.exit("error: {} was assigned the value '{}', but got the " "value '{}'. Check the symbol's dependencies, and make " "sure that it has a prompt." .format(name, value, sym.str_value)) print(kconf.write_config()) if __name__ == "__main__": main()
{ "content_hash": "e96eb57d7f1088d548b4d706e6d8d867", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 79, "avg_line_length": 29.563218390804597, "alnum_prop": 0.5940902021772939, "repo_name": "gem5/gem5", "id": "f9cf5cd314da242b5d8827065fa40601a89b581c", "size": "2664", "binary": false, "copies": "4", "ref": "refs/heads/stable", "path": "ext/Kconfiglib/setconfig.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "145626" }, { "name": "Awk", "bytes": "3386" }, { "name": "BASIC", "bytes": "2884" }, { "name": "C", "bytes": "3927153" }, { "name": "C++", "bytes": "42960484" }, { "name": "CMake", "bytes": "133888" }, { "name": "Dockerfile", "bytes": "34102" }, { "name": "Emacs Lisp", "bytes": "1914" }, { "name": "Forth", "bytes": "354" }, { "name": "Fortran", "bytes": "15436" }, { "name": "HTML", "bytes": "146414" }, { "name": "Hack", "bytes": "139769" }, { "name": "Java", "bytes": "6966" }, { "name": "M4", "bytes": "42624" }, { "name": "Makefile", "bytes": "39573" }, { "name": "Perl", "bytes": "23784" }, { "name": "Python", "bytes": "8079781" }, { "name": "Roff", "bytes": "8754" }, { "name": "SCSS", "bytes": "2971" }, { "name": "SWIG", "bytes": "173" }, { "name": "Scala", "bytes": "5328" }, { "name": "Shell", "bytes": "95638" }, { "name": "Starlark", "bytes": "25668" }, { "name": "SuperCollider", "bytes": "8869" }, { "name": "Vim Script", "bytes": "4343" }, { "name": "sed", "bytes": "3897" } ], "symlink_target": "" }
import jinja2 import jingo from tower import ugettext as _ from access import acl from reviews.models import ReviewFlag from . import forms @jingo.register.filter def stars(num, large=False): # check for 0.0 incase None was cast to a float. Should # be safe since lowest rating you can give is 1.0 if num is None or num == 0.0: return _('Not yet rated') else: num = min(5, int(round(num))) t = jingo.env.get_template('reviews/impala/reviews_rating.html') # These are getting renamed for contextual sense in the template. return jinja2.Markup(t.render({'rating': num, 'detailpage': large})) @jingo.register.function def reviews_link(addon, collection_uuid=None, link_to_list=False): t = jingo.env.get_template('reviews/reviews_link.html') return jinja2.Markup(t.render({'addon': addon, 'link_to_list': link_to_list, 'collection_uuid': collection_uuid})) @jingo.register.function def impala_reviews_link(addon, collection_uuid=None, link_to_list=False): t = jingo.env.get_template('reviews/impala/reviews_link.html') return jinja2.Markup(t.render({'addon': addon, 'link_to_list': link_to_list, 'collection_uuid': collection_uuid})) @jingo.register.inclusion_tag('reviews/mobile/reviews_link.html') @jinja2.contextfunction def mobile_reviews_link(context, addon): c = dict(context.items()) c.update(addon=addon) return c @jingo.register.inclusion_tag('reviews/report_review.html') @jinja2.contextfunction def report_review_popup(context): c = dict(context.items()) c.update(ReviewFlag=ReviewFlag, flag_form=forms.ReviewFlagForm()) return c @jingo.register.inclusion_tag('reviews/edit_review.html') @jinja2.contextfunction def edit_review_form(context): c = dict(context.items()) c.update(form=forms.ReviewForm()) return c @jingo.register.inclusion_tag('reviews/edit_review.html') @jinja2.contextfunction def edit_review_reply_form(context): c = dict(context.items()) c.update(form=forms.ReviewReplyForm()) return c def user_can_delete_review(request, review): """Return whether or not the request.user can delete reviews. People who can delete reviews: * The original review author. * Editors, but only if they aren't listed as an author of the add-on. * Users in a group with "Users:Edit" privileges. * Users in a group with "Addons:Edit" privileges. Persona editors can't delete addons reviews. """ is_author = review.addon.has_author(request.user) return ( review.user_id == request.user.id or not is_author and ( acl.is_editor(request, review.addon) or acl.action_allowed(request, 'Users', 'Edit') or acl.action_allowed(request, 'Addons', 'Edit'))) @jingo.register.function @jinja2.contextfunction def check_review_delete(context, review): return user_can_delete_review(context['request'], review)
{ "content_hash": "4900b60ae838c76a1ed902413edca310", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 76, "avg_line_length": 32.145833333333336, "alnum_prop": 0.6672067401166558, "repo_name": "Witia1/olympia", "id": "cbe4866714d7786dd2846dacdbb2a36f98cddea1", "size": "3086", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "apps/reviews/helpers.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "249" }, { "name": "C", "bytes": "4145" }, { "name": "CSS", "bytes": "656811" }, { "name": "HTML", "bytes": "1635245" }, { "name": "JavaScript", "bytes": "1287516" }, { "name": "Makefile", "bytes": "4009" }, { "name": "PLSQL", "bytes": "74" }, { "name": "Python", "bytes": "3947149" }, { "name": "Shell", "bytes": "10335" }, { "name": "Smarty", "bytes": "2229" } ], "symlink_target": "" }
from . import rman_ui_base from . import rman_ui_txmanager from . import rman_ui_aovs from . import rman_ui_viewport from . import rman_ui_light_handlers from . import rman_ui_render_panels from . import rman_ui_object_panels from . import rman_ui_mesh_panels from . import rman_ui_curve_panels from . import rman_ui_material_panels from . import rman_ui_scene_panels from . import rman_ui_world_panels from . import rman_ui_camera_panels from . import rman_ui_particles_panels from . import rman_ui_header_panels from . import rman_ui_view3d_panels from . import rman_ui_blender_panels from . import rman_ui_view3d_menus from . import rman_ui_texteditor from . import rman_ui_output_panels from . import rman_ui_node_category_menus def register(): rman_ui_base.register() rman_ui_txmanager.register() rman_ui_aovs.register() rman_ui_viewport.register() rman_ui_light_handlers.register() rman_ui_render_panels.register() rman_ui_object_panels.register() rman_ui_mesh_panels.register() rman_ui_curve_panels.register() rman_ui_material_panels.register() rman_ui_scene_panels.register() rman_ui_world_panels.register() rman_ui_camera_panels.register() rman_ui_particles_panels.register() rman_ui_header_panels.register() rman_ui_view3d_panels.register() rman_ui_blender_panels.register() rman_ui_view3d_menus.register() rman_ui_texteditor.register() rman_ui_output_panels.register() rman_ui_node_category_menus.register() def unregister(): rman_ui_base.unregister() rman_ui_txmanager.unregister() rman_ui_aovs.unregister() rman_ui_viewport.unregister() rman_ui_light_handlers.unregister() rman_ui_render_panels.unregister() rman_ui_object_panels.unregister() rman_ui_mesh_panels.unregister() rman_ui_curve_panels.unregister() rman_ui_material_panels.unregister() rman_ui_scene_panels.unregister() rman_ui_world_panels.unregister() rman_ui_camera_panels.unregister() rman_ui_particles_panels.unregister() rman_ui_header_panels.unregister() rman_ui_view3d_panels.unregister() rman_ui_blender_panels.unregister() rman_ui_view3d_menus.unregister() rman_ui_texteditor.unregister() rman_ui_output_panels.unregister() rman_ui_node_category_menus.unregister()
{ "content_hash": "fa87b0f4bd0b640282dc51f60afbd34a", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 44, "avg_line_length": 34.59701492537314, "alnum_prop": 0.7286453839516824, "repo_name": "adminradio/RenderManForBlender", "id": "717517138a7e49812824b9be1f33c06273183c8a", "size": "2318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rman_ui/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "1055354" } ], "symlink_target": "" }
from __future__ import with_statement import os import sys from trac.env import open_environment from trac.ticket.model import Priority, Severity priority_mapping = { 'highest': 'blocker', 'high': 'critical', 'normal': 'major', 'low': 'minor', 'lowest': 'trivial' } def main(): if len(sys.argv) < 2: print >> sys.stderr, 'usage: %s /path/to/projenv' \ % os.path.basename(sys.argv[0]) sys.exit(2) env = open_environment(sys.argv[1]) with env.db_transaction: for oldprio, newprio in priority_mapping.items(): priority = Priority(env, oldprio) priority.name = newprio priority.update() for severity in list(Severity.select(env)): severity.delete() if __name__ == '__main__': main()
{ "content_hash": "8c1dd6a7b61a42c764775eb22720c301", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 60, "avg_line_length": 24.852941176470587, "alnum_prop": 0.5692307692307692, "repo_name": "dinhkhanh/trac", "id": "bf4a099d08717bb40e7a785a865cf16886767eb1", "size": "1269", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "contrib/migrateticketmodel.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "79829" }, { "name": "Python", "bytes": "2814020" } ], "symlink_target": "" }
""" .. module:: dj-stripe.tests.test_contrib.test_views :synopsis: dj-stripe Rest views for Subscription Tests. .. moduleauthor:: Philippe Luickx (@philippeluickx) """ from __future__ import unicode_literals from decimal import Decimal from django.utils import timezone from django.conf import settings from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from mock import patch, PropertyMock from rest_framework import status from rest_framework.test import APITestCase from djstripe.models import CurrentSubscription, Customer from djstripe import settings as djstripe_settings if settings.STRIPE_PUBLIC_KEY and settings.STRIPE_SECRET_KEY: import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class RestSubscriptionTest(APITestCase): """ Test the REST api for subscriptions. """ def setUp(self): self.url = reverse("rest_djstripe:subscription") self.user = get_user_model().objects.create_user( username="testuser", email="test@example.com", password="123" ) self.assertTrue(self.client.login(username="testuser", password="123")) @patch("djstripe.models.Customer.subscribe", autospec=True) @patch("djstripe.models.Customer.update_card", autospec=True) @patch("stripe.Customer.create", return_value=PropertyMock(id="cus_xxx1234567890")) def test_create_subscription(self, stripe_customer_mock, update_card_mock, subscribe_mock): self.assertEqual(0, Customer.objects.count()) data = { "plan": "test0", "stripe_token": "cake", } response = self.client.post(self.url, data) self.assertEqual(1, Customer.objects.count()) update_card_mock.assert_called_once_with(self.user.customer, "cake") subscribe_mock.assert_called_once_with(self.user.customer, "test0") self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data, data) @patch("djstripe.models.Customer.subscribe", autospec=True) @patch("djstripe.models.Customer.update_card", autospec=True) @patch("stripe.Customer.create", return_value=PropertyMock(id="cus_xxx1234567890")) def test_create_subscription_exception(self, stripe_customer_mock, update_card_mock, subscribe_mock): e = Exception subscribe_mock.side_effect = e data = { "plan": "test0", "stripe_token": "cake", } response = self.client.post(self.url, data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_get_no_content_for_subscription(self): response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) def test_get_subscription(self): fake_customer = Customer.objects.create( stripe_id="cus_xxx1234567890", subscriber=self.user ) CurrentSubscription.objects.create( customer=fake_customer, plan="test", quantity=1, start=timezone.now(), amount=Decimal(25.00), status="active", ) response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["plan"], "test") self.assertEqual(response.data['status'], 'active') self.assertEqual(response.data['cancel_at_period_end'], False) @patch("djstripe.models.Customer.cancel_subscription", return_value=CurrentSubscription(status=CurrentSubscription.STATUS_ACTIVE)) @patch("djstripe.models.Customer.current_subscription", new_callable=PropertyMock, return_value=CurrentSubscription(plan="test", amount=Decimal(25.00), status="active")) @patch("djstripe.models.Customer.subscribe", autospec=True) def test_cancel_subscription(self, subscribe_mock, stripe_create_customer_mock, cancel_subscription_mock): fake_customer = Customer.objects.create( stripe_id="cus_xxx1234567890", subscriber=self.user ) CurrentSubscription.objects.create( customer=fake_customer, plan="test", quantity=1, start=timezone.now(), amount=Decimal(25.00), status="active", ) self.assertEqual(1, CurrentSubscription.objects.count()) response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # Cancelled means flagged as cancelled, so it should still be there self.assertEqual(1, CurrentSubscription.objects.count()) cancel_subscription_mock.assert_called_once_with( at_period_end=djstripe_settings.CANCELLATION_AT_PERIOD_END ) self.assertTrue(self.user.is_authenticated()) def test_cancel_subscription_exception(self): response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_create_subscription_incorrect_data(self): self.assertEqual(0, Customer.objects.count()) data = { "foo": "bar", } response = self.client.post(self.url, data) self.assertEqual(0, Customer.objects.count()) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) class RestSubscriptionNotLoggedInTest(APITestCase): """ Test the exceptions thrown by the subscription rest views. """ def setUp(self): self.url = reverse("rest_djstripe:subscription") def test_create_subscription_not_logged_in(self): self.assertEqual(0, Customer.objects.count()) data = { "plan": "test0", "stripe_token": "cake", } response = self.client.post(self.url, data) self.assertEqual(0, Customer.objects.count()) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
{ "content_hash": "46e7a48fde4f36633e90c3a278627ef7", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 173, "avg_line_length": 38.98701298701299, "alnum_prop": 0.6665556295802798, "repo_name": "cjrh/dj-stripe", "id": "8089f854fc465303a0276fd4d2b169c58a1eecac", "size": "6004", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "tests/test_contrib/test_views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "20378" }, { "name": "Makefile", "bytes": "226" }, { "name": "Python", "bytes": "297617" } ], "symlink_target": "" }
import os import shutil git_path = os.path.join('.git') hooks_path = os.path.join(git_path, 'hooks') commitmsg_hook_path = os.path.join(hooks_path, 'commit-msg') def install(): check_git_path() if not os.path.isdir(hooks_path): os.makedirs(hooks_path, mode=0o755, exist_ok=True) uninstall() commitmsg_script_path = shutil.which('commit-msg') assert commitmsg_script_path os.symlink(commitmsg_script_path, commitmsg_hook_path) assert os.path.exists(commitmsg_hook_path) return commitmsg_hook_path def uninstall(): check_git_path() if os.path.exists(commitmsg_hook_path): os.remove(commitmsg_hook_path) return commitmsg_hook_path def check_git_path(): assert os.path.isdir(git_path)
{ "content_hash": "19866f6e271d2ee023d9a6a973a7953f", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 60, "avg_line_length": 25.233333333333334, "alnum_prop": 0.6869220607661823, "repo_name": "ngouzy/commitmsg", "id": "4dcad0d0e718dd416b7e1494c275931491a02780", "size": "757", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "smartchangelog/githook.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "32069" } ], "symlink_target": "" }
__docformat__='restructuredtext' # Migration number: 011 # Last update - Account migration = [ ("""\ ALTER TABLE accounts ALTER COLUMN user_id SET NOT NULL; ALTER TABLE accounts ALTER COLUMN service_id SET NOT NULL; """, """\ ALTER TABLE accounts ALTER COLUMN service_id DROP NOT NULL; ALTER TABLE accounts ALTER COLUMN user_id DROP NOT NULL; """), ]
{ "content_hash": "67e5695f03a7161184fd285510997bcf", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 67, "avg_line_length": 25.375, "alnum_prop": 0.6330049261083743, "repo_name": "santisiri/popego", "id": "bcf203e14ecb1a5e99ca9b3e1299e9635ff86de6", "size": "429", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "popego/popserver/popserver/db/migration_012.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1246" }, { "name": "C", "bytes": "504141" }, { "name": "C++", "bytes": "26125" }, { "name": "CSS", "bytes": "342653" }, { "name": "FORTRAN", "bytes": "4872" }, { "name": "GAP", "bytes": "13267" }, { "name": "Genshi", "bytes": "407" }, { "name": "Groff", "bytes": "17116" }, { "name": "HTML", "bytes": "383181" }, { "name": "JavaScript", "bytes": "1090769" }, { "name": "Makefile", "bytes": "2441" }, { "name": "Mako", "bytes": "376944" }, { "name": "Python", "bytes": "20895618" }, { "name": "Ruby", "bytes": "3380" }, { "name": "Shell", "bytes": "23581" }, { "name": "Smarty", "bytes": "522" }, { "name": "TeX", "bytes": "35712" } ], "symlink_target": "" }
""" Varnish Plugin for NewRelic """ from xml.etree import ElementTree import helper import logging import subprocess import json import time import requests class NewRelicVarnishPlugin(helper.Controller): """ The NewRelicVarnish plugin polls varnishstat utility for stats and reports to NewRelic """ def __init__(self, args, operating_system): super(NewRelicVarnish, self).__init__(args, operating_system) def setup(self): self.http_headers['X-License-Key'] = self.license_key @property def http_headers(self): return { 'Accept': 'application/json', 'Content-Type': 'application/json'} @property def license_key(self): return self.config.application.license_key def process(self): """ This method is called by super class (helper.Controller) every sleep interval """ logging.info("Process") data = self.fetch() self.send(data) def get_varnish_stats(self): command = subprocess.Popen(['varnishstat', '-1', '-x'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if err is not None: error_msg = 'Failed to fetch varnishstats'.join([err]) logging.error(error_msg); raise Exception(error_msg) return out def parse(self, output): result = [] try: stats = ElementTree.XML(output) expect Exception: raise for stat in stats.iter(tag='stat'): metrics = [] for prop in stat: metrics.append((prop.tag, prop.text)) result.append(dict(metrics)) return result def package_stats(self, stats): components = { 'name': self.app_name, 'guid': self.guid, 'duration': self.duration, 'metrics': stats } body = { 'agent': self.agent_data, 'components': components } return body def fetch(self): try: xml = self.get_varnish_stats() stats = self.parse(xml) except Exception as inst: raise return self.package_stats(stats) def send(self, package): try: response = requests.post(self.endpoint, headers=self.http_headers, proxies=self.proxies, data=json.dumps(package, ensure_ascii=False), timeout=self.config.get('newrelic_api_timeout', 10), verify=self.config.get('verify_ssl_cert', True) except requests.ConnectionError as error: logging.error('Error contacting NewRelic server: %s', error) except requests.Timeout as error: logging.error('Timed out contacting NewRelic server: %s', error) def main(): helper.parser.description('The Varnish Plugin for NewRelic polls varnishstat ' 'for status and sends the data to the NewRelic ' 'Platform') helper.parser.name('newrelic_varnish_plugin') argparse = helper.parser.get() argparse.add_argument('-C', action='store_true', dest='configure', help='Run interactive configuration') args = helper.parser.parse() if args.configure: print('Configuration') sys.exit(0) helper.start(NewRelicVarnishPlugin) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) main()
{ "content_hash": "2224a14c3ba576cea7aff5532a6545f8", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 88, "avg_line_length": 26.103174603174605, "alnum_prop": 0.6245059288537549, "repo_name": "syrgak/newrelic-plugin-varnish", "id": "364282132760c836b948e7f9666f418af282d6eb", "size": "3312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugin.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "3312" }, { "name": "Shell", "bytes": "316" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('disease', '0006_allelecolor'), ] operations = [ migrations.AddField( model_name='allelecolor', name='snp_marker', field=models.ForeignKey(default=-1, to='disease.SNPMarker'), preserve_default=False, ), ]
{ "content_hash": "77b4a9a0d1d2747245131930536a485f", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 72, "avg_line_length": 22.94736842105263, "alnum_prop": 0.5963302752293578, "repo_name": "jiivan/genoomy", "id": "e40311e29489beb504792476f37a3a7dd72e5cce", "size": "460", "binary": false, "copies": "1", "ref": "refs/heads/dev_deploy", "path": "genoome/disease/migrations/0007_allelecolor_snp_marker.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "51082" }, { "name": "HTML", "bytes": "47982" }, { "name": "JavaScript", "bytes": "31061" }, { "name": "Python", "bytes": "138292" }, { "name": "Shell", "bytes": "5962" } ], "symlink_target": "" }
""" I wrote this script to explore the usage and limitations of parameters and expression objects in Pyomo. I thought they were interchangable, but when I converted a parameter to an expression I got an error where it was being used later in an if statement as part of a test for data validity. The punchline is that expressions are not a drop-in replacement for parameters and don't offer any clear and obvious benefits. If I were to use expressions to replace derived parameters and I don't want to keep track of which component is which object, then I should wrap all if statements in value() expressions to force the expressions to resolve. The best use of expressions is probably as a substitute for derived variables. Expressions and derived variables can enable more readable and easier-to-maintain models by replacing repeated portions of equations with a single term. Derived variables increase the size of the optimization problem, and effective preprocessing is required to remove them. Expressions will not increase the size of the optimization problem and will be resolved during compilation. """ from coopr.pyomo import * mod = AbstractModel() mod.set = Set(initialize=[1, 2]) mod.param = Param(mod.set, initialize=lambda m, i: i+10) # This expression should always be greater than param mod.expression = Expression(mod.set, initialize=lambda m, i: m.param[i]+1) # exp_as_param should have a value identical to expression mod.exp_as_param = Param(mod.set, initialize=lambda m, i: m.param[i]+1) # This simple syntax that treats model components as normal variables # works if both components are parameters. m.param[i] > m.exp_as_param[i] try: print "A test treating both components as normal variables works " +\ "if both components are parameters." mod.build_check = BuildCheck( mod.set, rule=lambda m, i: m.param[i] > m.exp_as_param[i]) instance = mod.create() print "The test passed. This wasn't supposed to happen.\n" except ValueError as e: print "The test failed as expected!\n" # This failed check illustrates that expressions cannot be used in the # same way as parameters. Attempting to access them in the same manner # will return an expression object that is not evaluated into a value. try: print "This method doesn't work when one component is an expression." mod.del_component('build_check') mod.build_check = BuildCheck( mod.set, rule=lambda m, i: m.param[i] > m.expression[i]) instance = mod.create() print "The test passed. This wasn't supposed to happen.\n" except ValueError as e: print "The test failed as expected!\n" # Wrapping the overall expression in a value() statement will give the # expected behavior, whether the components are params or expressions. try: print "It will work if you wrap the whole test in a value() function." mod.del_component('build_check') mod.working_check = BuildCheck( mod.set, rule=lambda m, i: value(m.param[i] > m.expression[i])) instance = mod.create() print "The test passed. This wasn't supposed to happen.\n" except ValueError as e: print "The test failed as expected!\n" # If you keep track of which compoenents are expressions, you can wrap # them in a value() function to access their value, but keeping track of # expressions vs parameters could be cumbersomw. An alternative method # of accessing the value is m.expression[i](), but that syntax will # generate an error if you try to use it on a parameter. Calling # m.expression[i].value will return the expression object, which isn't # useful in this sort of mathematical statement, and the .value # attribute is not defined for parameters. try: print "It also works if you wrap one or both components in a value() function." mod.del_component('build_check') mod.working_check3 = BuildCheck( mod.set, rule=lambda m, i: m.param[i] > value(m.expression[i])) # Treating both components the same and wrapping them in value() # functions works but it is too verbose :/ # rule=lambda m, i: value(m.param[i]) > value(m.expression[i])) instance = mod.create() print "The test passed. This wasn't supposed to happen.\n" except ValueError as e: print "The test failed as expected!\n"
{ "content_hash": "da2e203d02a2c75ede918bd95053a0fc", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 83, "avg_line_length": 46.40217391304348, "alnum_prop": 0.7383462169126259, "repo_name": "mseaborn/switch_py", "id": "ccd34ef2eec1e027f075c040fb9e407f7479a22b", "size": "4430", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sandbox_dev/param_v_expression.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "255281" } ], "symlink_target": "" }
import unittest from test_helper import test_is_not_empty, get_file_output class TestCase(unittest.TestCase): def test_not_empty(self): self.assertTrue(test_is_not_empty(), 'The output is empty') def test_output(self): output = get_file_output(path='task.py') answers = [ "WordsAlphabet(alphabet:'a', fruit='apple', country='australia')", "WordsAlphabet(alphabet:'b', fruit='banana', country='brazil')", "WordsAlphabet(alphabet:'c', fruit='cherry', country='canada')" ] for ans in answers: self.assertIn(ans, output, "Incorrect output. Generate WordsAlphabet objects after CoGroupByKey.")
{ "content_hash": "408ddaf07691bdb84934e944bca17eca", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 110, "avg_line_length": 34.55, "alnum_prop": 0.6396526772793053, "repo_name": "apache/beam", "id": "82d22c59ddd1aac330ce9690ea044f96760dd262", "size": "1480", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "learning/katas/python/Core Transforms/CoGroupByKey/CoGroupByKey/tests/test_task.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1598" }, { "name": "C", "bytes": "3869" }, { "name": "CSS", "bytes": "4957" }, { "name": "Cython", "bytes": "70760" }, { "name": "Dart", "bytes": "912687" }, { "name": "Dockerfile", "bytes": "59805" }, { "name": "FreeMarker", "bytes": "7933" }, { "name": "Go", "bytes": "5508697" }, { "name": "Groovy", "bytes": "936956" }, { "name": "HCL", "bytes": "103872" }, { "name": "HTML", "bytes": "184151" }, { "name": "Java", "bytes": "41223435" }, { "name": "JavaScript", "bytes": "119576" }, { "name": "Jupyter Notebook", "bytes": "55818" }, { "name": "Kotlin", "bytes": "220768" }, { "name": "Lua", "bytes": "3620" }, { "name": "Python", "bytes": "10728612" }, { "name": "Rust", "bytes": "5168" }, { "name": "SCSS", "bytes": "318364" }, { "name": "Sass", "bytes": "25954" }, { "name": "Scala", "bytes": "1429" }, { "name": "Shell", "bytes": "375834" }, { "name": "Smarty", "bytes": "2618" }, { "name": "Thrift", "bytes": "3260" }, { "name": "TypeScript", "bytes": "1997829" } ], "symlink_target": "" }
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RecomendadorUD.settings") #os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev') os.environ.setdefault('DJANGO_CONFIGURATION', 'Prod') #from django.core.management import execute_from_command_line from configurations.management import execute_from_command_line execute_from_command_line(sys.argv)
{ "content_hash": "a3652ed702b4b20e43720d345e4dc21d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 78, "avg_line_length": 32.38461538461539, "alnum_prop": 0.7315914489311164, "repo_name": "camilortte/RecomendadorUD", "id": "4214dbee67aabaabaa39cad3a5346d90d0ab6f39", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manage.py", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "741" }, { "name": "CSS", "bytes": "169155" }, { "name": "Go", "bytes": "7075" }, { "name": "HTML", "bytes": "267644" }, { "name": "JavaScript", "bytes": "1055584" }, { "name": "PHP", "bytes": "52919" }, { "name": "Python", "bytes": "400602" }, { "name": "Shell", "bytes": "924" } ], "symlink_target": "" }
from .base import * DEBUG = True
{ "content_hash": "f2711cc2a786a044e4e99fbedd142e40", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 19, "avg_line_length": 8.75, "alnum_prop": 0.6571428571428571, "repo_name": "iAmMrinal0/Taskbuster", "id": "f04354e07ef195bd83520822d50576f9559e032a", "size": "35", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "taskbuster/settings/development.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6989" }, { "name": "CSS", "bytes": "255" }, { "name": "HTML", "bytes": "7046" }, { "name": "JavaScript", "bytes": "1" }, { "name": "Makefile", "bytes": "7425" }, { "name": "Python", "bytes": "22962" } ], "symlink_target": "" }
"""Utilities for determining application-specific dirs. See <https://github.com/ActiveState/appdirs> for details and usage. """ # Dev Notes: # - MSDN on where to store app data files: # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html # - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html __version__ = "1.4.4" __version_info__ = tuple(int(segment) for segment in __version__.split(".")) import os import sys PY3 = sys.version_info[0] == 3 if PY3: unicode = str if sys.platform.startswith("java"): import platform os_name = platform.java_ver()[3][0] if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. system = "win32" elif os_name.startswith("Mac"): # "Mac OS X", etc. system = "darwin" else: # "Linux", "SunOS", "FreeBSD", etc. # Setting this to "linux2" is not ideal, but only Windows or Mac # are actually checked for and the rest of the module expects # *sys.platform* style strings. system = "linux2" else: system = sys.platform def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>". """ if system == "darwin": path = os.path.expanduser("~/Library/Application Support/") if appname: path = os.path.join(path, appname) elif system == "win32": if appauthor is None: appauthor = appname const = "CSIDL_APPDATA" if roaming else "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: path = ( os.path.join(path, appauthor, appname) if appauthor is not False else os.path.join(path, appname) ) else: path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical site data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "darwin": path = os.path.expanduser("/Library/Application Support") if appname: path = os.path.join(path, appname) elif system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: path = ( os.path.join(path, appauthor, appname) if appauthor is not False else os.path.join(path, appname) ) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv( "XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]) ) pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] path = os.pathsep.join(pathlist) if multipath else pathlist[0] return path if appname and version: path = os.path.join(path, version) return path def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user config directories are: Mac OS X: ~/Library/Preferences/<AppName> Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>". """ if system == "win32": path = user_data_dir(appname, appauthor, None, roaming) elif system == "darwin": path = os.path.expanduser("~/Library/Preferences/") if appname: path = os.path.join(path, appname) else: path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set Typical site config directories are: Mac OS X: same as site_data_dir Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "darwin": path = os.path.expanduser("/Library/Preferences") if appname: path = os.path.join(path, appname) elif system == "win32": path = site_data_dir(appname, appauthor) if appname and version: path = os.path.join(path, version) else: # XDG default for $XDG_CONFIG_DIRS # only first, if multipath is False path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") pathlist = [ os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) ] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] path = os.pathsep.join(pathlist) if multipath else pathlist[0] return path def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.expanduser("~/Library/Caches") if appname: path = os.path.join(path, appname) elif system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: path = ( os.path.join(path, appauthor, appname) if appauthor is not False else os.path.join(path, appname) ) if opinion: path = os.path.join(path, "Cache") else: path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user log directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path class AppDirs: """Convenience wrapper for getting application dirs.""" def __init__( self, appname=None, appauthor=None, version=None, roaming=False, multipath=False ): self.appname = appname self.appauthor = appauthor self.version = version self.roaming = roaming self.multipath = multipath @property def user_data_dir(self): return user_data_dir( self.appname, self.appauthor, version=self.version, roaming=self.roaming ) @property def site_data_dir(self): return site_data_dir( self.appname, self.appauthor, version=self.version, multipath=self.multipath ) @property def user_config_dir(self): return user_config_dir( self.appname, self.appauthor, version=self.version, roaming=self.roaming ) @property def site_config_dir(self): return site_config_dir( self.appname, self.appauthor, version=self.version, multipath=self.multipath ) @property def user_cache_dir(self): return user_cache_dir(self.appname, self.appauthor, version=self.version) @property def user_state_dir(self): return user_state_dir(self.appname, self.appauthor, version=self.version) @property def user_log_dir(self): return user_log_dir(self.appname, self.appauthor, version=self.version) # ---- internal support stuff def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir def _get_win_folder_with_ctypes(csidl_name): import ctypes csidl_const = { "CSIDL_APPDATA": 26, "CSIDL_COMMON_APPDATA": 35, "CSIDL_LOCAL_APPDATA": 28, }[csidl_name] buf = ctypes.create_unicode_buffer(1024) ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) has_high_char = any(ord(c) > 255 for c in buf) if has_high_char: buf2 = ctypes.create_unicode_buffer(1024) if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): buf = buf2 return buf.value def _get_win_folder_with_jna(csidl_name): import array from com.sun import jna from com.sun.jna.platform import win32 buf_size = win32.WinDef.MAX_PATH * 2 buf = array.zeros("c", buf_size) shell = win32.Shell32.INSTANCE shell.SHGetFolderPath( None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf, ) dir = jna.Native.toString(buf.tostring()).rstrip("\0") has_high_char = any(ord(c) > 255 for c in dir) if has_high_char: buf = array.zeros("c", buf_size) kernel = win32.Kernel32.INSTANCE if kernel.GetShortPathName(dir, buf, buf_size): dir = jna.Native.toString(buf.tostring()).rstrip("\0") return dir def _get_win_folder_from_environ(csidl_name): env_var_name = { "CSIDL_APPDATA": "APPDATA", "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE", "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA", }[csidl_name] return os.environ[env_var_name] if system == "win32": try: from ctypes import windll except ImportError: try: import com.sun.jna except ImportError: try: if PY3: import winreg as _winreg else: import _winreg except ImportError: _get_win_folder = _get_win_folder_from_environ else: _get_win_folder = _get_win_folder_from_registry else: _get_win_folder = _get_win_folder_with_jna else: _get_win_folder = _get_win_folder_with_ctypes # ---- self test code if __name__ == "__main__": appname = "MyApp" appauthor = "MyCompany" props = ( "user_data_dir", "user_config_dir", "user_cache_dir", "user_state_dir", "user_log_dir", "site_data_dir", "site_config_dir", ) print(f"-- app dirs {__version__} --") print("-- app dirs (with optional 'version')") dirs = AppDirs(appname, appauthor, version="1.0") for prop in props: print(f"{prop}: {getattr(dirs, prop)}") print("\n-- app dirs (without optional 'version')") dirs = AppDirs(appname, appauthor) for prop in props: print(f"{prop}: {getattr(dirs, prop)}") print("\n-- app dirs (without optional 'appauthor')") dirs = AppDirs(appname) for prop in props: print(f"{prop}: {getattr(dirs, prop)}") print("\n-- app dirs (with disabled 'appauthor')") dirs = AppDirs(appname, appauthor=False) for prop in props: print(f"{prop}: {getattr(dirs, prop)}")
{ "content_hash": "9073a2d8688c90b86e174652fa135371", "timestamp": "", "source": "github", "line_count": 606, "max_line_length": 122, "avg_line_length": 39.44884488448845, "alnum_prop": 0.6195934075127583, "repo_name": "timcera/tsgettoolbox", "id": "2edfdd556c17c8e560b8a00a822a20a819311878", "size": "23995", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/tsgettoolbox/appdirs.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "49109" }, { "name": "Python", "bytes": "2676079" }, { "name": "Shell", "bytes": "2740" } ], "symlink_target": "" }
from redash.models import db from redash.devspark.custom_models.favourites import Favourite if __name__ == '__main__': with db.database.transaction(): Favourite.create_table() db.close_db(None)
{ "content_hash": "32773474aa8e54070ee50896f6caba84", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 62, "avg_line_length": 27.375, "alnum_prop": 0.6712328767123288, "repo_name": "jmvasquez/redashtest", "id": "c507f679241cb3a9d726e35cca3863df6dadbe52", "size": "219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "migrations/0014_create_favourites_table.py", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "10567" }, { "name": "HTML", "bytes": "123402" }, { "name": "JavaScript", "bytes": "257609" }, { "name": "Makefile", "bytes": "1009" }, { "name": "Nginx", "bytes": "577" }, { "name": "Python", "bytes": "409970" }, { "name": "Ruby", "bytes": "709" }, { "name": "Shell", "bytes": "41757" } ], "symlink_target": "" }
from . import handlers from firenado import tornadoweb from firenado.launcher import ProcessLauncher import os class LauncherComponent(tornadoweb.TornadoComponent): def __init__(self, name, application): super(LauncherComponent, self).__init__(name, application) self.launcher_path = os.path.abspath(os.path.dirname(__file__)) self.charge_path = os.path.join(self.launcher_path, "charge") self.launcher = None self.launcher_callback = None def get_handlers(self): return [ (r'/', handlers.IndexHandler), ] def initialize(self): import tornado.ioloop self.launcher_callback = tornado.ioloop.IOLoop.current().add_callback( callback=self.launch_charge ) async def launch_charge(self): import sys os.chdir(self.charge_path) self.launcher = ProcessLauncher(dir=self.charge_path, logfile=sys.stderr) self.launcher.load() await self.launcher.launch() os.chdir(self.launcher_path) def shutdown(self): self.launcher.shutdown()
{ "content_hash": "302dd41680686b22e1e97f17eca61e79", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 78, "avg_line_length": 30.945945945945947, "alnum_prop": 0.6279475982532751, "repo_name": "piraz/firenado", "id": "386784e03a3f094d0d332cdb24253012d09df370", "size": "1145", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "examples/launcher/app.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Gherkin", "bytes": "472" }, { "name": "HTML", "bytes": "5244" }, { "name": "Python", "bytes": "226940" }, { "name": "Shell", "bytes": "1289" } ], "symlink_target": "" }
__author__ = 'privat' class FiniteStateMachine: def __init__(self): self.handlers = {} self.start_state = None self.end_states = [] def add_state(self, name, handler=None): """ Add new state to machine. If handler is None state will be set to an end_state :param name: :param handler: """ name = name.upper() if handler: self.handlers[name] = handler else: self.end_states.append(name) def set_start(self, name): """ Set machine start state. :type name: str :param name: Name of initial state. """ self.start_state = name.upper() def run(self, cargo): """ Run finite state machine. This method calls state handlers and enables transitions. It is the core of the machine. :param cargo: Initial payload(function arguments) for start state. :raise RuntimeError: If there are no states or the start state is missing a RuntimeError will be raised. """ try: handler = self.handlers[self.start_state] except: raise RuntimeError('Must call .set_start() before .run() and start_state must have a handler!') if not len(self.end_states): raise RuntimeError('at least one state must be an end_state') while True: new_state, cargo = handler(cargo) if new_state.upper() in self.end_states: print("reached ", new_state) break else: handler = self.handlers[new_state.upper()]
{ "content_hash": "a080efefc323ef8636e2d390253ae81a", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 112, "avg_line_length": 30.054545454545455, "alnum_prop": 0.5601935874168179, "repo_name": "sem23/roslab_ide", "id": "6abe78cc99740026db074cb7b86673aeeba3ca49", "size": "1653", "binary": false, "copies": "1", "ref": "refs/heads/hydro", "path": "src/roslab_ide/fsm.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "196906" } ], "symlink_target": "" }
import os import io import codecs import yaml import jenkins from jenkins_jobs import cmd from jenkins_jobs.errors import JenkinsJobsException from tests.cmd.test_cmd import CmdTestsBase from tests.base import mock os_walk_return_values = { '/jjb_projects': [ ('/jjb_projects', ('dir1', 'dir2', 'dir3'), ()), ('/jjb_projects/dir1', ('bar',), ()), ('/jjb_projects/dir2', ('baz',), ()), ('/jjb_projects/dir3', (), ()), ('/jjb_projects/dir1/bar', (), ()), ('/jjb_projects/dir2/baz', (), ()), ], '/jjb_templates': [ ('/jjb_templates', ('dir1', 'dir2', 'dir3'), ()), ('/jjb_templates/dir1', ('bar',), ()), ('/jjb_templates/dir2', ('baz',), ()), ('/jjb_templates/dir3', (), ()), ('/jjb_templates/dir1/bar', (), ()), ('/jjb_templates/dir2/baz', (), ()), ], '/jjb_macros': [ ('/jjb_macros', ('dir1', 'dir2', 'dir3'), ()), ('/jjb_macros/dir1', ('bar',), ()), ('/jjb_macros/dir2', ('baz',), ()), ('/jjb_macros/dir3', (), ()), ('/jjb_macros/dir1/bar', (), ()), ('/jjb_macros/dir2/baz', (), ()), ], } def os_walk_side_effects(path_name, topdown): return os_walk_return_values[path_name] @mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock) class TestTests(CmdTestsBase): def test_non_existing_config_dir(self): """ Run test mode and pass a non-existing configuration directory """ args = self.parser.parse_args(['test', 'foo']) self.assertRaises(IOError, cmd.execute, args, self.config) def test_non_existing_config_file(self): """ Run test mode and pass a non-existing configuration file """ args = self.parser.parse_args(['test', 'non-existing.yaml']) self.assertRaises(IOError, cmd.execute, args, self.config) def test_non_existing_job(self): """ Run test mode and pass a non-existing job name (probably better to fail here) """ args = self.parser.parse_args(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'invalid']) args.output_dir = mock.MagicMock() cmd.execute(args, self.config) # probably better to fail here def test_valid_job(self): """ Run test mode and pass a valid job name """ args = self.parser.parse_args(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'foo-job']) args.output_dir = mock.MagicMock() cmd.execute(args, self.config) # probably better to fail here @mock.patch('jenkins_jobs.cmd.Builder.update_job') def test_multi_path(self, update_job_mock): """ Run test mode and pass multiple paths. """ path_list = list(os_walk_return_values.keys()) multipath = os.pathsep.join(path_list) args = self.parser.parse_args(['test', multipath]) args.output_dir = mock.MagicMock() cmd.execute(args, self.config) self.assertEqual(args.path, path_list) update_job_mock.assert_called_with(path_list, [], output=args.output_dir) @mock.patch('jenkins_jobs.cmd.Builder.update_job') @mock.patch('jenkins_jobs.cmd.os.path.isdir') @mock.patch('jenkins_jobs.cmd.os.walk') def test_recursive_multi_path(self, os_walk_mock, isdir_mock, update_job_mock): """ Run test mode and pass multiple paths with recursive path option. """ os_walk_mock.side_effect = os_walk_side_effects isdir_mock.return_value = True path_list = os_walk_return_values.keys() paths = [] for path in path_list: paths.extend([p for p, _, _ in os_walk_return_values[path]]) multipath = os.pathsep.join(path_list) args = self.parser.parse_args(['test', '-r', multipath]) args.output_dir = mock.MagicMock() cmd.execute(args, self.config) update_job_mock.assert_called_with(paths, [], output=args.output_dir) args = self.parser.parse_args(['test', multipath]) self.config.set('job_builder', 'recursive', 'True') cmd.execute(args, self.config) update_job_mock.assert_called_with(paths, [], output=args.output_dir) def test_console_output(self): """ Run test mode and verify that resulting XML gets sent to the console. """ console_out = io.BytesIO() with mock.patch('sys.stdout', console_out): cmd.main(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]) xml_content = codecs.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', 'utf-8').read() self.assertEqual(console_out.getvalue().decode('utf-8'), xml_content) def test_config_with_test(self): """ Run test mode and pass a config file """ args = self.parser.parse_args(['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'foo-job']) config = cmd.setup_config_settings(args) self.assertEqual(config.get('jenkins', 'url'), "http://test-jenkins.with.non.default.url:8080/") @mock.patch('jenkins_jobs.builder.YamlParser.generateXML') @mock.patch('jenkins_jobs.builder.ModuleRegistry') def test_plugins_info_stub_option(self, registry_mock, generateXML_mock): """ Test handling of plugins_info stub option. """ plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'plugins-info.yaml') args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')] args = self.parser.parse_args(args) with mock.patch('sys.stdout'): cmd.execute(args, self.config) # probably better to fail here with open(plugins_info_stub_yaml_file, 'r') as yaml_file: plugins_info_list = yaml.load(yaml_file) registry_mock.assert_called_with(self.config, plugins_info_list) @mock.patch('jenkins_jobs.builder.YamlParser.generateXML') @mock.patch('jenkins_jobs.builder.ModuleRegistry') def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock): """ Verify that a JenkinsJobException is raised if the plugins_info stub file does not yield a list as its top-level object. """ plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'bogus-plugins-info.yaml') args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')] args = self.parser.parse_args(args) with mock.patch('sys.stdout'): e = self.assertRaises(JenkinsJobsException, cmd.execute, args, self.config) self.assertIn("must contain a Yaml list", str(e)) class TestJenkinsGetPluginInfoError(CmdTestsBase): """ This test class is used for testing the 'test' subcommand when we want to validate its behavior without mocking jenkins_jobs.builder.Jenkins.get_plugins_info """ @mock.patch('jenkins.Jenkins.get_plugins_info') def test_console_output_jenkins_connection_failure_warning( self, get_plugins_info_mock): """ Run test mode and verify that failed Jenkins connection attempt exception does not bubble out of cmd.main. Ideally, we would also test that an appropriate message is logged to stderr but it's somewhat difficult to figure out how to actually enable stderr in this test suite. """ get_plugins_info_mock.side_effect = \ jenkins.JenkinsException("Connection refused") with mock.patch('sys.stdout'): try: cmd.main(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]) except jenkins.JenkinsException: self.fail("jenkins.JenkinsException propagated to main") except: pass # only care about jenkins.JenkinsException for now
{ "content_hash": "b7aea982be9e5eb85ebfa7deb2b91409", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 78, "avg_line_length": 38.91596638655462, "alnum_prop": 0.537680846469445, "repo_name": "michalvanco/jenkins-job-builder", "id": "c59f5ae73e8609f2ba1a6dd34f9be9c10c82d815", "size": "9262", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/cmd/subcommands/test_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "619" }, { "name": "Python", "bytes": "586287" }, { "name": "Shell", "bytes": "869" } ], "symlink_target": "" }
"""Unit tests for ace model.""" import unittest import os from ace import model from ace.samples import breiman85 from ace.samples import wang04 # pylint: disable=protected-access, missing-docstring class TestModel(unittest.TestCase): def setUp(self): self.model = model.Model() def tearDown(self): pass def test_build_model_from_xy(self): x, y = breiman85.build_sample_ace_problem_breiman85() self.model.build_model_from_xy(x, y) def test_eval_1d(self): x, y = breiman85.build_sample_ace_problem_breiman85() self.model.build_model_from_xy(x, y) val = self.model.eval([0.5]) self.assertGreater(val, 0.0) def test_eval_multiple(self): x, y = wang04.build_sample_ace_problem_wang04() self.model.build_model_from_xy(x, y) val = self.model.eval([0.5, 0.3, 0.2, 0.1, 0.0]) self.assertGreater(val, 0.0) def test_read_column_data_from_txt(self): x, y = breiman85.build_sample_ace_problem_breiman85() self.model.build_model_from_xy(x, y) fname = os.path.join(os.path.dirname(__file__), 'sample_xy_input.txt') self.model.ace.write_input_to_file(fname) model2 = model.Model() model2.build_model_from_txt(fname) val = self.model.eval([0.5]) val2 = model2.eval([0.5]) self.assertAlmostEqual(val, val2, 2) model2.ace.write_transforms_to_file() def test_smaller_dataset(self): x, y = wang04.build_sample_ace_problem_wang04(N=50) self.model.build_model_from_xy(x, y) val = self.model.eval([0.5, 0.3, 0.2, 0.1, 0.0]) self.assertGreater(val, 0.0) if __name__ == "__main__": unittest.main()
{ "content_hash": "e54c95577dd4f7f4aecd9e9579b5e5c3", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 78, "avg_line_length": 29.305084745762713, "alnum_prop": 0.6188548293811452, "repo_name": "partofthething/ace", "id": "541f195a0cb9cfe627162af24e5d342843b6aac6", "size": "1729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ace/tests/test_model.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "55936" } ], "symlink_target": "" }
import argparse import csv import json import math import time import numpy as np import torch import torch.nn.functional as F import torch.optim as optim import torch.utils.data as data from nltk.tokenize.treebank import TreebankWordDetokenizer from torchtext import data as torchtext_data from torchtext import datasets from tqdm import tqdm, trange from pplm_classification_head import ClassificationHead from transformers import GPT2LMHeadModel, GPT2Tokenizer torch.manual_seed(0) np.random.seed(0) EPSILON = 1e-10 example_sentence = "This is incredible! I love it, this is the best chicken I have ever had." max_length_seq = 100 class Discriminator(torch.nn.Module): """Transformer encoder followed by a Classification Head""" def __init__(self, class_size, pretrained_model="gpt2-medium", cached_mode=False, device="cpu"): super().__init__() self.tokenizer = GPT2Tokenizer.from_pretrained(pretrained_model) self.encoder = GPT2LMHeadModel.from_pretrained(pretrained_model) self.embed_size = self.encoder.transformer.config.hidden_size self.classifier_head = ClassificationHead(class_size=class_size, embed_size=self.embed_size) self.cached_mode = cached_mode self.device = device def get_classifier(self): return self.classifier_head def train_custom(self): for param in self.encoder.parameters(): param.requires_grad = False self.classifier_head.train() def avg_representation(self, x): mask = x.ne(0).unsqueeze(2).repeat(1, 1, self.embed_size).float().to(self.device).detach() hidden = self.encoder.transformer(x)["last_hidden_state"] masked_hidden = hidden * mask avg_hidden = torch.sum(masked_hidden, dim=1) / (torch.sum(mask, dim=1).detach() + EPSILON) return avg_hidden def forward(self, x): if self.cached_mode: avg_hidden = x.to(self.device) else: avg_hidden = self.avg_representation(x.to(self.device)) logits = self.classifier_head(avg_hidden) probs = F.log_softmax(logits, dim=-1) return probs class Dataset(data.Dataset): def __init__(self, X, y): """Reads source and target sequences from txt files.""" self.X = X self.y = y def __len__(self): return len(self.X) def __getitem__(self, index): """Returns one data pair (source and target).""" data = {} data["X"] = self.X[index] data["y"] = self.y[index] return data def collate_fn(data): def pad_sequences(sequences): lengths = [len(seq) for seq in sequences] padded_sequences = torch.zeros(len(sequences), max(lengths)).long() # padding value = 0 for i, seq in enumerate(sequences): end = lengths[i] padded_sequences[i, :end] = seq[:end] return padded_sequences, lengths item_info = {} for key in data[0].keys(): item_info[key] = [d[key] for d in data] x_batch, _ = pad_sequences(item_info["X"]) y_batch = torch.tensor(item_info["y"], dtype=torch.long) return x_batch, y_batch def cached_collate_fn(data): item_info = {} for key in data[0].keys(): item_info[key] = [d[key] for d in data] x_batch = torch.cat(item_info["X"], 0) y_batch = torch.tensor(item_info["y"], dtype=torch.long) return x_batch, y_batch def train_epoch(data_loader, discriminator, optimizer, epoch=0, log_interval=10, device="cpu"): samples_so_far = 0 discriminator.train_custom() for batch_idx, (input_t, target_t) in enumerate(data_loader): input_t, target_t = input_t.to(device), target_t.to(device) optimizer.zero_grad() output_t = discriminator(input_t) loss = F.nll_loss(output_t, target_t) loss.backward(retain_graph=True) optimizer.step() samples_so_far += len(input_t) if batch_idx % log_interval == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( epoch + 1, samples_so_far, len(data_loader.dataset), 100 * samples_so_far / len(data_loader.dataset), loss.item(), ) ) def evaluate_performance(data_loader, discriminator, device="cpu"): discriminator.eval() test_loss = 0 correct = 0 with torch.no_grad(): for input_t, target_t in data_loader: input_t, target_t = input_t.to(device), target_t.to(device) output_t = discriminator(input_t) # sum up batch loss test_loss += F.nll_loss(output_t, target_t, reduction="sum").item() # get the index of the max log-probability pred_t = output_t.argmax(dim=1, keepdim=True) correct += pred_t.eq(target_t.view_as(pred_t)).sum().item() test_loss /= len(data_loader.dataset) print( "Performance on test set: " "Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)".format( test_loss, correct, len(data_loader.dataset), 100.0 * correct / len(data_loader.dataset) ) ) def predict(input_sentence, model, classes, cached=False, device="cpu"): input_t = model.tokenizer.encode(input_sentence) input_t = torch.tensor([input_t], dtype=torch.long, device=device) if cached: input_t = model.avg_representation(input_t) log_probs = model(input_t).data.cpu().numpy().flatten().tolist() print("Input sentence:", input_sentence) print( "Predictions:", ", ".join("{}: {:.4f}".format(c, math.exp(log_prob)) for c, log_prob in zip(classes, log_probs)), ) def get_cached_data_loader(dataset, batch_size, discriminator, shuffle=False, device="cpu"): data_loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=batch_size, collate_fn=collate_fn) xs = [] ys = [] for batch_idx, (x, y) in enumerate(tqdm(data_loader, ascii=True)): with torch.no_grad(): x = x.to(device) avg_rep = discriminator.avg_representation(x).cpu().detach() avg_rep_list = torch.unbind(avg_rep.unsqueeze(1)) xs += avg_rep_list ys += y.cpu().numpy().tolist() data_loader = torch.utils.data.DataLoader( dataset=Dataset(xs, ys), batch_size=batch_size, shuffle=shuffle, collate_fn=cached_collate_fn ) return data_loader def train_discriminator( dataset, dataset_fp=None, pretrained_model="gpt2-medium", epochs=10, batch_size=64, log_interval=10, save_model=False, cached=False, no_cuda=False, ): device = "cuda" if torch.cuda.is_available() and not no_cuda else "cpu" print("Preprocessing {} dataset...".format(dataset)) start = time.time() if dataset == "SST": idx2class = ["positive", "negative", "very positive", "very negative", "neutral"] class2idx = {c: i for i, c in enumerate(idx2class)} discriminator = Discriminator( class_size=len(idx2class), pretrained_model=pretrained_model, cached_mode=cached, device=device ).to(device) text = torchtext_data.Field() label = torchtext_data.Field(sequential=False) train_data, val_data, test_data = datasets.SST.splits( text, label, fine_grained=True, train_subtrees=True, ) x = [] y = [] for i in trange(len(train_data), ascii=True): seq = TreebankWordDetokenizer().detokenize(vars(train_data[i])["text"]) seq = discriminator.tokenizer.encode(seq) seq = torch.tensor([50256] + seq, device=device, dtype=torch.long) x.append(seq) y.append(class2idx[vars(train_data[i])["label"]]) train_dataset = Dataset(x, y) test_x = [] test_y = [] for i in trange(len(test_data), ascii=True): seq = TreebankWordDetokenizer().detokenize(vars(test_data[i])["text"]) seq = discriminator.tokenizer.encode(seq) seq = torch.tensor([50256] + seq, device=device, dtype=torch.long) test_x.append(seq) test_y.append(class2idx[vars(test_data[i])["label"]]) test_dataset = Dataset(test_x, test_y) discriminator_meta = { "class_size": len(idx2class), "embed_size": discriminator.embed_size, "pretrained_model": pretrained_model, "class_vocab": class2idx, "default_class": 2, } elif dataset == "clickbait": idx2class = ["non_clickbait", "clickbait"] class2idx = {c: i for i, c in enumerate(idx2class)} discriminator = Discriminator( class_size=len(idx2class), pretrained_model=pretrained_model, cached_mode=cached, device=device ).to(device) with open("datasets/clickbait/clickbait_train_prefix.txt") as f: data = [] for i, line in enumerate(f): try: data.append(eval(line)) except Exception: print("Error evaluating line {}: {}".format(i, line)) continue x = [] y = [] with open("datasets/clickbait/clickbait_train_prefix.txt") as f: for i, line in enumerate(tqdm(f, ascii=True)): try: d = eval(line) seq = discriminator.tokenizer.encode(d["text"]) if len(seq) < max_length_seq: seq = torch.tensor([50256] + seq, device=device, dtype=torch.long) else: print("Line {} is longer than maximum length {}".format(i, max_length_seq)) continue x.append(seq) y.append(d["label"]) except Exception: print("Error evaluating / tokenizing" " line {}, skipping it".format(i)) pass full_dataset = Dataset(x, y) train_size = int(0.9 * len(full_dataset)) test_size = len(full_dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size]) discriminator_meta = { "class_size": len(idx2class), "embed_size": discriminator.embed_size, "pretrained_model": pretrained_model, "class_vocab": class2idx, "default_class": 1, } elif dataset == "toxic": idx2class = ["non_toxic", "toxic"] class2idx = {c: i for i, c in enumerate(idx2class)} discriminator = Discriminator( class_size=len(idx2class), pretrained_model=pretrained_model, cached_mode=cached, device=device ).to(device) x = [] y = [] with open("datasets/toxic/toxic_train.txt") as f: for i, line in enumerate(tqdm(f, ascii=True)): try: d = eval(line) seq = discriminator.tokenizer.encode(d["text"]) if len(seq) < max_length_seq: seq = torch.tensor([50256] + seq, device=device, dtype=torch.long) else: print("Line {} is longer than maximum length {}".format(i, max_length_seq)) continue x.append(seq) y.append(int(np.sum(d["label"]) > 0)) except Exception: print("Error evaluating / tokenizing" " line {}, skipping it".format(i)) pass full_dataset = Dataset(x, y) train_size = int(0.9 * len(full_dataset)) test_size = len(full_dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size]) discriminator_meta = { "class_size": len(idx2class), "embed_size": discriminator.embed_size, "pretrained_model": pretrained_model, "class_vocab": class2idx, "default_class": 0, } else: # if dataset == "generic": # This assumes the input dataset is a TSV with the following structure: # class \t text if dataset_fp is None: raise ValueError("When generic dataset is selected, " "dataset_fp needs to be specified aswell.") classes = set() with open(dataset_fp) as f: csv_reader = csv.reader(f, delimiter="\t") for row in tqdm(csv_reader, ascii=True): if row: classes.add(row[0]) idx2class = sorted(classes) class2idx = {c: i for i, c in enumerate(idx2class)} discriminator = Discriminator( class_size=len(idx2class), pretrained_model=pretrained_model, cached_mode=cached, device=device ).to(device) x = [] y = [] with open(dataset_fp) as f: csv_reader = csv.reader(f, delimiter="\t") for i, row in enumerate(tqdm(csv_reader, ascii=True)): if row: label = row[0] text = row[1] try: seq = discriminator.tokenizer.encode(text) if len(seq) < max_length_seq: seq = torch.tensor([50256] + seq, device=device, dtype=torch.long) else: print("Line {} is longer than maximum length {}".format(i, max_length_seq)) continue x.append(seq) y.append(class2idx[label]) except Exception: print("Error tokenizing line {}, skipping it".format(i)) pass full_dataset = Dataset(x, y) train_size = int(0.9 * len(full_dataset)) test_size = len(full_dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size]) discriminator_meta = { "class_size": len(idx2class), "embed_size": discriminator.embed_size, "pretrained_model": pretrained_model, "class_vocab": class2idx, "default_class": 0, } end = time.time() print("Preprocessed {} data points".format(len(train_dataset) + len(test_dataset))) print("Data preprocessing took: {:.3f}s".format(end - start)) if cached: print("Building representation cache...") start = time.time() train_loader = get_cached_data_loader(train_dataset, batch_size, discriminator, shuffle=True, device=device) test_loader = get_cached_data_loader(test_dataset, batch_size, discriminator, device=device) end = time.time() print("Building representation cache took: {:.3f}s".format(end - start)) else: train_loader = torch.utils.data.DataLoader( dataset=train_dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn ) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, collate_fn=collate_fn) if save_model: with open("{}_classifier_head_meta.json".format(dataset), "w") as meta_file: json.dump(discriminator_meta, meta_file) optimizer = optim.Adam(discriminator.parameters(), lr=0.0001) for epoch in range(epochs): start = time.time() print("\nEpoch", epoch + 1) train_epoch( discriminator=discriminator, data_loader=train_loader, optimizer=optimizer, epoch=epoch, log_interval=log_interval, device=device, ) evaluate_performance(data_loader=test_loader, discriminator=discriminator, device=device) end = time.time() print("Epoch took: {:.3f}s".format(end - start)) print("\nExample prediction") predict(example_sentence, discriminator, idx2class, cached=cached, device=device) if save_model: # torch.save(discriminator.state_dict(), # "{}_discriminator_{}.pt".format( # args.dataset, epoch + 1 # )) torch.save( discriminator.get_classifier().state_dict(), "{}_classifier_head_epoch_{}.pt".format(dataset, epoch + 1), ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Train a discriminator on top of GPT-2 representations") parser.add_argument( "--dataset", type=str, default="SST", choices=("SST", "clickbait", "toxic", "generic"), help="dataset to train the discriminator on." "In case of generic, the dataset is expected" "to be a TSBV file with structure: class \\t text", ) parser.add_argument( "--dataset_fp", type=str, default="", help="File path of the dataset to use. " "Needed only in case of generic datadset", ) parser.add_argument( "--pretrained_model", type=str, default="gpt2-medium", help="Pretrained model to use as encoder" ) parser.add_argument("--epochs", type=int, default=10, metavar="N", help="Number of training epochs") parser.add_argument( "--batch_size", type=int, default=64, metavar="N", help="input batch size for training (default: 64)" ) parser.add_argument( "--log_interval", type=int, default=10, metavar="N", help="how many batches to wait before logging training status", ) parser.add_argument("--save_model", action="store_true", help="whether to save the model") parser.add_argument("--cached", action="store_true", help="whether to cache the input representations") parser.add_argument("--no_cuda", action="store_true", help="use to turn off cuda") args = parser.parse_args() train_discriminator(**(vars(args)))
{ "content_hash": "dc6a1ac4184ed4ebf623c3fc7caf8d04", "timestamp": "", "source": "github", "line_count": 505, "max_line_length": 117, "avg_line_length": 35.92277227722772, "alnum_prop": 0.5737831431563861, "repo_name": "huggingface/pytorch-transformers", "id": "51cdb5677324dead3ebe265e075c01ac1870404e", "size": "18769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/research_projects/pplm/run_pplm_discrim_train.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "194" }, { "name": "Jupyter Notebook", "bytes": "535623" }, { "name": "Python", "bytes": "897445" } ], "symlink_target": "" }
"""A wrapper of Session API which runs hooks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import sys import six from tensorflow.core.protobuf import config_pb2 from tensorflow.python.distribute import distribute_coordinator_context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import resources from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import coordinator from tensorflow.python.training import queue_runner from tensorflow.python.training import saver as training_saver from tensorflow.python.training import session_manager as sm from tensorflow.python.training import session_run_hook from tensorflow.python.util import function_utils from tensorflow.python.util.tf_export import tf_export # The list of exceptions that we should recover from. Exceptions not in this # list may terminate the job. _PREEMPTION_ERRORS = (errors.AbortedError, errors.UnavailableError) # Value that indicates no value was provided. USE_DEFAULT = object() @tf_export('train.Scaffold') class Scaffold(object): """Structure to create or gather pieces commonly needed to train a model. When you build a model for training you usually need ops to initialize variables, a `Saver` to checkpoint them, an op to collect summaries for the visualizer, and so on. Various libraries built on top of the core TensorFlow library take care of creating some or all of these pieces and storing them in well known collections in the graph. The `Scaffold` class helps pick these pieces from the graph collections, creating and adding them to the collections if needed. If you call the scaffold constructor without any arguments, it will pick pieces from the collections, creating default ones if needed when `scaffold.finalize()` is called. You can pass arguments to the constructor to provide your own pieces. Pieces that you pass to the constructor are not added to the graph collections. The following pieces are directly accessible as attributes of the `Scaffold` object: * `saver`: A `tf.train.Saver` object taking care of saving the variables. Picked from and stored into the `SAVERS` collection in the graph by default. * `init_op`: An op to run to initialize the variables. Picked from and stored into the `INIT_OP` collection in the graph by default. * `ready_op`: An op to verify that the variables are initialized. Picked from and stored into the `READY_OP` collection in the graph by default. * `ready_for_local_init_op`: An op to verify that global state has been initialized and it is alright to run `local_init_op`. Picked from and stored into the `READY_FOR_LOCAL_INIT_OP` collection in the graph by default. This is needed when the initialization of local variables depends on the values of global variables. * `local_init_op`: An op to initialize the local variables. Picked from and stored into the `LOCAL_INIT_OP` collection in the graph by default. * `summary_op`: An op to run and merge the summaries in the graph. Picked from and stored into the `SUMMARY_OP` collection in the graph by default. * `global_step`: A tensor containing the global step counter. Picked from and stored into the `GLOBAL_STEP` collection in the graph by default. You can also pass the following additional pieces to the constructor: * `init_feed_dict`: A session feed dictionary that should be used when running the init op. * `init_fn`: A callable to run after the init op to perform additional initializations. The callable will be called as `init_fn(scaffold, session)`. """ def __init__(self, init_op=None, init_feed_dict=None, init_fn=None, ready_op=None, ready_for_local_init_op=None, local_init_op=None, summary_op=None, saver=None, copy_from_scaffold=None): """Create a scaffold. Args: init_op: Optional op for initializing variables. init_feed_dict: Optional session feed dictionary to use when running the init_op. init_fn: Optional function to use to initialize the model after running the init_op. Will be called as `init_fn(scaffold, session)`. ready_op: Optional op to verify that the variables are initialized. Must return an empty 1D string tensor when the variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized variables. ready_for_local_init_op: Optional op to verify that the global variables are initialized and `local_init_op` can be run. Must return an empty 1D string tensor when the global variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized global variables. local_init_op: Optional op to initialize local variables. summary_op: Optional op to gather all summaries. Must return a scalar string tensor containing a serialized `Summary` proto. saver: Optional `tf.train.Saver` object to use to save and restore variables. copy_from_scaffold: Optional scaffold object to copy fields from. Its fields will be overwritten by the provided fields in this function. """ if copy_from_scaffold is not None: if not isinstance(copy_from_scaffold, Scaffold): raise TypeError('copy_from_scaffold is not a Scaffold instance.') # We need _coalesce since Tensor is not converted to bool automatically, # so the common idiom of (a or b) does not work. coalesce = lambda a, b: a if a is not None else b init_op = coalesce(init_op, copy_from_scaffold.init_op) init_feed_dict = coalesce(init_feed_dict, copy_from_scaffold.init_feed_dict) # Use the original init_fn provided by the user to init the new Scaffold. init_fn = coalesce(init_fn, copy_from_scaffold._user_init_fn) # pylint: disable=protected-access ready_op = coalesce(ready_op, copy_from_scaffold.ready_op) ready_for_local_init_op = coalesce( ready_for_local_init_op, copy_from_scaffold.ready_for_local_init_op) local_init_op = coalesce(local_init_op, copy_from_scaffold.local_init_op) summary_op = coalesce(summary_op, copy_from_scaffold.summary_op) saver = coalesce(saver, copy_from_scaffold.saver) # NOTE(touts): modifying the init function to be passed the scaffold is a # hack to make it easy to find the saver. Is there a better way? self._user_init_fn = init_fn if init_fn: self._init_fn = lambda sess: init_fn(self, sess) else: self._init_fn = None self._init_op = init_op self._init_feed_dict = init_feed_dict self._ready_op = ready_op self._ready_for_local_init_op = ready_for_local_init_op self._local_init_op = local_init_op self._summary_op = summary_op self._saver = saver def finalize(self): """Creates operations if needed and finalizes the graph.""" if self._init_op is None: def default_init_op(): return control_flow_ops.group( variables.global_variables_initializer(), resources.initialize_resources(resources.shared_resources())) self._init_op = Scaffold.get_or_default( 'init_op', ops.GraphKeys.INIT_OP, default_init_op) if self._ready_op is None: def default_ready_op(): return array_ops.concat([ variables.report_uninitialized_variables(), resources.report_uninitialized_resources() ], 0) self._ready_op = Scaffold.get_or_default( 'ready_op', ops.GraphKeys.READY_OP, default_ready_op) if self._ready_for_local_init_op is None: def default_ready_for_local_init_op(): return variables.report_uninitialized_variables( variables.global_variables()) self._ready_for_local_init_op = Scaffold.get_or_default( 'ready_for_local_init_op', ops.GraphKeys.READY_FOR_LOCAL_INIT_OP, default_ready_for_local_init_op) if self._local_init_op is None: self._local_init_op = Scaffold.get_or_default( 'local_init_op', ops.GraphKeys.LOCAL_INIT_OP, Scaffold.default_local_init_op) if self._summary_op is None: self._summary_op = Scaffold.get_or_default('summary_op', ops.GraphKeys.SUMMARY_OP, summary.merge_all) # pylint: disable=g-long-lambda if self._saver is None: self._saver = training_saver._get_saver_or_default() # pylint: disable=protected-access # pylint: enable=g-long-lambda self._saver.build() ops.get_default_graph().finalize() logging.info('Graph was finalized.') return self @property def init_fn(self): return self._init_fn @property def init_op(self): return self._init_op @property def ready_op(self): return self._ready_op @property def ready_for_local_init_op(self): return self._ready_for_local_init_op @property def local_init_op(self): return self._local_init_op @property def summary_op(self): return self._summary_op @property def saver(self): return self._saver @property def init_feed_dict(self): return self._init_feed_dict @staticmethod def get_or_default(arg_name, collection_key, default_constructor): """Get from cache or create a default operation.""" elements = ops.get_collection(collection_key) if elements: if len(elements) > 1: raise RuntimeError('More than one item in the collection "%s". ' 'Please indicate which one to use by passing it to ' 'the tf.Scaffold constructor as: ' 'tf.Scaffold(%s=item to use)', collection_key, arg_name) return elements[0] op = default_constructor() if op is not None: ops.add_to_collection(collection_key, op) return op @staticmethod def default_local_init_op(): """Returns an op that groups the default local init ops. This op is used during session initialization when a Scaffold is initialized without specifying the local_init_op arg. It includes `tf.local_variables_initializer`, `tf.tables_initializer`, and also initializes local session resources. Returns: The default Scaffold local init op. """ return control_flow_ops.group( variables.local_variables_initializer(), lookup_ops.tables_initializer(), resources.initialize_resources(resources.local_resources())) def _create_monitored_session_with_worker_context(worker_context, # pylint: disable=missing-docstring scaffold, checkpoint_dir=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=None, save_summaries_steps=None, save_summaries_secs=None, config=None, stop_grace_period_secs=120, log_step_count_steps=100, max_wait_secs=7200, save_checkpoint_steps=None, summary_dir=None): all_hooks = [] if hooks: all_hooks.extend(hooks) if chief_only_hooks and worker_context.is_chief: all_hooks.extend(chief_only_hooks) summary_dir = summary_dir or checkpoint_dir if summary_dir and worker_context.should_save_summary: if log_step_count_steps and log_step_count_steps > 0: all_hooks.append( basic_session_run_hooks.StepCounterHook( output_dir=summary_dir, every_n_steps=log_step_count_steps)) if (save_summaries_steps and save_summaries_steps > 0) or ( save_summaries_secs and save_summaries_secs > 0): all_hooks.append( basic_session_run_hooks.SummarySaverHook( scaffold=scaffold, save_steps=save_summaries_steps, save_secs=save_summaries_secs, output_dir=summary_dir)) if checkpoint_dir and worker_context.should_checkpoint: if (save_checkpoint_secs and save_checkpoint_secs > 0) or ( save_checkpoint_steps and save_checkpoint_steps > 0): all_hooks.append( basic_session_run_hooks.CheckpointSaverHook( checkpoint_dir, save_steps=save_checkpoint_steps, save_secs=save_checkpoint_secs, scaffold=scaffold)) session_creator = worker_context.session_creator( scaffold, config=config, checkpoint_dir=checkpoint_dir, max_wait_secs=max_wait_secs) return MonitoredSession( session_creator=session_creator, hooks=all_hooks, stop_grace_period_secs=stop_grace_period_secs) @tf_export('train.MonitoredTrainingSession') def MonitoredTrainingSession(master='', # pylint: disable=invalid-name is_chief=True, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=USE_DEFAULT, save_summaries_steps=USE_DEFAULT, save_summaries_secs=USE_DEFAULT, config=None, stop_grace_period_secs=120, log_step_count_steps=100, max_wait_secs=7200, save_checkpoint_steps=USE_DEFAULT, summary_dir=None): """Creates a `MonitoredSession` for training. For a chief, this utility sets proper session initializer/restorer. It also creates hooks related to checkpoint and summary saving. For workers, this utility sets proper session creator which waits for the chief to initialize/restore. Please check `tf.train.MonitoredSession` for more information. Args: master: `String` the TensorFlow master to use. is_chief: If `True`, it will take care of initialization and recovery the underlying TensorFlow session. If `False`, it will wait on a chief to initialize or recover the TensorFlow session. checkpoint_dir: A string. Optional path to a directory where to restore variables. scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified, a default one is created. It's used to finalize the graph. hooks: Optional list of `SessionRunHook` objects. chief_only_hooks: list of `SessionRunHook` objects. Activate these hooks if `is_chief==True`, ignore otherwise. save_checkpoint_secs: The frequency, in seconds, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default 600. save_summaries_steps: The frequency, in number of global steps, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default 100. save_summaries_secs: The frequency, in secs, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default not enabled. config: an instance of `tf.ConfigProto` proto used to configure the session. It's the `config` argument of constructor of `tf.Session`. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. log_step_count_steps: The frequency, in number of global steps, that the global step/sec is logged. max_wait_secs: Maximum time workers should wait for the session to become available. This should be kept relatively short to help detect incorrect code, but sometimes may need to be increased if the chief takes a while to start up. save_checkpoint_steps: The frequency, in number of global steps, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default not enabled. summary_dir: A string. Optional path to a directory where to save summaries. If None, checkpoint_dir is used instead. Returns: A `MonitoredSession` object. """ if save_summaries_steps == USE_DEFAULT and save_summaries_secs == USE_DEFAULT: save_summaries_steps = 100 save_summaries_secs = None elif save_summaries_secs == USE_DEFAULT: save_summaries_secs = None elif save_summaries_steps == USE_DEFAULT: save_summaries_steps = None if (save_checkpoint_steps == USE_DEFAULT and save_checkpoint_secs == USE_DEFAULT): save_checkpoint_steps = None save_checkpoint_secs = 600 elif save_checkpoint_secs == USE_DEFAULT: save_checkpoint_secs = None elif save_checkpoint_steps == USE_DEFAULT: save_checkpoint_steps = None scaffold = scaffold or Scaffold() worker_context = distribute_coordinator_context.get_current_worker_context() if worker_context: return _create_monitored_session_with_worker_context( worker_context, scaffold, checkpoint_dir=checkpoint_dir, hooks=hooks, chief_only_hooks=chief_only_hooks, save_checkpoint_secs=save_checkpoint_secs, save_summaries_steps=save_summaries_steps, save_summaries_secs=save_summaries_secs, config=config, stop_grace_period_secs=stop_grace_period_secs, log_step_count_steps=log_step_count_steps, max_wait_secs=max_wait_secs, save_checkpoint_steps=save_checkpoint_steps, summary_dir=summary_dir) if not is_chief: session_creator = WorkerSessionCreator( scaffold=scaffold, master=master, config=config, max_wait_secs=max_wait_secs) return MonitoredSession( session_creator=session_creator, hooks=hooks or [], stop_grace_period_secs=stop_grace_period_secs) all_hooks = [] if chief_only_hooks: all_hooks.extend(chief_only_hooks) session_creator = ChiefSessionCreator( scaffold=scaffold, checkpoint_dir=checkpoint_dir, master=master, config=config) summary_dir = summary_dir or checkpoint_dir if summary_dir: if log_step_count_steps and log_step_count_steps > 0: all_hooks.append( basic_session_run_hooks.StepCounterHook( output_dir=summary_dir, every_n_steps=log_step_count_steps)) if (save_summaries_steps and save_summaries_steps > 0) or ( save_summaries_secs and save_summaries_secs > 0): all_hooks.append( basic_session_run_hooks.SummarySaverHook( scaffold=scaffold, save_steps=save_summaries_steps, save_secs=save_summaries_secs, output_dir=summary_dir)) if checkpoint_dir: if (save_checkpoint_secs and save_checkpoint_secs > 0) or ( save_checkpoint_steps and save_checkpoint_steps > 0): all_hooks.append( basic_session_run_hooks.CheckpointSaverHook( checkpoint_dir, save_steps=save_checkpoint_steps, save_secs=save_checkpoint_secs, scaffold=scaffold)) if hooks: all_hooks.extend(hooks) return MonitoredSession( session_creator=session_creator, hooks=all_hooks, stop_grace_period_secs=stop_grace_period_secs) @tf_export('train.SessionCreator') class SessionCreator(object): """A factory for tf.Session.""" @abc.abstractmethod def create_session(self): raise NotImplementedError( 'create_session is not implemented for {}.'.format(self)) @tf_export('train.ChiefSessionCreator') class ChiefSessionCreator(SessionCreator): """Creates a tf.Session for a chief.""" def __init__(self, scaffold=None, master='', config=None, checkpoint_dir=None, checkpoint_filename_with_path=None): """Initializes a chief session creator. Args: scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. checkpoint_dir: A string. Optional path to a directory where to restore variables. checkpoint_filename_with_path: Full file name path to the checkpoint file. """ self._checkpoint_dir = checkpoint_dir self._checkpoint_filename_with_path = checkpoint_filename_with_path self._scaffold = scaffold or Scaffold() self._session_manager = None self._master = master self._config = config def _get_session_manager(self): if self._session_manager: return self._session_manager self._session_manager = sm.SessionManager( local_init_op=self._scaffold.local_init_op, ready_op=self._scaffold.ready_op, ready_for_local_init_op=self._scaffold.ready_for_local_init_op, graph=ops.get_default_graph()) return self._session_manager def create_session(self): self._scaffold.finalize() return self._get_session_manager().prepare_session( self._master, saver=self._scaffold.saver, checkpoint_dir=self._checkpoint_dir, checkpoint_filename_with_path=self._checkpoint_filename_with_path, config=self._config, init_op=self._scaffold.init_op, init_feed_dict=self._scaffold.init_feed_dict, init_fn=self._scaffold.init_fn) @tf_export('train.WorkerSessionCreator') class WorkerSessionCreator(SessionCreator): """Creates a tf.Session for a worker.""" def __init__(self, scaffold=None, master='', config=None, max_wait_secs=30 * 60): """Initializes a worker session creator. Args: scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. """ self._scaffold = scaffold or Scaffold() self._session_manager = None self._master = master self._config = config self._max_wait_secs = max_wait_secs def _get_session_manager(self): if self._session_manager: return self._session_manager self._session_manager = sm.SessionManager( local_init_op=self._scaffold.local_init_op, ready_op=self._scaffold.ready_op, ready_for_local_init_op=self._scaffold.ready_for_local_init_op, graph=ops.get_default_graph()) return self._session_manager def create_session(self): self._scaffold.finalize() return self._get_session_manager().wait_for_session( self._master, config=self._config, max_wait_secs=self._max_wait_secs ) class _MonitoredSession(object): """See `MonitoredSession` or `SingularMonitoredSession`.""" def __init__(self, session_creator, hooks, should_recover, stop_grace_period_secs=120): """Sets up a Monitored or Hooked Session. Args: session_creator: A factory object to create session. Typically a `ChiefSessionCreator` or a `WorkerSessionCreator`. hooks: An iterable of `SessionRunHook' objects. should_recover: A bool. Indicates whether to recover from `AbortedError` and `UnavailableError` or not. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. """ self._graph_was_finalized = ops.get_default_graph().finalized self._hooks = hooks or [] for h in self._hooks: h.begin() worker_context = distribute_coordinator_context.get_current_worker_context() if not session_creator and worker_context: session_creator = worker_context.session_creator() # Create the session. self._coordinated_creator = self._CoordinatedSessionCreator( session_creator=session_creator or ChiefSessionCreator(), hooks=self._hooks, stop_grace_period_secs=stop_grace_period_secs) if should_recover: self._sess = _RecoverableSession(self._coordinated_creator) else: self._sess = self._coordinated_creator.create_session() @property def graph(self): """The graph that was launched in this session.""" if self._tf_sess() is None: return None return self._tf_sess().graph def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Run ops in the monitored session. This method is completely compatible with the `tf.Session.run()` method. Args: fetches: Same as `tf.Session.run()`. feed_dict: Same as `tf.Session.run()`. options: Same as `tf.Session.run()`. run_metadata: Same as `tf.Session.run()`. Returns: Same as `tf.Session.run()`. """ return self._sess.run(fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) def run_step_fn(self, step_fn): """Run ops using a step function. Args: step_fn: A function or a method with a single argument of type `StepContext`. The function may use methods of the argument to perform computations with access to a raw session. The returned value of the `step_fn` will be returned from `run_step_fn`, unless a stop is requested. In that case, the next `should_stop` call will return True. Example usage: ```python with tf.Graph().as_default(): c = tf.placeholder(dtypes.float32) v = tf.add(c, 4.0) w = tf.add(c, 0.5) def step_fn(step_context): a = step_context.session.run(fetches=v, feed_dict={c: 0.5}) if a <= 4.5: step_context.request_stop() return step_context.run_with_hooks(fetches=w, feed_dict={c: 0.1}) with tf.MonitoredSession() as session: while not session.should_stop(): a = session.run_step_fn(step_fn) ``` Hooks interact with the `run_with_hooks()` call inside the `step_fn` as they do with a `MonitoredSession.run` call. Returns: Returns the returned value of `step_fn`. Raises: StopIteration: if `step_fn` has called `request_stop()`. It may be caught by `with tf.MonitoredSession()` to close the session. ValueError: if `step_fn` doesn't have a single argument called `step_context`. It may also optionally have `self` for cases when it belongs to an object. """ step_fn_arguments = function_utils.fn_args(step_fn) if step_fn_arguments != ('step_context',) and step_fn_arguments != ( 'self', 'step_context', ): raise ValueError( '`step_fn` may either have one `step_context` argument, or' ' `self` and `step_context` arguments if it\'s an instance' ' method. Got {} instead.'.format(step_fn_arguments)) # `self._sess` is either `_RecoverableSession` or a `_CoordinatedSession`. # Setting `run_with_hooks` to `None` will cause `run_with_hooks` to be # `_CoordinatedSession.run` downstream in either case. This allows # `_PREEMPTION_ERRORS` to propage from within `step_fn` to # `_RecoverableSession.run_step_fn`. return self._sess.run_step_fn(step_fn, self._tf_sess(), run_with_hooks=None) class StepContext(object): """Control flow instrument for the `step_fn` from `run_step_fn()`. Users of `step_fn` may perform `run()` calls without running hooks by accessing the `session`. A `run()` call with hooks may be performed using `run_with_hooks()`. Computation flow can be interrupted using `request_stop()`. """ def __init__(self, session, run_with_hooks_fn): """Initializes the `step_context` argument for a `step_fn` invocation. Args: session: An instance of `tf.Session`. run_with_hooks_fn: A function for running fetches and hooks. """ self._session = session self._run_with_hooks_fn = run_with_hooks_fn @property def session(self): return self._session def run_with_hooks(self, *args, **kwargs): """Same as `MonitoredSession.run`. Accepts the same arguments.""" return self._run_with_hooks_fn(*args, **kwargs) def request_stop(self): """Exit the training loop by causing `should_stop()` to return `True`. Causes `step_fn` to exit by raising an exception. Raises: StopIteration """ raise StopIteration('step_fn has requested the iterations to stop.') def should_stop(self): return self._sess is None or self._sess.should_stop() def close(self): self._close_internal() def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): if exception_type in [errors.OutOfRangeError, StopIteration]: exception_type = None self._close_internal(exception_type) # __exit__ should return True to suppress an exception. return exception_type is None class _CoordinatedSessionCreator(SessionCreator): """Factory for the _RecoverableSession.""" def __init__(self, session_creator, hooks, stop_grace_period_secs): self._session_creator = session_creator self._hooks = hooks self.coord = None self.tf_sess = None self._stop_grace_period_secs = stop_grace_period_secs def create_session(self): """Creates a coordinated session.""" # Keep the tf_sess for unit testing. self.tf_sess = self._session_creator.create_session() # We don't want coordinator to suppress any exception. self.coord = coordinator.Coordinator(clean_stop_exception_types=[]) if ops.get_collection(ops.GraphKeys.QUEUE_RUNNERS): queue_runner.start_queue_runners(sess=self.tf_sess, coord=self.coord) # Inform the hooks that a new session has been created. for hook in self._hooks: hook.after_create_session(self.tf_sess, self.coord) return _CoordinatedSession( _HookedSession(self.tf_sess, self._hooks), self.coord, self._stop_grace_period_secs) def _close_internal(self, exception_type=None): try: if not exception_type: for h in self._hooks: h.end(self._coordinated_creator.tf_sess) finally: try: if self._sess is None: raise RuntimeError('Session is already closed.') self._sess.close() finally: self._sess = None self._coordinated_creator.tf_sess = None self._coordinated_creator.coord = None if not self._graph_was_finalized: ops.get_default_graph()._unsafe_unfinalize() # pylint: disable=protected-access def _is_closed(self): """Return True if the monitored session is closed. For tests only. Returns: A boolean. """ return self._coordinated_creator.tf_sess is None def _tf_sess(self): return self._coordinated_creator.tf_sess @tf_export('train.MonitoredSession') class MonitoredSession(_MonitoredSession): """Session-like object that handles initialization, recovery and hooks. Example usage: ```python saver_hook = CheckpointSaverHook(...) summary_hook = SummarySaverHook(...) with MonitoredSession(session_creator=ChiefSessionCreator(...), hooks=[saver_hook, summary_hook]) as sess: while not sess.should_stop(): sess.run(train_op) ``` Initialization: At creation time the monitored session does following things in given order: * calls `hook.begin()` for each given hook * finalizes the graph via `scaffold.finalize()` * create session * initializes the model via initialization ops provided by `Scaffold` * restores variables if a checkpoint exists * launches queue runners * calls `hook.after_create_session()` Run: When `run()` is called, the monitored session does following things: * calls `hook.before_run()` * calls TensorFlow `session.run()` with merged fetches and feed_dict * calls `hook.after_run()` * returns result of `session.run()` asked by user * if `AbortedError` or `UnavailableError` occurs, it recovers or reinitializes the session before executing the run() call again Exit: At the `close()`, the monitored session does following things in order: * calls `hook.end()` * closes the queue runners and the session * suppresses `OutOfRange` error which indicates that all inputs have been processed if the monitored_session is used as a context How to set `tf.Session` arguments: * In most cases you can set session arguments as follows: ```python MonitoredSession( session_creator=ChiefSessionCreator(master=..., config=...)) ``` * In distributed setting for a non-chief worker, you can use following: ```python MonitoredSession( session_creator=WorkerSessionCreator(master=..., config=...)) ``` See `MonitoredTrainingSession` for an example usage based on chief or worker. Note: This is not a `tf.Session`. For example, it cannot do following: * it cannot be set as default session. * it cannot be sent to saver.save. * it cannot be sent to tf.train.start_queue_runners. Args: session_creator: A factory object to create session. Typically a `ChiefSessionCreator` which is the default one. hooks: An iterable of `SessionRunHook' objects. Returns: A MonitoredSession object. """ def __init__(self, session_creator=None, hooks=None, stop_grace_period_secs=120): super(MonitoredSession, self).__init__( session_creator, hooks, should_recover=True, stop_grace_period_secs=stop_grace_period_secs) @tf_export('train.SingularMonitoredSession') class SingularMonitoredSession(_MonitoredSession): """Session-like object that handles initialization, restoring, and hooks. Please note that this utility is not recommended for distributed settings. For distributed settings, please use `tf.train.MonitoredSession`. The differences between `MonitoredSession` and `SingularMonitoredSession` are: * `MonitoredSession` handles `AbortedError` and `UnavailableError` for distributed settings, but `SingularMonitoredSession` does not. * `MonitoredSession` can be created in `chief` or `worker` modes. `SingularMonitoredSession` is always created as `chief`. * You can access the raw `tf.Session` object used by `SingularMonitoredSession`, whereas in MonitoredSession the raw session is private. This can be used: - To `run` without hooks. - To save and restore. * All other functionality is identical. Example usage: ```python saver_hook = CheckpointSaverHook(...) summary_hook = SummarySaverHook(...) with SingularMonitoredSession(hooks=[saver_hook, summary_hook]) as sess: while not sess.should_stop(): sess.run(train_op) ``` Initialization: At creation time the hooked session does following things in given order: * calls `hook.begin()` for each given hook * finalizes the graph via `scaffold.finalize()` * create session * initializes the model via initialization ops provided by `Scaffold` * restores variables if a checkpoint exists * launches queue runners Run: When `run()` is called, the hooked session does following things: * calls `hook.before_run()` * calls TensorFlow `session.run()` with merged fetches and feed_dict * calls `hook.after_run()` * returns result of `session.run()` asked by user Exit: At the `close()`, the hooked session does following things in order: * calls `hook.end()` * closes the queue runners and the session * suppresses `OutOfRange` error which indicates that all inputs have been processed if the `SingularMonitoredSession` is used as a context. """ def __init__(self, hooks=None, scaffold=None, master='', config=None, checkpoint_dir=None, stop_grace_period_secs=120, checkpoint_filename_with_path=None): """Creates a SingularMonitoredSession. Args: hooks: An iterable of `SessionRunHook' objects. scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. checkpoint_dir: A string. Optional path to a directory where to restore variables. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. checkpoint_filename_with_path: A string. Optional path to a checkpoint file from which to restore variables. """ session_creator = ChiefSessionCreator( scaffold=scaffold, master=master, config=config, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path) super(SingularMonitoredSession, self).__init__( session_creator, hooks, should_recover=False, stop_grace_period_secs=stop_grace_period_secs) def raw_session(self): """Returns underlying `TensorFlow.Session` object.""" return self._tf_sess() class _WrappedSession(object): """Wrapper around a `tf.Session`. This wrapper is used as a base class for various session wrappers that provide additional functionality such as monitoring, coordination, and recovery. In addition to the methods exported by `SessionInterface` the wrapper provides a method to check for stop and never raises exceptions from calls to `close()`. """ def __init__(self, sess): """Creates a `_WrappedSession`. Args: sess: A `tf.Session` or `_WrappedSession` object. The wrapped session. """ self._sess = sess self._wrapped_is_stoppable = isinstance(self._sess, _WrappedSession) @property def graph(self): return self._sess.graph @property def sess_str(self): return self._sess.sess_str def should_stop(self): """Return true if this session should not be used anymore. Always return True if the session was closed. Returns: True if the session should stop, False otherwise. """ if self._check_stop(): return True if self._sess: return self._wrapped_is_stoppable and self._sess.should_stop() return True def _check_stop(self): """Hook for subclasses to provide their own stop condition. Returns: True if the session should stop, False otherwise. """ return False def close(self): if self._sess: try: self._sess.close() except _PREEMPTION_ERRORS: pass finally: self._sess = None def run(self, *args, **kwargs): return self._sess.run(*args, **kwargs) def run_step_fn(self, step_fn, raw_session, run_with_hooks): # `_RecoverableSession` sets `run_with_hooks` to `_CoordinatedSession.run`. # It is `None` when called from `_CoordinatedSession`. In that case # `self.run` is `_CoordinatedSession.run`. run_with_hooks = run_with_hooks or self.run return step_fn(_MonitoredSession.StepContext(raw_session, run_with_hooks)) class _RecoverableSession(_WrappedSession): """A wrapped session that recreates a session upon certain kinds of errors. The constructor is passed a SessionCreator object, not a session. Calls to `run()` are delegated to the wrapped session. If a call raises the exception `tf.errors.AbortedError` or `tf.errors.UnavailableError`, the wrapped session is closed, and a new one is created by calling the factory again. """ def __init__(self, sess_creator): """Create a new `_RecoverableSession`. The value returned by calling `sess_creator.create_session()` will be the session wrapped by this recoverable session. Args: sess_creator: A 'SessionCreator' to be wrapped by recoverable. """ self._sess_creator = sess_creator _WrappedSession.__init__(self, self._create_session()) def _create_session(self): while True: try: return self._sess_creator.create_session() except _PREEMPTION_ERRORS as e: logging.info('An error was raised while a session was being created. ' 'This may be due to a preemption of a connected worker ' 'or parameter server. A new session will be created. ' 'Error: %s', e) def _check_stop(self): try: if self._sess: return self._sess._check_stop() # pylint: disable=protected-access else: return True except _PREEMPTION_ERRORS as e: logging.info('An error was raised while considering whether the ' 'session is complete. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = self._create_session() # Since we have just recreated the session, the overall computation should # not stop: return False except Exception: # pylint: disable=broad-except # `should_stop` should return True instead of raising an exception. return True def run(self, fetches, feed_dict=None, options=None, run_metadata=None): while True: try: if not self._sess: self._sess = self._create_session() return self._sess.run(fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) except _PREEMPTION_ERRORS as e: logging.info('An error was raised. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = None def run_step_fn(self, step_fn, raw_session, run_with_hooks): while True: try: if not self._sess: self._sess = self._create_session() run_with_hooks = self._sess.run return self._sess.run_step_fn(step_fn, raw_session, run_with_hooks) except _PREEMPTION_ERRORS as e: logging.info('An error was raised. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = None class _CoordinatedSession(_WrappedSession): """A wrapped session that works with a `tf.Coordinator`. Calls to `run()` are delegated to the wrapped session. If a call raises an exception, the exception is reported to the coordinator. In addition, after each call to `run()` this session ask the coordinator if the session should stop. In that case it will will join all the threads registered with the coordinator before returning. If the coordinator was requested to stop with an exception, that exception will be re-raised from the call to `run()`. """ def __init__(self, sess, coord, stop_grace_period_secs=120): """Create a new `_CoordinatedSession`. Args: sess: A `tf.Session` object. The wrapped session. coord: A `tf.train.Coordinator` object. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. """ _WrappedSession.__init__(self, sess) self._coord = coord self._stop_grace_period_secs = stop_grace_period_secs def _check_stop(self): # If the coordinator was asked to stop due to an exception, then it needs # to be propagated to this stack. self._coord.raise_requested_exception() # At this point, no exceptions are recorded in the coordinator. return self._coord.should_stop() def close(self): self._coord.request_stop() try: self._coord.join( stop_grace_period_secs=self._stop_grace_period_secs, ignore_live_threads=True) finally: try: _WrappedSession.close(self) except Exception: # pylint: disable=broad-except # We intentionally suppress exceptions from the close() here since # useful exceptions are already reported by join(). pass def run(self, *args, **kwargs): try: return self._sess.run(*args, **kwargs) except _PREEMPTION_ERRORS: raise except Exception: # pylint: disable=broad-except # A non-preemption error could have been caused by a preemption error # in the coordinator. If this is the case, raise that exception instead, # since it's the root cause. Otherwise, stick to the `original_exc_info`. original_exc_info = sys.exc_info() try: self._coord.raise_requested_exception() except _PREEMPTION_ERRORS: raise except Exception: # pylint: disable=broad-except raise six.reraise(*original_exc_info) else: raise six.reraise(*original_exc_info) class _HookedSession(_WrappedSession): """A _WrappedSession that calls hooks during calls to run(). The list of hooks to call is passed in the constructor. Before each call to `run()` the session calls the `before_run()` method of the hooks, which can return additional ops or tensors to run. These are added to the arguments of the call to `run()`. When the `run()` call finishes, the session calls the `after_run()` methods of the hooks, passing the values returned by the `run()` call corresponding to the ops and tensors that each hook requested. If any call to the hooks, requests stop via run_context the session will be marked as needing to stop and its `should_stop()` method will now return `True`. """ def __init__(self, sess, hooks): """Initializes a _HookedSession object. Args: sess: A `tf.Session` or a `_WrappedSession` object. hooks: An iterable of `SessionRunHook' objects. """ _WrappedSession.__init__(self, sess) self._hooks = hooks self._should_stop = False def _check_stop(self): """See base class.""" return self._should_stop def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """See base class.""" if self.should_stop(): raise RuntimeError('Run called even after should_stop requested.') actual_fetches = {'caller': fetches} run_context = session_run_hook.SessionRunContext( original_args=session_run_hook.SessionRunArgs(fetches, feed_dict), session=self._sess) options = options or config_pb2.RunOptions() feed_dict = self._call_hook_before_run(run_context, actual_fetches, feed_dict, options) # Do session run. run_metadata = run_metadata or config_pb2.RunMetadata() outputs = _WrappedSession.run(self, fetches=actual_fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) for hook in self._hooks: hook.after_run( run_context, session_run_hook.SessionRunValues( results=outputs[hook] if hook in outputs else None, options=options, run_metadata=run_metadata)) self._should_stop = self._should_stop or run_context.stop_requested return outputs['caller'] def _call_hook_before_run(self, run_context, fetch_dict, user_feed_dict, options): """Calls hooks.before_run and handles requests from hooks.""" hook_feeds = {} for hook in self._hooks: request = hook.before_run(run_context) if request is not None: if request.fetches is not None: fetch_dict[hook] = request.fetches if request.feed_dict: self._raise_if_feeds_intersects( hook_feeds, request.feed_dict, 'Same tensor is fed by two hooks.') hook_feeds.update(request.feed_dict) if request.options: self._merge_run_options(options, request.options) if not hook_feeds: return user_feed_dict if not user_feed_dict: return hook_feeds self._raise_if_feeds_intersects( user_feed_dict, hook_feeds, 'Same tensor is fed by a SessionRunHook and user.') hook_feeds.update(user_feed_dict) return hook_feeds def _raise_if_feeds_intersects(self, feeds1, feeds2, message): intersection = set(feeds1.keys()) & set(feeds2.keys()) if intersection: raise RuntimeError(message + ' Conflict(s): ' + str(list(intersection))) def _merge_run_options(self, options, incoming_options): """Merge two instances of RunOptions into the first one. During the merger, the numerical fields including trace_level, timeout_in_ms, inter_op_thread_pool are set to the larger one of the two. The boolean value is set to the logical OR of the two. debug_tensor_watch_opts of the original options is extended with that from the incoming one. Args: options: The options to merge into. incoming_options: The options to be merged into the first argument. """ options.trace_level = max(options.trace_level, incoming_options.trace_level) options.timeout_in_ms = max(options.timeout_in_ms, incoming_options.timeout_in_ms) options.inter_op_thread_pool = max(options.inter_op_thread_pool, incoming_options.inter_op_thread_pool) options.output_partition_graphs = max( options.output_partition_graphs, incoming_options.output_partition_graphs) options.debug_options.debug_tensor_watch_opts.extend( incoming_options.debug_options.debug_tensor_watch_opts) options.debug_options.reset_disk_byte_usage = ( options.debug_options.reset_disk_byte_usage or incoming_options.debug_options.reset_disk_byte_usage)
{ "content_hash": "3accd1ce0021aa6dbe5f486d0e9ae760", "timestamp": "", "source": "github", "line_count": 1354, "max_line_length": 103, "avg_line_length": 38.438700147710485, "alnum_prop": 0.6552280674787688, "repo_name": "xodus7/tensorflow", "id": "0e0125a9566208109a7eb595554f37be06cabe03", "size": "52771", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tensorflow/python/training/monitored_session.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1286" }, { "name": "Batchfile", "bytes": "9258" }, { "name": "C", "bytes": "340946" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "48861698" }, { "name": "CMake", "bytes": "195699" }, { "name": "Dockerfile", "bytes": "36400" }, { "name": "Go", "bytes": "1240309" }, { "name": "HTML", "bytes": "4681865" }, { "name": "Java", "bytes": "834061" }, { "name": "Jupyter Notebook", "bytes": "2604756" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "52618" }, { "name": "Objective-C", "bytes": "15650" }, { "name": "Objective-C++", "bytes": "99243" }, { "name": "PHP", "bytes": "1357" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "40952138" }, { "name": "Ruby", "bytes": "553" }, { "name": "Shell", "bytes": "459258" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_rightmost_set_bit(0) -1 >>> get_index_of_rightmost_set_bit(5) 0 >>> get_index_of_rightmost_set_bit(36) 2 >>> get_index_of_rightmost_set_bit(8) 3 >>> get_index_of_rightmost_set_bit(-18) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if number < 0 or not isinstance(number, int): raise ValueError("Input must be a non-negative integer") intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == "__main__": """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
{ "content_hash": "ecebe224c84012fd473eb6fe9d0567ba", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 78, "avg_line_length": 27.675, "alnum_prop": 0.6214995483288166, "repo_name": "TheAlgorithms/Python", "id": "eb52ea4e63e38ebed0434f65a3e55aac7c83efeb", "size": "1183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bit_manipulation/index_of_rightmost_set_bit.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2601694" } ], "symlink_target": "" }
"""Sluice Flask App.""" from __future__ import absolute_import import os from celery import Celery from flask import ( Flask, abort, flash, render_template, redirect, request, session, url_for, ) from flask.ext.bootstrap import Bootstrap from flask.ext import breadcrumbs from flask_extras import FlaskExtras from flask_wtf.csrf import CsrfProtect from bson.objectid import ObjectId from pymongo import MongoClient import forms import filters import prospector_api as api import settings as fs DB_URI = os.environ.get('SLUICE_DB_HOST', 'localhost') DB_PORT = int(os.environ.get('SLUICE_DB_PORT', 27017)) DB_NAME = os.environ.get('SLUICE_DB', 'sluice') DB_COLL = os.environ.get('SLUICE_DB_COLL', 'jobs') client = MongoClient(host=DB_URI, port=DB_PORT) conn = client[DB_NAME] coll = conn[DB_COLL] currdir = os.getcwd() app = Flask(__name__) app.config.update(**fs.FLASK_CONFIG) app.secret_key = fs.SECRET_KEY app.jinja_env.filters['error_label'] = filters.error_label app.jinja_env.filters['get_strictness_label'] = filters.get_strictness_label celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) # Inject app config into celery. celery.conf.update(app.config) # Add nav breadcrumbs breadcrumbs.Breadcrumbs(app=app) # Setup CSRF protection CsrfProtect().init_app(app) bootstrap = Bootstrap(app) # Setup extra filters/macros FlaskExtras(app) def _get_search_formdefaults(): """Return search form pre-populated with existing GET params.""" defaults = dict() for arg in ['output', 'strictness', 'name', 'path', 'github_url']: if all([ request.args.get(arg) is not None, request.args.get(arg) != '', ]): defaults.update(**{arg: request.args.get(arg).strip()}) return forms.SearchForm(**defaults) @app.context_processor def _inject_default_args(): return dict( active_nav='', searchform=_get_search_formdefaults(), APP_NAME=fs.APP_NAME, page_title=str(request.url_rule), user=session.get('user', None), ) @app.route('/job/<tr_id>', methods=['GET']) @breadcrumbs.register_breadcrumb(app, '.job', 'Job') def job(tr_id): """Job results.""" testrun = coll.find_one(dict(_id=ObjectId(tr_id))) if not testrun: abort(404) kwargs = dict( id=tr_id, testrun=testrun ) return render_template('pages/job.html', **kwargs) @app.route('/timeline', methods=['GET']) @breadcrumbs.register_breadcrumb(app, '.timeline', 'Timeline') def timeline(): """View results.""" runs = None url = request.args.get('github_url') if url is not None: runs = coll.find(dict(github_url=url)) kwargs = dict( url=url, runs=runs, ) return render_template('pages/timeline.html', **kwargs) @celery.task def lint_code(username, **kwargs): """Layer of indirection around db, celery task and prospector API.""" pathname = kwargs.pop('path') name = kwargs.pop('name') github_url = kwargs.pop('github_url') results = api.get_results(pathname, **kwargs) kwargs.update(dict( name=name, github_url=github_url, pathname=pathname, created_by=username, results=results, )) coll.insert_one(kwargs) @app.route('/search', methods=['GET']) @breadcrumbs.register_breadcrumb(app, '.search', 'Search results') def search(): """Search page.""" search_kwargs = dict() for arg in ['output', 'strictness', 'name', 'path', 'github_url']: if all([ request.args.get(arg) is not None, request.args.get(arg) != '', ]): search_kwargs.update(**{arg: request.args.get(arg).strip()}) results = coll.find(search_kwargs) if not results: return abort(404) kwargs = dict(results=results) return render_template('pages/search.html', **kwargs) @app.route('/', methods=['GET', 'POST']) @breadcrumbs.register_breadcrumb(app, '.', 'Home') def index(): """Index page.""" form = forms.ProspectorResultsForm() task = None if request.method == 'POST': if form.validate_on_submit(): data = form.data user = session.get('user', 'Anonymous') task = lint_code.delay(user, **data) flash('Added new test entry to queue.') return redirect(url_for('index')) kwargs = dict( active_nav='home', results=task, form=form, existing=coll.find(), ) return render_template('pages/index.html', **kwargs) if __name__ == "__main__": # TOOD: move to one-time script, like alembic. # models.create_schemas(db) app.run(**fs.FLASK_RUN_SETTINGS)
{ "content_hash": "df600429d3f452a66a052c2b52ead8e7", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 76, "avg_line_length": 26.39664804469274, "alnum_prop": 0.6323809523809524, "repo_name": "christabor-incubator/sluice", "id": "53a338235d57a59e946974ca7d6dba0673bb7724", "size": "4748", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7884" }, { "name": "Python", "bytes": "8603" } ], "symlink_target": "" }
import time from behave import step from atip.web import web @step(u'I wait for {timeout:d} seconds') def wait_for_timeout(context, timeout): time.sleep(timeout) @step(u'launch "{app_name}"') def launch_app_by_name(context, app_name): web.launch_webapp_by_name(context, app_name) @step(u'I launch "{app_name}" with "{apk_pkg_name}" and "{apk_activity_name}"') def launch_app_by_names(context, app_name, apk_pkg_name, apk_activity_name): web.launch_webapp_by_name(context, app_name, apk_pkg_name, apk_activity_name) @step(u'switch to "{app_name}"') def switch_to_app_name(context, app_name): if app_name in context.apps: context.app = context.apps[app_name] assert True else: assert False @step(u'pic "{pic1}" and pic "{pic2}" should be more than "{similarity}" similar') def check_picture(context, pic1, pic2, similarity): assert context.app.check_pic_same(pic1, pic2, similarity) @step(u'pic "{pic1}" and pic "{pic2}" should be less than "{similarity}" similar') def check_picture(context, pic1, pic2, similarity): assert context.app.check_pic_different(pic1, pic2, similarity)
{ "content_hash": "7c7a6c53795dbbb1773b92872b13855f", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 82, "avg_line_length": 35.5625, "alnum_prop": 0.6968365553602812, "repo_name": "jacky-young/crosswalk-test-suite", "id": "646bba18f691a8756b47645307d9e6d8f89d2ef1", "size": "2667", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/atip/atip/common/steps.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "820234" }, { "name": "CoffeeScript", "bytes": "18978" }, { "name": "Cucumber", "bytes": "65825" }, { "name": "GLSL", "bytes": "3495" }, { "name": "Groff", "bytes": "12" }, { "name": "HTML", "bytes": "39686628" }, { "name": "Java", "bytes": "284601" }, { "name": "JavaScript", "bytes": "17553033" }, { "name": "Makefile", "bytes": "1044" }, { "name": "PHP", "bytes": "44946" }, { "name": "Python", "bytes": "4264875" }, { "name": "Shell", "bytes": "1097373" }, { "name": "XSLT", "bytes": "767778" } ], "symlink_target": "" }
import serial import unilog from . import misc, excepts from .compat import unicode, xrange, str_compat from .handlers import commands as hc STX = bytearray((0x02, )) # START OF TEXT - начало текста ENQ = bytearray((0x05, )) # ENQUIRY - запрос ACK = bytearray((0x06, )) # ACKNOWLEDGE - положительное подтверждение NAK = bytearray((0x15, )) # NEGATIVE ACKNOWLEDGE - отрицательное подтверждение class Protocol(object): MAX_ATTEMPTS = 10 CHECK_NUM = 3 def __init__(self, port, baudrate, timeout, fs=False): """ Класс описывающий протокол взаимодействия в устройством. :type port: str :param port: порт взаимодействия с устройством :type baudrate: int :param baudrate: скорость взаимодействия с устройством :type timeout: float :param timeout: время таймаута ответа устройства :type fs: bool :param fs: признак наличия ФН (фискальный накопитель) """ self.port = port self.serial = serial.Serial( baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=timeout, writeTimeout=timeout ) self.fs = fs self.connected = False def connect(self): """ Метод подключения к устройству. """ if not self.connected: self.serial.port = self.port if not self.serial.isOpen(): try: self.serial.open() except serial.SerialException as exc: raise excepts.NoConnectionError( u'Не удалось открыть порт {} ({})'.format( self.port, exc ) ) for r in self.check(self.CHECK_NUM, True): if r: self.connected = True return else: self.serial.close() raise excepts.NoConnectionError() def disconnect(self): """ Метод отключения от устройства. """ if self.connected: self.serial.close() self.connected = False def init(self): """ Метод инициализации устройства перед отправкой команды. """ try: self.serial.write(ENQ) byte = self.serial.read() if not byte: raise excepts.NoConnectionError() if byte == NAK: pass elif byte == ACK: self.handle_response() else: while self.serial.read(): pass return False return True except serial.SerialTimeoutException: self.serial.flushOutput() raise excepts.ProtocolError(u'Не удалось записать байт в ККМ') except serial.SerialException as exc: self.serial.flushInput() raise excepts.ProtocolError(unicode(exc)) def handle_response(self): """ Метод обработки ответа ККМ. :rtype: dict :return: ответ ККМ в виде словаря """ for _ in xrange(self.MAX_ATTEMPTS): stx = self.serial.read() if stx != STX: raise excepts.NoConnectionError() length = self.serial.read() payload = self.serial.read(misc.UNCAST_SIZE['1'](length)) _lrc = misc.UNCAST_SIZE['1'](self.serial.read()) if misc.lrc(misc.bytearray_concat(length, payload)) == _lrc: self.serial.write(ACK) return self.handle_payload(payload) else: self.serial.write(NAK) self.serial.write(ENQ) byte = self.serial.read() if byte != ACK: raise excepts.UnexpectedResponseError(u'Получен байт 0x{:02X}, ожидался ACK'.format(ord(byte))) else: raise excepts.NoConnectionError() def handle_payload(self, payload): """ Метод обработки полезной нагрузки ответа ККМ. :type payload: str or bytearray :param payload: часть ответа ККМ, содержащая полезную нагрузку :rtype: dict :return: набор параметров в виде словаря """ payload = misc.bytearray_cast(payload) # предполагаем, что команда однобайтная cmd_len = 1 try: cmd = payload[0] # если байт полный, то скорее всего команда двубайтная, # т.к. в спецификации Штриха не предусмотрено команды с кодом 0xFF if cmd == 0xFF: cmd_len = 2 cmd = misc.bytes_to_int((payload[1], cmd)) except IndexError: raise excepts.UnexpectedResponseError(u'Не удалось получить байт(ы) команды из ответа') response = payload[slice(cmd_len, None)] handler = hc.HANDLERS.get(cmd) if handler: result = {} for _slice, func, name in handler: chunk = _slice(response) if isinstance(_slice, misc.mslice) else response[_slice] if chunk and name is None: result.update(func(chunk)) elif chunk: result[name] = func(chunk) if func else chunk else: result[name] = None error = result.get(hc.ERROR_CODE_STR, 0) if error != 0: raise excepts.Error(cmd, error, fs=self.fs) return Response(cmd, result) return response def command_nopass(self, cmd, params=bytearray()): """ Метод отправки команды без пароля оператора. :type cmd: int :param cmd: номер команды :type params: bytearray :param params: набор параметров команды :rtype: dict :return: набор параметров ответа в виде словаря """ if not isinstance(params, bytearray): raise TypeError(u'{} expected, got {} instead'.format(bytearray, type(params))) cmd_len = len(misc.int_to_bytes(cmd)) buff = misc.bytearray_concat( misc.CAST_SIZE['1'](cmd_len + len(params)), misc.CAST_CMD[cmd_len](cmd), params ) command = misc.bytearray_concat(STX, buff, misc.CAST_SIZE['1'](misc.lrc(buff))) for r in self.check(self.CHECK_NUM): if not r: continue for _ in xrange(self.MAX_ATTEMPTS): try: self.serial.write(command) byte = self.serial.read() if byte == ACK: return self.handle_response() except serial.SerialTimeoutException: self.serial.flushOutput() raise excepts.ProtocolError(u'Не удалось записать байт в ККМ') except serial.SerialException as exc: self.serial.flushInput() raise excepts.ProtocolError(unicode(exc)) else: raise excepts.NoConnectionError() else: raise excepts.NoConnectionError() def command(self, cmd, password, *params): """ Метод отправки команды с паролем оператора. :type cmd: int :param cmd: номер команды :type password: int :param password: пароль оператора :type params: bytearray :param params: набор параметров команды :rtype: dict :return: набор параметров ответа в виде словаря """ params = misc.bytearray_concat( misc.CAST_SIZE['4'](password), *params ) return self.command_nopass(cmd, params) def check(self, count=1, quiet=False): """ Проверка связи с ККМ. :type count: int :param count: количество отправляемых пакетов :type quiet: bool :param quiet: подавление исключений """ if self.serial is None: raise excepts.ProtocolError(u'Необходимо вначале выполнить метод connect()') if count < 1: raise ValueError('Параметр count должен быть >= 1') for _ in xrange(count): try: yield self.init() except excepts.NoConnectionError: if quiet: yield False else: raise @str_compat class Response(object): __slots__ = ( 'cmd', 'cmd_name', 'params' ) def __init__(self, cmd, params): """ Класс ответа ККМ. :type cmd: int :param cmd: номер команды :type params: dict :param params: словарь параметров ответа ККМ """ self.cmd = cmd self.cmd_name = hc.COMMANDS[cmd] self.params = params def __getitem__(self, item): return self.params[item] def __setitem__(self, key, value): self.params[key] = value def __str__(self): return u'0x{:02X} ({}) - {}'.format( self.cmd, self.cmd_name, unilog.as_unicode(self.params) ) __repr__ = __str__
{ "content_hash": "c1bbe1fef39c8ffcd827e41b0cccad36", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 115, "avg_line_length": 29.758842443729904, "alnum_prop": 0.5324689357104267, "repo_name": "juliadolgova/pyshtrih", "id": "5e90670f5320f21e0edd175a350ee016fd1873a2", "size": "10425", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pyshtrih/protocol.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "106406" } ], "symlink_target": "" }
from django.core.management.base import BaseCommand class Command(BaseCommand): """ Alter one or more models' tables with the registered attributes """ help = "Alter the tables for all registered models, or just specified models" args = "[appname ...]" can_import_settings = True requires_model_validation = False def handle(self, *args, **options): """ Alter the tables """ from categories.migration import migrate_app from categories.settings import MODEL_REGISTRY if args: for app in args: migrate_app(None, app) else: for app in MODEL_REGISTRY: migrate_app(None, app)
{ "content_hash": "b05a54731aac9e6a3841ac6481960cef", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 81, "avg_line_length": 28.8, "alnum_prop": 0.6069444444444444, "repo_name": "miceno/django-categories", "id": "53daf580caf91674f23bcf76bc48826ede9299b1", "size": "720", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "categories/management/commands/add_category_fields.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3091" }, { "name": "CSS", "bytes": "17443" }, { "name": "HTML", "bytes": "18445" }, { "name": "JavaScript", "bytes": "28087" }, { "name": "Makefile", "bytes": "3637" }, { "name": "Python", "bytes": "157634" } ], "symlink_target": "" }
from CPWeb.BibtexTools import getCitationOrAlternative, getBibtexParser from CPWeb.SphinxTools import FluidGenerator import os.path import CoolProp web_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) root_dir = os.path.abspath(os.path.join(web_dir, '..')) csvfile = os.path.join(web_dir,'fluid_properties','PurePseudoPure.csv') indexfile = os.path.join(web_dir,'fluid_properties', 'fluidstoc.rst.in') class Dossier: def __init__(self): self.data = {} def add(self, key, value): if key not in self.data: self.data[key] = [] self.data[key].append(value) d = Dossier() from pybtex.database.input import bibtex parser = bibtex.Parser() bibdata = parser.parse_file(os.path.join(root_dir,"CoolPropBibTeXLibrary.bib")) bibtexer = getBibtexParser() bibtex_map = {'EOS': 'EOS', 'CP0': ':math:`c_{p0}`', 'CONDUCTIVITY': ':math:`\lambda`', 'VISCOSITY': ':math:`\eta`', 'MELTING_LINE': 'melt', 'SURFACE_TENSION': ':math:`\sigma`'} bibtex_keys = ['EOS','CP0','CONDUCTIVITY','VISCOSITY','MELTING_LINE','SURFACE_TENSION'] fluids_path = os.path.join(web_dir,'fluid_properties','fluids') if not os.path.exists(fluids_path): os.makedirs(fluids_path) for fluid in CoolProp.__fluids__: FG = FluidGenerator(fluid) FG.write(fluids_path) d.add('name', fluid) for key in bibtex_keys: try: # get the item s = CoolProp.CoolProp.get_BibTeXKey(fluid,key) s = s.strip() if s and any([_s not in bibdata.entries.keys() for _s in s.split(',')]): print 'problem', fluid, key, '\t\t\t\t', "|"+s+'|' d.add(key, '') else: d.add(key, s) except ValueError as E: d.add(key, '') import pandas df = pandas.DataFrame(d.data) df = df.sort_values(by=['name'], ascending = [1]) def build_citation(key): if not key: return '' else: return ':cite:`'+key+'`' def fluid_reference(fluid): return ':ref:`{fluid:s} <fluid_{fluid:s}>`'.format(fluid = fluid) # Write the table with open(csvfile,'w') as fp: rowdata = ["Name"] + [bibtex_map[key] for key in bibtex_keys] fp.write(';'.join(rowdata)+'\n') for index, row in df.iterrows(): rowdata = [fluid_reference(row['name'])] + [build_citation(row[key]) for key in bibtex_keys] fp.write(';'.join(rowdata)+'\n') # Write the hidden table to make sphinx happy with open(indexfile,'w') as fp: fp.write('.. toctree::\n :hidden:\n\n') for index, row in df.iterrows(): fp.write(' fluids/' + row['name'] + '.rst\n')
{ "content_hash": "d17affedfe25edccfbe7d95af7d1f825", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 100, "avg_line_length": 32.91566265060241, "alnum_prop": 0.5845534407027818, "repo_name": "DANA-Laboratory/CoolProp", "id": "2d6aaa0701038bc32614f84806a8d1ae83bae664", "size": "2732", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Web/scripts/fluid_properties.PurePseudoPure.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4019" }, { "name": "C", "bytes": "266660" }, { "name": "C#", "bytes": "64222" }, { "name": "C++", "bytes": "2737181" }, { "name": "CMake", "bytes": "125400" }, { "name": "CSS", "bytes": "8226" }, { "name": "Fortran", "bytes": "7463" }, { "name": "HTML", "bytes": "10898" }, { "name": "Julia", "bytes": "64855" }, { "name": "Jupyter Notebook", "bytes": "112217" }, { "name": "Lua", "bytes": "9624" }, { "name": "M", "bytes": "120" }, { "name": "Makefile", "bytes": "27444" }, { "name": "Mathematica", "bytes": "4264" }, { "name": "Matlab", "bytes": "7828" }, { "name": "Objective-C", "bytes": "856" }, { "name": "Pascal", "bytes": "41142" }, { "name": "Python", "bytes": "1472910" }, { "name": "Scilab", "bytes": "1684" }, { "name": "Shell", "bytes": "22046" }, { "name": "TeX", "bytes": "127745" }, { "name": "Visual Basic", "bytes": "30858" } ], "symlink_target": "" }
import cherrypy from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa import json import os import re from urllib.parse import urlparse, urlunparse, parse_qs from urllib.request import urlopen import validators from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, getApiUrl, setResponseHeader from girder.constants import AccessType from girder.exceptions import RestException from girder.models.folder import Folder from girder.models.item import Item from girder.plugins.ythub.constants import PluginSettings _DOI_REGEX = re.compile(r'(10.\d{4,9}/[-._;()/:A-Z0-9]+)', re.IGNORECASE) _QUOTES_REGEX = re.compile(r'"(.*)"') _CNTDISP_REGEX = re.compile(r'filename="(.*)"') class DataverseImportProvider(object): @staticmethod def query_dataverse(search_url): resp = urlopen(search_url).read() data = json.loads(resp.decode('utf-8'))['data'] if data['count_in_response'] != 1: raise ValueError item = data['items'][0] doi = None doi_search = _DOI_REGEX.search(item['dataset_citation']) if doi_search is not None: doi = "doi:" + doi_search.group() # TODO: get a proper protocol return doi @staticmethod def parse_dataset(url): """Extract title, file, doi from Dataverse resource. Handles: {siteURL}/dataset.xhtml?persistentId={persistentId} Handles: {siteURL}/api/datasets/{:id} """ if "persistentId" in url.query: dataset_url = urlunparse( url._replace(path='/api/datasets/:persistentId') ) else: dataset_url = urlunparse(url) resp = urlopen(dataset_url).read() data = json.loads(resp.decode('utf-8')) doi = '{protocol}:{authority}/{identifier}'.format(**data['data']) return doi def parse_file_url(self, url): """Extract title, file, doi from Dataverse resource. Handles: {siteURL}/file.xhtml?persistentId={persistentId}&... {siteURL}/api/access/datafile/:persistentId/?persistentId={persistentId} """ qs = parse_qs(url.query) try: full_doi = qs['persistentId'][0] except (KeyError, ValueError): # fail here in a meaningful way... raise return os.path.dirname(full_doi) def parse_access_url(self, url): """Extract title, file, doi from Dataverse resource. Handles: {siteURL}/api/access/datafile/{fileId} """ fileId = os.path.basename(url.path) search_url = urlunparse( url._replace(path='/api/search', query='q=entityId:' + fileId) ) return self.query_dataverse(search_url) @staticmethod def dataset_full_url(site, doi): return "{scheme}://{netloc}/dataset.xhtml?persistentId={doi}".format( scheme=site.scheme, netloc=site.netloc, doi=doi ) class ytHub(Resource): """Meta resource for yt Hub.""" def __init__(self): super(ytHub, self).__init__() self.resourceName = "ythub" self.route("GET", (), self.get_ythub_url) self.route("GET", (":id", "examples"), self.generateExamples) self.route("GET", (":id", "registry"), self.generate_pooch_registry) self.route("POST", ("genkey",), self.generateRSAKey) self.route("GET", ("dataverse",), self.dataverseExternalTools) @access.admin @autoDescribeRoute(Description("Generate ythub's RSA key")) def generateRSAKey(self, params): rsa_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) pubkey_pem = ( rsa_key.public_key() .public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) .decode("utf8") ) privkey_pem = rsa_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ).decode("utf8") self.model("setting").set(PluginSettings.HUB_PUB_KEY, pubkey_pem) self.model("setting").set(PluginSettings.HUB_PRIV_KEY, privkey_pem) return { PluginSettings.HUB_PUB_KEY: pubkey_pem, PluginSettings.HUB_PRIV_KEY: privkey_pem, } @access.public @autoDescribeRoute(Description("Return url for tmpnb hub.")) def get_ythub_url(self, params): setting = self.model("setting") url = setting.get(PluginSettings.REDIRECT_URL) if not url: url = setting.get(PluginSettings.TMPNB_URL) return {"url": url, "pubkey": setting.get(PluginSettings.HUB_PUB_KEY)} @access.public @autoDescribeRoute( Description("Generate example data page.").modelParam( "id", model="folder", level=AccessType.READ ) ) def generateExamples(self, folder, params): def get_code(resource): try: return resource["meta"]["code"] except KeyError: return "unknown" def sizeof_fmt(num, suffix="B"): for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, "Yi", suffix) def download_path(_id, resource): return "{}/{}/{}/download".format(getApiUrl(), resource, _id) def get_meta(item): try: frontend = "{} frontend".format(item["meta"]["frontend"]) fname, fobj = next(Item().fileList(item, data=False)) entry = { "code": get_code(item), "description": item["meta"]["description"], "filename": fname.rsplit(".", 2)[0], "size": sizeof_fmt(fobj["size"]), "url": download_path(fobj["_id"], "file"), } return frontend, entry except: pass result = {} for ds in Folder().childItems(folder): frontend, entry = get_meta(ds) if frontend not in result: result[frontend] = [] result[frontend].append(entry) return result @access.public @autoDescribeRoute( Description("Generate pooch registry for yt data").modelParam( "id", model="folder", level=AccessType.READ ) ) def generate_pooch_registry(self, folder): def download_path(_id, resource): return "{}/{}/{}/download".format(getApiUrl(), resource, _id) result = {} for item in Folder().childItems(folder): fname, fobj = next(Item().fileList(item, data=False)) result[item["name"]] = { "hash": "sha512:{}".format(fobj["sha512"]), "load_kwargs": item["meta"].get("load_kwargs", {}), "load_name": item["meta"].get("load_name"), "url": download_path(fobj["_id"], "file"), } return result @access.public @autoDescribeRoute( Description("Convert external tools request and bounce it to the BinderHub.") .param( "siteUrl", "The URL of the Dataverse installation that hosts the file " "with the fileId above", required=True, ) .param( "fileId", "The database ID of a file the user clicks 'Explore' on. " "For example, 42. This reserved word is required for file level tools " "unless you use {filePid} instead.", required=False, ) .param( "filePid", "The Persistent ID (DOI or Handle) of a file the user clicks 'Explore' on. " "For example, doi:10.7910/DVN/TJCLKP/3VSTKY. Note that not all installations " "of Dataverse have Persistent IDs (PIDs) enabled at the file level. " "This reserved word is required for file level tools unless " "you use {fileId} instead.", required=False, ) .param( "apiToken", "The Dataverse API token of the user launching the external " "tool, if available. Please note that API tokens should be treated with " "the same care as a password. For example, " "f3465b0c-f830-4bc7-879f-06c0745a5a5c.", required=False, ) .param( "datasetId", "The database ID of the dataset. For example, 42. This reseved word is " "required for dataset level tools unless you use {datasetPid} instead.", required=False, ) .param( "datasetPid", "The Persistent ID (DOI or Handle) of the dataset. " "For example, doi:10.7910/DVN/TJCLKP. This reseved word is " "required for dataset level tools unless you use {datasetId} instead.", required=False, ) .param( "datasetVersion", "The friendly version number ( or :draft ) of the dataset version " "the tool is being launched from. For example, 1.0 or :draft.", required=False, ) .param( "fullDataset", "If True, imports the full dataset that " "contains the file defined by fileId.", dataType="boolean", default=True, required=False, ) .notes("apiToken is currently ignored.") ) def dataverseExternalTools( self, siteUrl, fileId, filePid, apiToken, datasetId, datasetPid, datasetVersion, fullDataset, ): if not validators.url(siteUrl): raise RestException("Not a valid URL: siteUrl") if all(arg is None for arg in (fileId, filePid, datasetId, datasetPid)): raise RestException("No data Id provided") provider = DataverseImportProvider() site = urlparse(siteUrl) if fileId: try: fileId = int(fileId) except (TypeError, ValueError): raise RestException("Invalid fileId (should be integer)") url = "{scheme}://{netloc}/api/access/datafile/{fileId}".format( scheme=site.scheme, netloc=site.netloc, fileId=fileId ) doi = provider.parse_access_url(urlparse(url)) elif datasetId: try: datasetId = int(datasetId) except (TypeError, ValueError): raise RestException("Invalid datasetId (should be integer)") url = "{scheme}://{netloc}/api/datasets/{_id}".format( scheme=site.scheme, netloc=site.netloc, _id=datasetId ) doi = provider.parse_dataset(urlparse(url)) url = provider.dataset_full_url(site, doi) elif filePid: url = "{scheme}://{netloc}/file.xhtml?persistentId={doi}".format( scheme=site.scheme, netloc=site.netloc, doi=filePid ) doi = provider.parse_file_url(urlparse(url)) elif datasetPid: url = provider.dataset_full_url(site, datasetPid) doi = provider.parse_dataset(urlparse(url)) binder_url = os.environ.get("BINDER_URL", "https://mybinder.org/v2/dataverse/") location = os.path.join(binder_url, doi.rsplit(":")[-1]) setResponseHeader("Location", location) cherrypy.response.status = 303
{ "content_hash": "4c6df3f4632604757238bac50303b854", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 90, "avg_line_length": 36.77300613496933, "alnum_prop": 0.570653987320654, "repo_name": "data-exp-lab/girder_ythub", "id": "4ad2c7f082fd66022cf94e76aa7efa405c7c72e5", "size": "12034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/rest/ythub.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CMake", "bytes": "1724" }, { "name": "CSS", "bytes": "1968" }, { "name": "Dockerfile", "bytes": "522" }, { "name": "HTML", "bytes": "8357" }, { "name": "JavaScript", "bytes": "38699" }, { "name": "Python", "bytes": "62943" } ], "symlink_target": "" }
from cloudbaseinit.osutils import base from subprocess import CalledProcessError import subprocess import datetime import os import os.path class FreeBSDUtils(base.BaseOSUtils): def reboot(self): if ( os.system('reboot') != 0 ): raise Exception('Reboot failed') def user_exists(self, username): try: subprocess.check_output(["id", username]) except CalledProcessError: return False return True def create_user(self, username, password, invite_group=None, password_expires=False): """ :param invite_group: it must be a list of string. """ home_dir = '/home/' + username user_shell = '/bin/tcsh' user_comment = 'Created by bsdcloud-init' grouplist = '' assert not invite_group or isinstance(invite_group, list), "param invite_group must be a list." assert invite_group, "invite_group cannot be empty." for i in invite_group: grouplist += i+',' grouplist = grouplist[:-1] pw_cmd = "echo " + password + " | pw useradd -n " + username + " -c '" + user_comment + "' -d '" + home_dir + "' -s /bin/tcsh -h 0 -G " + grouplist subprocess.check_call(pw_cmd, shell=True) subprocess.check_call("mkdir -p %s" % (home_dir), shell=True) self.chown(username, username, home_dir) def set_host_name(self, new_host_name): subprocess.check_call(['hostname', new_host_name]) self._add_rc_conf({'hostname': new_host_name}) def sanitize_shell_input(self, value): pass def set_user_password(self, username, password): pw_cmd = "echo " + password + " | pw usermod -n " + username + " -h 0" subprocess.check_call(pw_cmd, shell=True) def add_user_to_local_group(self, username, groupname): pw_cmd = 'pw usermod ' + username + ' -G ' + groupname subprocess.check_call(pw_cmd, shell=True) def get_user_home(self, username): home_dir = subprocess.check_output('printf ~' + username, shell=True) return home_dir def get_network_adapters(self): """ This fucntion will return a list of interface. """ if_list = subprocess.check_output(['ifconfig', '-l']).split(' ') # Filter out non-network interfaces if_list = filter(lambda x: x.startswith(('pflog', 'lo', 'plip')), if_list) return if_list def set_static_network_config(self, adapter_name, address, netmask, broadcast, gateway, dnsdomain, dnsnameservers): """ :param dnsnameservers: must be a list, it can contain 3 elements at most. """ if_list = self.get_network_adapters() assert adapter_name in if_list, 'Network interface: ' + adapter_name + ' not found.' assert isinstance(dnsnameservers, list), 'dnsnameservers must be a list.' if_cmd = 'ifconfig ' + adapter_name + ' inet ' + address + ' netmask ' + netmask + ' broadcast ' + broadcast route_cmd = 'route add default ' + gateway resolv_conf = ['domain ' + dnsdomain] resolv_conf_file = os.popen('resolvconf -a vtnet0', 'w', 1) for i in dnsnameservers: resolv_conf.append('nameserver ' + i) subprocess.check_call(if_cmd, shell=True) subprocess.check_call(route_cmd, shell=True) self._add_comment(resolv_conf_file); for line in resolv_conf: resolv_conf_file.write(line + '\n') self._add_rc_conf({'ifconfig_' + adapter_name: 'inet ' + address + ' netmask ' + netmask + ' broadcast ' + broadcast, 'defaultrouter': gateway}) resolv_conf_file.close() # should return reboot_required, which is always false. return False def set_dhcp_network_config(self, adapter_name): if_list = self.get_network_adapters() assert adapter_name in if_list, 'Network interface: ' + adapter_name + ' not found.' _add_rc_conf({'ifconfig_' + adapter_name: 'DHCP'}) subprocess.check_call(['dhclient', adapter_name]) def set_config_value(self, name, value, section=None): pass def get_config_value(self, name, section=None): pass def wait_for_boot_completion(self): pass def terminate(self): pass def get_default_gateway(self): """ We cannot handle mutiple default gateway. """ interface = subprocess.check_output("route get default | grep interface", shell=True).split()[1] gateway_ip = subprocess.check_output("route get default | grep gateway", shell=True).split()[1] return (interface, gateway_ip) def check_static_route_exists(self, destination): pass def add_static_route(self, destination, mask, next_hop, interface_index, metric): pass def get_os_version(self): pass def get_volume_label(self, drive): pass def set_timezone(self, timezone, zoneinfo_dir='/usr/share/zoneinfo'): """ :param timezone: The zoneinfo_file path under /usr/share/zoneinfo. e.g: Asia/Taipei Note that this parameter is case-sensitive, because it's the real path under filesystem. """ path = zoneinfo_dir + '/' + timezone assert os.path.isfile(path), 'Time zone file not found: ' + path subprocess.check_call(['cp', path, '/etc/localtime']) subprocess.check_call(['adjkerntz', '-a']) def adj_sys_time(self, ntp_server): """ This function will using 'ntpdate' to sync the clock. param ntp_server: string of server. """ subprocess.check_call(['ntpdate', '-b', ntp_server]) def _add_comment(self, file_obj): file_obj.write('# Generated by bsdcloud-init ' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + '\n') def _add_rc_conf(self, options): """ For appending new options to /etc/rc.conf :param options: an dictionary that contain {'option name': 'value'} e.g. {'hostname': 'example', 'sshd_enable': 'YES'} """ assert isinstance(options, dict), 'param options must be a dictionary.' rc_conf_file = open('/etc/rc.conf', 'a') self._add_comment(rc_conf_file) for key in options: rc_conf_file.write(key + '="' + options[key] + '"\n') rc_conf_file.close() def chown(self, user, group=None, path=None): if path is None: return subprocess.check_call( 'chown -R {user}{group} {path}'.format( user=user, group=':' + group if group else None, path=path, ), shell=True )
{ "content_hash": "468f36eacb1656c34bd7621661baf369", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 155, "avg_line_length": 36.71808510638298, "alnum_prop": 0.5796030711284949, "repo_name": "bincentvaret/bsd-cloudinit", "id": "3ac10e1b39d50a0b543ecb124be896767247d97c", "size": "6903", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "cloudbaseinit/osutils/freebsd.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1055104" } ], "symlink_target": "" }
from unittest import TestCase import math import torch from pose_format.torch.masked.tensor import MaskedTensor from pose_format.torch.representation.point_line_distance import PointLineDistanceRepresentation representation = PointLineDistanceRepresentation() class TestPointLineDistanceRepresentation(TestCase): def test_call_value_should_be_distance(self): p1s = MaskedTensor(torch.tensor([[[[2, 3, 4]]]], dtype=torch.float)) p2s = MaskedTensor(torch.tensor([[[[1, 1, 1]]]], dtype=torch.float)) p3s = MaskedTensor(torch.tensor([[[[3, 4, 2]]]], dtype=torch.float)) distances = representation(p1s, p2s, p3s) self.assertAlmostEqual(float(distances[0][0][0]), math.sqrt(75 / 14), places=6) def test_call_masked_value_should_be_zero(self): mask = torch.tensor([[[[0, 1, 1]]]], dtype=torch.bool) p1s = MaskedTensor(torch.tensor([[[[2, 3, 4]]]], dtype=torch.float), mask) p2s = MaskedTensor(torch.tensor([[[[1, 1, 1]]]], dtype=torch.float)) p3s = MaskedTensor(torch.tensor([[[[3, 4, 2]]]], dtype=torch.float)) distances = representation(p1s, p2s, p3s) self.assertEqual(float(distances[0][0][0]), 0)
{ "content_hash": "7827d46ef0068e312f85d746709e9f52", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 96, "avg_line_length": 46, "alnum_prop": 0.6722408026755853, "repo_name": "AmitMY/pose-format", "id": "3e28ab09a48b2a5a7028de9a074690ba78f1737b", "size": "1196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pose_format/torch/representation/point_line_distance_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "294" }, { "name": "HTML", "bytes": "3186" }, { "name": "Python", "bytes": "167290" }, { "name": "Starlark", "bytes": "10118" }, { "name": "TypeScript", "bytes": "22828" } ], "symlink_target": "" }
""" Functionality for converting Tuskar domain models into their Heat-acceptable formats. These functions are written against the HOT specification found at: http://docs.openstack.org/developer/heat/template_guide/hot_spec.html """ import yaml from tuskar.templates.heat import Resource def compose_template(template): """Converts a template object into its HOT template format. :param template: template object to convert :type template: tuskar.templates.heat.Template :return: HOT template :rtype: str """ parameters = _compose_parameters(template) parameter_groups = _compose_parameter_groups(template) resources = _compose_resources(template) outputs = _compose_outputs(template) template_dict = { 'heat_template_version': template.version, 'parameters': parameters, 'parameter_groups': parameter_groups, 'resources': resources, 'outputs': outputs, } # Remove optional sections if they have no values for x in ('parameters', 'parameter_groups', 'outputs'): if len(template_dict[x]) == 0: template_dict.pop(x) if template.description is not None: template_dict['description'] = template.description content = yaml.safe_dump(template_dict, default_flow_style=False) return content def compose_environment(environment): """Converts an environment object into its HOT template format. :param environment: environment object to convert :type environment: tuskar.templates.heat.Environment :return: HOT template :rtype: str """ parameters = _compose_environment_parameters(environment) registry = _compose_resource_registry(environment) env_dict = { 'parameters': parameters, 'resource_registry': registry } content = yaml.safe_dump(env_dict, default_flow_style=False) return content def _compose_parameters(template): parameters = {} for p in template.parameters: details = { 'type': p.param_type, 'description': p.description, 'default': p.default, 'label': p.label, 'hidden': p.hidden, } details = _strip_missing(details) if len(p.constraints) > 0: details['constraints'] = [] for constraint in p.constraints: constraint_value = { constraint.constraint_type: constraint.definition } if constraint.description is not None: constraint_value['description'] = constraint.description details['constraints'].append(constraint_value) parameters[p.name] = details return parameters def _compose_parameter_groups(template): groups = [] for g in template.parameter_groups: details = { 'label': g.label, 'description': g.description, 'parameters': list(g.parameter_names), # yaml doesn't handle tuple } details = _strip_missing(details) if len(details['parameters']) == 0: details.pop('parameters') groups.append(details) return groups def _compose_resources(template): resources = {} def _generate_details(r): """Converts a resource into its HOT dictionary version. This method will recursively call itself in the event a resource is nested within another as a resource definition. """ d = { 'type': r.resource_type, 'metadata': r.metadata, 'depends_on': r.depends_on, 'update_policy': r.update_policy, 'deletion_policy': r.deletion_policy, } d = _strip_missing(d) # Properties if len(r.properties) > 0: d['properties'] = {} for p in r.properties: if isinstance(p.value, Resource): v = _generate_details(p.value) else: v = p.value d['properties'][p.name] = v return d for resource in template.resources: details = _generate_details(resource) resources[resource.resource_id] = details return resources def _compose_outputs(template): outputs = {} for o in template.outputs: details = { 'description': o.description, 'value': o.value, } details = _strip_missing(details) outputs[o.name] = details return outputs def _compose_environment_parameters(environment): params = dict((p.name, p.value) for p in environment.parameters) return params def _compose_resource_registry(environment): reg = dict((e.alias, e.filename) for e in environment.registry_entries) return reg def _strip_missing(details): """Removes all entries from a dictionary whose value is None. This is used in this context to remove optional attributes that were added to the template creation. :type details: dict :return: new dictionary with the empty attributes removed :rtype: dict """ return dict((k, v) for k, v in details.items() if v is not None)
{ "content_hash": "62fcf3672aeb79faedcb0bef609aef4a", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 79, "avg_line_length": 27.68617021276596, "alnum_prop": 0.6184438040345821, "repo_name": "rdo-management/tuskar", "id": "41864d4cbf82485fa35ebfa36274707ce87e1027", "size": "5746", "binary": false, "copies": "1", "ref": "refs/heads/mgt-master", "path": "tuskar/templates/composer.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "115" }, { "name": "Mako", "bytes": "5046" }, { "name": "Python", "bytes": "564511" }, { "name": "Shell", "bytes": "4469" } ], "symlink_target": "" }
''' With this recipe, you can control pan/tilt and preset of Sony VISCA Color Video Camera. ''' # <!-- parameters param_disabled = Parameter({'desc': 'Disables this node?', 'schema': {'type': 'boolean'}}) param_ipAddress = Parameter({'schema': {'type': 'string'}}) _port = 52381 param_port = Parameter({'schema': {'type': 'integer', 'hint': '(default is %s)' % _port}}) _viscaAddress = 1 param_viscaAddress = Parameter({'schema': {'type': 'integer', 'hint': '(default is %s)' % _viscaAddress}}) def main(): if not param_ipAddress: console.warn('IP address not configured') return if param_port: # 0 is not allowed here global _port _port = param_port if param_viscaAddress != None: # 0 is allowed here global _viscaAddress _viscaAddress = param_viscaAddress target = "%s:%s" % (param_ipAddress, _port) console.info('Will connect to [%s]' % target) udp.setDest(target) resetSequenceNo() def udp_received(src, data): log(2, 'udp_recv %s (from %s)' % (':'.join([b.encode('hex') for b in data]), src)) def udp_sent(data): log(1, 'udp_sent %s' % ':'.join([b.encode('hex') for b in data])) udp = UDP(sent=udp_sent, ready=lambda: console.info('udp_ready'), received=udp_received) def get_command_string(cmd_type, visca_addr, seq_number, data=None): def address_to_hex(addr_number): return chr(0x80 + addr_number) def seq_to_hex(seq_number): hex_str = '' hex_str += chr(seq_number >> 24 & 0xff) hex_str += chr(seq_number >> 16 & 0xff) hex_str += chr(seq_number >> 8 & 0xff) hex_str += chr(seq_number & 0xff) return hex_str def number_to_hex(number): return chr(int(number)) def payload_len_to_hex(payload): payload_len = len(payload) hex_str = '' hex_str += chr(payload_len >> 8 & 0xff) hex_str += chr(payload_len & 0xff) return hex_str msg_header = None msg_payload = None pan_speed = local_event_PanSpeed.getArg() tilt_speed = local_event_TiltSpeed.getArg() if cmd_type == 'up': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x01' + chr(pan_speed) + chr(tilt_speed) + '\x03\x01' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'down': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x01' + chr(pan_speed) + chr(tilt_speed) + '\x03\x02' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'left': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x01' + chr(pan_speed) + chr(tilt_speed) + '\x01\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'right': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x01' + chr(pan_speed) + chr(tilt_speed) + '\x02\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'home': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x04' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'stop': msg_payload = address_to_hex(visca_addr) + '\x01\x06\x01\x05\x05\x03\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'reset_seq': msg_payload = '\x01' msg_header = '\x02\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'preset_reset': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x3f\x00' + number_to_hex(data) + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'preset_set': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x3f\x01' + number_to_hex(data) + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'preset_recall': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x3f\x02' + number_to_hex(data) + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'zoom_stop': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x07\x00' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'zoom_tele': # Standard msg_payload = address_to_hex(visca_addr) + '\x01\x04\x07\x02' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'zoom_wide': # Standard msg_payload = address_to_hex(visca_addr) + '\x01\x04\x07\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'focus_auto': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x38\x02' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'focus_manual': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x38\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'focus_stop': msg_payload = address_to_hex(visca_addr) + '\x01\x04\x08\x00' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'focus_far': # Standard msg_payload = address_to_hex(visca_addr) + '\x01\x04\x08\x02' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) elif cmd_type == 'focus_near': # Standard msg_payload = address_to_hex(visca_addr) + '\x01\x04\x08\x03' + '\xff' msg_header = '\x01\x00' + payload_len_to_hex(msg_payload) + seq_to_hex(seq_number) else: raise Exception('Unsupported command type') return msg_header + msg_payload # --> # <!-- actions def resetSequenceNo(): console.log('[resetSequenceNo] called') ctrlCmd_reset_seq = get_command_string('reset_seq', _viscaAddress, next_seq() + 20000) udp.send(ctrlCmd_reset_seq) # -- drive related -- INIT_PAN_SPEED = 5 # initial values INIT_TILT_SPEED = 5 local_event_PanSpeed = LocalEvent({ 'group': 'PTZ Drive', 'title': 'Pan Speed', 'schema': { 'type': 'integer', 'format': 'range', 'min': 1, 'max': 24 }, 'order': next_seq() }) local_event_TiltSpeed = LocalEvent({ 'group': 'PTZ Drive', 'title': 'Tilt Speed', 'schema': { 'type': 'integer', 'format': 'range', 'min': 1, 'max': 24 }, 'order': next_seq() }) @before_main def initPanAndTiltSpeeds(): panSpeedArg = local_event_PanSpeed.getArg() if panSpeedArg < 1 or panSpeedArg > 24: local_event_PanSpeed.emit(INIT_PAN_SPEED) tiltSpeedArg = local_event_TiltSpeed.getArg() if tiltSpeedArg < 1 or tiltSpeedArg > 24: local_event_TiltSpeed.emit(INIT_TILT_SPEED) @local_action({'group': 'PTZ Drive', 'title': 'Pan Speed', 'schema': { 'type': 'integer', 'hint': '(default: 5, Min: 1, Max: 24)', 'format': 'range', 'min': 1, 'max': 24 }, 'order': next_seq() }) def PanSpeed(arg): if arg < 1 or arg > 24: return console.warn('[set_pan_speed] bad arg - %s' % arg) iArg = int(arg) console.log('[set_pan_speed] %s' % iArg) local_event_PanSpeed.emit(iArg) @local_action({'group': 'PTZ Drive', 'title': 'Tilt Speed', 'schema': { 'type': 'integer', 'hint': '(default: 5, Min: 1, Max: 24)', 'format': 'range', 'min': 1, 'max': 24}, 'order': next_seq() }) def TiltSpeed(arg): if arg < 1 or arg > 24: return console.warn('[set_tilt_speed] bad arg - %s' % arg) iArg = int(arg) console.log('[set_tilt_speed] %s' % iArg) local_event_TiltSpeed.emit(iArg) @local_action({'group': 'PTZ Drive', 'title': 'Home', 'order': next_seq()}) def ptz_home(ignore): console.log('[ptz_home] called') inquery_ptdHome = get_command_string('home', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdHome) @local_action({'group': 'PTZ Drive', 'title': 'Up', 'order': next_seq()}) def ptz_up(data): console.log('[ptz_up] called') inquery_ptdUp = get_command_string('up', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdUp) @local_action({'group': 'PTZ Drive', 'title': 'Down', 'order': next_seq()}) def ptz_down(data): console.log('[ptz_down] called') inquery_ptdDown = get_command_string('down', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdDown) @local_action({'group': 'PTZ Drive', 'title': 'Left', 'order': next_seq()}) def ptz_left(data): console.log('[ptz_left] called') inquery_ptdLeft = get_command_string('left', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdLeft) @local_action({'group': 'PTZ Drive', 'title': 'Right', 'order': next_seq()}) def ptz_right(data): console.log('[ptz_right] called') inquery_ptdRight = get_command_string('right', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdRight) @local_action({'group': 'PTZ Drive', 'title': 'Stop', 'order': next_seq()}) def ptz_stop(data): console.log('[ptz_stop] called') inquery_ptdStop = get_command_string('stop', _viscaAddress, next_seq() + 20000) udp.send(inquery_ptdStop) # -- preset related -- @local_action({'group': 'PTZ Preset', 'title': 'Preset Reset', 'order': next_seq(), 'schema': {'type': 'integer'}}) def ptz_preset_reset(data): console.log('[ptz_preset_reset] called') inquery_presetReset = get_command_string('preset_reset', _viscaAddress, next_seq() + 20000, data) udp.send(inquery_presetReset) @local_action({'group': 'PTZ Preset', 'title': 'Preset Set', 'order': next_seq(), 'schema': {'type': 'integer'}}) def ptz_preset_set(data): console.log('[ptz_preset_set] called') inquery_presetSet = get_command_string('preset_set', _viscaAddress, next_seq() + 20000, data) udp.send(inquery_presetSet) @local_action({'group': 'PTZ Preset', 'title': 'Preset Recall', 'order': next_seq(), 'schema': {'type': 'integer'}}) def ptz_preset_recall(arg): console.log('[ptz_preset_recall] called') inquery_presetRecall = get_command_string('preset_recall', _viscaAddress, next_seq() + 20000, arg) udp.send(inquery_presetRecall) # -- Zoom related -- @local_action({'group': 'PTZ Zoom', 'title': 'Zoom Stop', 'order': next_seq()}) def ptz_zoom_stop(arg): console.log('[ptz_zoom_stop] called') inquery_zoomStop = get_command_string('zoom_stop', _viscaAddress, next_seq() + 20000) udp.send(inquery_zoomStop) @local_action({'group': 'PTZ Zoom', 'title': 'Zoom Tele', 'order': next_seq()}) def ptz_zoom_tele(arg): console.log('[ptz_zoom_tele] called') inquery_zoomTele = get_command_string('zoom_tele', _viscaAddress, next_seq() + 20000) udp.send(inquery_zoomTele) @local_action({'group': 'PTZ Zoom', 'title': 'Zoom Wide', 'order': next_seq()}) def ptz_zoom_wide(arg): console.log('[ptz_zoom_wide] called') inquery_zoomWide = get_command_string('zoom_wide', _viscaAddress, next_seq() + 20000) udp.send(inquery_zoomWide) # -- Focus related -- le_Focus_Mode = create_local_event( 'Focus Mode', metadata={ 'title': 'Focus Mode', 'group': 'PTZ Focus', 'order': next_seq(), 'schema': { 'type': 'string' } } ) @local_action({'group': 'PTZ Focus', 'title': 'Focus Mode - Auto', 'order': next_seq()}) def ptz_focus_mode_auto(arg): console.log('[ptz_focus_mode_auto] called') inquery_focusModeAuto = get_command_string('focus_auto', _viscaAddress, next_seq() + 20000) udp.send(inquery_focusModeAuto) le_Focus_Mode.emit('AUTO') @local_action({'group': 'PTZ Focus', 'title': 'Focus Mode - Manual', 'order': next_seq()}) def ptz_focus_mode_manual(arg): console.log('[ptz_focus_mode_manual] called') inquery_focusModeManual = get_command_string('focus_manual', _viscaAddress, next_seq() + 20000) udp.send(inquery_focusModeManual) le_Focus_Mode.emit('MANUAL') @local_action({'group': 'PTZ Focus', 'title': 'Focus - Stop', 'order': next_seq()}) def ptz_focus_stop(arg): console.log('[ptz_focus_stop] called') inquery_focusStop = get_command_string('focus_stop', _viscaAddress, next_seq() + 20000) udp.send(inquery_focusStop) @local_action({'group': 'PTZ Focus', 'title': 'Focus - Far', 'order': next_seq()}) def ptz_focus_far(arg): console.log('[ptz_focus_far] called') inquery_focusFar = get_command_string('focus_far', _viscaAddress, next_seq() + 20000) udp.send(inquery_focusFar) @local_action({'group': 'PTZ Focus', 'title': 'Focus - Near', 'order': next_seq()}) def ptz_focus_near(arg): console.log('[ptz_focus_near] called') inquery_focusNear = get_command_string('focus_near', _viscaAddress, next_seq() + 20000) udp.send(inquery_focusNear) @local_action({'group': 'Status', 'order': next_seq()}) def httpPoll(): # look for this token if result to be sure TOKEN = 'birddog_p200.png' url = 'http://%s/login' % param_ipAddress try: log(2, 'httpPoll %s' % url) resp = get_url(url, connectTimeout=5) if TOKEN not in resp: console.warn('unexpected response! did not find token [%s] in response from %s' % (TOKEN, url)) return global _lastReceive _lastReceive = system_clock() except: log(1, 'problem polling %s' % url) timer_poller = Timer(lambda: httpPoll.call(), 30, 5) # every 30s, first after 5 # --> # <!-- status local_event_Status = LocalEvent({'title': 'Status', 'group': 'Status', 'order': 9990, "schema": { 'title': 'Status', 'type': 'object', 'properties': { 'level': {'title': 'Level', 'order': 1, 'type': 'integer'}, 'message': {'title': 'Message', 'order': 2, 'type': 'string'} } } }) _lastReceive = 0 # last valid comms, system_clock() based # roughly, the last contact local_event_LastContactDetect = LocalEvent({'group': 'Status', 'title': 'Last contact detect', 'schema': {'type': 'string'}}) def statusCheck(): diff = (system_clock() - _lastReceive)/1000.0 # (in secs) now = date_now() if diff > status_check_interval+15: previousContactValue = local_event_LastContactDetect.getArg() if previousContactValue == None: message = 'Never seen' else: previousContact = date_parse(previousContactValue) message = 'Missing %s' % formatPeriod(previousContact) local_event_Status.emit({'level': 2, 'message': message}) return local_event_Status.emit({'level': 0, 'message': 'OK'}) local_event_LastContactDetect.emit(str(now)) status_check_interval = 75 timer_statusCheck = Timer(statusCheck, status_check_interval) def formatPeriod(dateObj): if dateObj == None: return 'for unknown period' now = date_now() diff = (now.getMillis() - dateObj.getMillis()) / 1000 / 60 # in mins if diff == 0: return 'for <1 min' elif diff < 60: return 'for <%s mins' % diff elif diff < 60*24: return 'since %s' % dateObj.toString('h:mm:ss a') else: return 'since %s' % dateObj.toString('E d-MMM h:mm:ss a') # status --> # <!-- logging local_event_LogLevel = LocalEvent({ 'group': 'Debug', 'order': 10000 + next_seq(), 'desc': 'Use this to ramp up the logging (with indentation)', 'schema': {'type': 'integer'} }) def warn(level, msg): if local_event_LogLevel.getArg() >= level: console.warn((' ' * level) + msg) def log(level, msg): if local_event_LogLevel.getArg() >= level: console.log((' ' * level) + msg) # --!>
{ "content_hash": "c657c53746503e9bddea4095c0a8058f", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 195, "avg_line_length": 39.6175, "alnum_prop": 0.6134915125891336, "repo_name": "museumsvictoria/nodel-recipes", "id": "e6ecff140c3a3fd45381b8626ff49f3ae0a2d206", "size": "15847", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Sony VISCA Color Video Camera/script.py", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "23083" }, { "name": "CSS", "bytes": "203723" }, { "name": "HTML", "bytes": "22272" }, { "name": "JavaScript", "bytes": "1186857" }, { "name": "Python", "bytes": "1695766" }, { "name": "XSLT", "bytes": "45475" } ], "symlink_target": "" }
__author__ = 'scooper' import sys import os import glob import re import shlex from voltcli import utility re_voltdb_jar = re.compile('^voltdb(client)?-[.0-9]+[.]jar$') # Filled in during startup. standalone = None version = None command_dir = None command_name = None voltdb_jar = None classpath = None # Assume that we're in a subdirectory of the main volt Python library # directory. Add the containing library directory to the Python module load # path so that verb modules can import any module here. E.g.: # from voltcli import <module>... volt_python = os.path.dirname(os.path.dirname(__file__)) if volt_python not in sys.path: sys.path.insert(0, volt_python) # Java configuration if 'JAVA_HOME' in os.environ: java = os.path.join(os.environ['JAVA_HOME'], 'bin', 'java') else: java = utility.find_in_path('java') if not java: utility.abort('Could not find java in environment, set JAVA_HOME or put java in the path.') java_opts = [] if 'JAVA_HEAP_MAX' in os.environ: java_opts.append(os.environ.get('JAVA_HEAP_MAX')) if 'VOLTDB_OPTS' in os.environ: java_opts.extend(shlex.split(os.environ['VOLTDB_OPTS'])) if 'JAVA_OPTS' in os.environ: java_opts.extend(shlex.split(os.environ['JAVA_OPTS'])) if not [opt for opt in java_opts if opt.startswith('-Xmx')]: java_opts.append('-Xmx1024m') def initialize(standalone_arg, command_name_arg, command_dir_arg, version_arg): """ Set the VOLTDB_LIB and VOLTDB_VOLTDB environment variables based on the script location and the working directory. """ global command_name, command_dir, version command_name = command_name_arg command_dir = command_dir_arg version = version_arg # Stand-alone scripts don't need a develoopment environment. global standalone standalone = standalone_arg if standalone: return # Add the working directory, the command directory, and VOLTCORE as # starting points for the scan. dirs = [] def add_dir(dir): if dir and os.path.isdir(dir) and dir not in dirs: dirs.append(os.path.realpath(dir)) add_dir(os.getcwd()) add_dir(command_dir) add_dir(os.environ.get('VOLTCORE', None)) utility.verbose_info('Base directories for scan:', dirs) lib_search_globs = [] voltdb_search_globs = [] for dir in dirs: # Crawl upward and look for the lib and voltdb directories. # They may be the same directory when installed by a Linux installer. # Set the VOLTDB_... environment variables accordingly. # Also locate the voltdb jar file. global voltdb_jar while (dir and dir != '/' and ('VOLTDB_LIB' not in os.environ or not voltdb_jar)): utility.debug('Checking potential VoltDB root directory: %s' % os.path.realpath(dir)) # Try to set VOLTDB_LIB if not set. if not os.environ.get('VOLTDB_LIB', ''): for subdir in ('lib', os.path.join('lib', 'voltdb')): glob_chk = os.path.join(os.path.realpath(os.path.join(dir, subdir)), 'zmq*.jar') lib_search_globs.append(glob_chk) if glob.glob(glob_chk): os.environ['VOLTDB_LIB'] = os.path.join(dir, subdir) utility.debug('VOLTDB_LIB=>%s' % os.environ['VOLTDB_LIB']) # Try to set VOLTDB_VOLTDB if not set. Look for the voltdb jar file. if not os.environ.get('VOLTDB_VOLTDB', '') or voltdb_jar is None: for subdir in ('voltdb', os.path.join('lib', 'voltdb')): # Need the hyphen to avoid the volt client jar. glob_chk = os.path.join(os.path.realpath(os.path.join(dir, subdir)), 'voltdb-*.jar') voltdb_search_globs.append(glob_chk) for voltdb_jar_chk in glob.glob(glob_chk): if re_voltdb_jar.match(os.path.basename(voltdb_jar_chk)): voltdb_jar = os.path.realpath(voltdb_jar_chk) utility.debug('VoltDB jar: %s' % voltdb_jar) if not os.environ.get('VOLTDB_VOLTDB', ''): os.environ['VOLTDB_VOLTDB'] = os.path.dirname(voltdb_jar) utility.debug('VOLTDB_VOLTDB=>%s' % os.environ['VOLTDB_VOLTDB']) dir = os.path.dirname(dir) # If the VoltDB jar was found then VOLTDB_VOLTDB will also be set. if voltdb_jar is None: utility.abort('Failed to find the VoltDB jar file.', ('You may need to perform a build.', 'Searched the following:', voltdb_search_globs)) if not os.environ.get('VOLTDB_LIB', ''): utility.abort('Failed to find the VoltDB library directory.', ('You may need to perform a build.', 'Searched the following:', lib_search_globs)) # LOG4J configuration if 'LOG4J_CONFIG_PATH' not in os.environ: for chk_dir in ('$VOLTDB_LIB/../src/frontend', '$VOLTDB_VOLTDB'): path = os.path.join(os.path.realpath(os.path.expandvars(chk_dir)), 'log4j.xml') if os.path.exists(path): os.environ['LOG4J_CONFIG_PATH'] = path utility.debug('LOG4J_CONFIG_PATH=>%s' % os.environ['LOG4J_CONFIG_PATH']) break else: utility.abort('Could not find log4j configuration file or LOG4J_CONFIG_PATH variable.') for var in ('VOLTDB_LIB', 'VOLTDB_VOLTDB', 'LOG4J_CONFIG_PATH'): utility.verbose_info('Environment: %s=%s' % (var, os.environ[var])) # Classpath is the voltdb jar and all the jars in VOLTDB_LIB, and if present, # any user supplied jars under VOLTDB/lib/extension global classpath classpath = [voltdb_jar] for path in glob.glob(os.path.join(os.environ['VOLTDB_LIB'], '*.jar')): classpath.append(path) for path in glob.glob(os.path.join(os.environ['VOLTDB_LIB'], 'extension', '*.jar')): classpath.append(path) utility.verbose_info('Classpath: %s' % ':'.join(classpath))
{ "content_hash": "34eb0f18c87d8f9ad41b3d7474920860", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 99, "avg_line_length": 42.855172413793106, "alnum_prop": 0.6037978757644029, "repo_name": "vtorshyn/voltdb-shardit-src", "id": "f377f574e13a2fff541a560853861ba8031f7f0d", "size": "7562", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "voltdb-3.7/lib/python/voltcli/environment.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "88927" }, { "name": "C++", "bytes": "813140" }, { "name": "CSS", "bytes": "32753" }, { "name": "Java", "bytes": "373018" }, { "name": "JavaScript", "bytes": "126719" }, { "name": "Python", "bytes": "229261" }, { "name": "Shell", "bytes": "47675" } ], "symlink_target": "" }
import arcpy from arcpy import env # Set environment settings env.workspace = "C:\Users\Ewan\Desktop\SFTPDST5\MapFiles" try: # Set the local variable in_Table = "Topography.csv" x_coords = "x" y_coords = "y" out_Layer = "Topography_Layer" saved_Layer = "c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\Topography.lyr" # Set the spatial reference spRef = r"Coordinate Systems\Geographic Coordinate Systens\World\WGS 1984.prj" # Make the XY Event Layer arcpy.MakeXYEventLayer_management(in_Table, x_coords, y_coords, out_Layer, spRef) # Save to a layer file arcpy.SaveToLayerFile_management(out_Layer, saved_Layer) except Exception as err: print(err.args[0]) # Set local variables inFeatures = "Topography.lyr" valField = "Topography" outRaster = "C:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\TopographyR" assignmentType = "MOST_FREQUENT" priorityField = "" cellSize = 0.000005 # Execute PointToRaster arcpy.PointToRaster_conversion(inFeatures, valField, outRaster, assignmentType, priorityField, cellSize) ##Assign colormap using clr file arcpy.AddColormap_management("c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\TopographyR", "#", "c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\colormap.clr")
{ "content_hash": "00fb9c7f23342a0b4483ba2f60652901", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 144, "avg_line_length": 31.8, "alnum_prop": 0.720125786163522, "repo_name": "harryfb/DST5", "id": "7b6dc04605dc68fc2fa8829afd9dadd74280c59e", "size": "1297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ArcPy Code/Topography.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "368717" }, { "name": "Python", "bytes": "48833" }, { "name": "Shell", "bytes": "126" } ], "symlink_target": "" }
""" Pygments regex lexer tests ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import time import unittest from pygments.token import String from pygments.lexers.perl import PerlLexer class RunawayRegexTest(unittest.TestCase): # A previous version of the Perl lexer would spend a great deal of # time backtracking when given particular strings. These tests show that # the runaway backtracking doesn't happen any more (at least for the given # cases). lexer = PerlLexer() ### Test helpers. def assert_single_token(self, s, token): """Show that a given string generates only one token.""" tokens = list(self.lexer.get_tokens_unprocessed(s)) self.assertEqual(len(tokens), 1, tokens) self.assertEqual(s, tokens[0][2]) self.assertEqual(token, tokens[0][1]) def assert_tokens(self, strings, expected_tokens): """Show that a given string generates the expected tokens.""" tokens = list(self.lexer.get_tokens_unprocessed(''.join(strings))) self.assertEqual(len(tokens), len(expected_tokens), tokens) for index, s in enumerate(strings): self.assertEqual(s, tokens[index][2]) self.assertEqual(expected_tokens[index], tokens[index][1]) def assert_fast_tokenization(self, s): """Show that a given string is tokenized quickly.""" start = time.time() tokens = list(self.lexer.get_tokens_unprocessed(s)) end = time.time() # Isn't 10 seconds kind of a long time? Yes, but we don't want false # positives when the tests are starved for CPU time. if end-start > 10: self.fail('tokenization took too long') return tokens ### Strings. def test_single_quote_strings(self): self.assert_single_token(r"'foo\tbar\\\'baz'", String) self.assert_fast_tokenization("'" + '\\'*999) def test_double_quote_strings(self): self.assert_single_token(r'"foo\tbar\\\"baz"', String) self.assert_fast_tokenization('"' + '\\'*999) def test_backtick_strings(self): self.assert_single_token(r'`foo\tbar\\\`baz`', String.Backtick) self.assert_fast_tokenization('`' + '\\'*999) ### Regex matches with various delimiters. def test_match(self): self.assert_single_token(r'/aa\tbb/', String.Regex) self.assert_fast_tokenization('/' + '\\'*999) def test_match_with_slash(self): self.assert_tokens(['m', '/\n\\t\\\\/'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m/xxx\n' + '\\'*999) def test_match_with_bang(self): self.assert_tokens(['m', r'!aa\t\!bb!'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m!' + '\\'*999) def test_match_with_brace(self): self.assert_tokens(['m', r'{aa\t\}bb}'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m{' + '\\'*999) def test_match_with_angle_brackets(self): self.assert_tokens(['m', r'<aa\t\>bb>'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m<' + '\\'*999) def test_match_with_parenthesis(self): self.assert_tokens(['m', r'(aa\t\)bb)'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m(' + '\\'*999) def test_match_with_at_sign(self): self.assert_tokens(['m', r'@aa\t\@bb@'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m@' + '\\'*999) def test_match_with_percent_sign(self): self.assert_tokens(['m', r'%aa\t\%bb%'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m%' + '\\'*999) def test_match_with_dollar_sign(self): self.assert_tokens(['m', r'$aa\t\$bb$'], [String.Regex, String.Regex]) self.assert_fast_tokenization('m$' + '\\'*999) ### Regex substitutions with various delimeters. def test_substitution_with_slash(self): self.assert_single_token('s/aaa/bbb/g', String.Regex) self.assert_fast_tokenization('s/foo/' + '\\'*999) def test_substitution_with_at_sign(self): self.assert_single_token(r's@aaa@bbb@g', String.Regex) self.assert_fast_tokenization('s@foo@' + '\\'*999) def test_substitution_with_percent_sign(self): self.assert_single_token(r's%aaa%bbb%g', String.Regex) self.assert_fast_tokenization('s%foo%' + '\\'*999) def test_substitution_with_brace(self): self.assert_single_token(r's{aaa}', String.Regex) self.assert_fast_tokenization('s{' + '\\'*999) def test_substitution_with_angle_bracket(self): self.assert_single_token(r's<aaa>', String.Regex) self.assert_fast_tokenization('s<' + '\\'*999) def test_substitution_with_angle_bracket(self): self.assert_single_token(r's<aaa>', String.Regex) self.assert_fast_tokenization('s<' + '\\'*999) def test_substitution_with_square_bracket(self): self.assert_single_token(r's[aaa]', String.Regex) self.assert_fast_tokenization('s[' + '\\'*999) def test_substitution_with_parenthesis(self): self.assert_single_token(r's(aaa)', String.Regex) self.assert_fast_tokenization('s(' + '\\'*999)
{ "content_hash": "3f6c3a962fdd5f0cb6d0825e62d52cf1", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 78, "avg_line_length": 39.05882352941177, "alnum_prop": 0.6242469879518072, "repo_name": "zmughal/pygments-mirror", "id": "26b2d0a71e37c1fe0d6c18342772bc9d8bfe87e4", "size": "5336", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tests/test_perllexer.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "APL", "bytes": "587" }, { "name": "ASP", "bytes": "636" }, { "name": "ActionScript", "bytes": "5686" }, { "name": "Ada", "bytes": "5145" }, { "name": "Agda", "bytes": "3154" }, { "name": "Alloy", "bytes": "6579" }, { "name": "AppleScript", "bytes": "421" }, { "name": "Assembly", "bytes": "3294" }, { "name": "AutoHotkey", "bytes": "3733" }, { "name": "AutoIt", "bytes": "692" }, { "name": "Awk", "bytes": "4528" }, { "name": "BlitzBasic", "bytes": "1824" }, { "name": "BlitzMax", "bytes": "2387" }, { "name": "Boo", "bytes": "1111" }, { "name": "Bro", "bytes": "7337" }, { "name": "C", "bytes": "109073" }, { "name": "C#", "bytes": "17784" }, { "name": "C++", "bytes": "79372" }, { "name": "COBOL", "bytes": "117432" }, { "name": "CSS", "bytes": "14802" }, { "name": "Ceylon", "bytes": "1387" }, { "name": "Chapel", "bytes": "4366" }, { "name": "Cirru", "bytes": "2574" }, { "name": "Clean", "bytes": "2878" }, { "name": "Clojure", "bytes": "23871" }, { "name": "CoffeeScript", "bytes": "20149" }, { "name": "ColdFusion", "bytes": "9263" }, { "name": "Common Lisp", "bytes": "49017" }, { "name": "Coq", "bytes": "66" }, { "name": "Cuda", "bytes": "776" }, { "name": "D", "bytes": "5475" }, { "name": "Dart", "bytes": "591" }, { "name": "Dylan", "bytes": "6343" }, { "name": "Ecl", "bytes": "2599" }, { "name": "Eiffel", "bytes": "2145" }, { "name": "Elixir", "bytes": "4340" }, { "name": "Erlang", "bytes": "5746" }, { "name": "F#", "bytes": "19734" }, { "name": "FORTRAN", "bytes": "27879" }, { "name": "Factor", "bytes": "10194" }, { "name": "Fancy", "bytes": "2581" }, { "name": "Fantom", "bytes": "25331" }, { "name": "GAP", "bytes": "15760" }, { "name": "Gnuplot", "bytes": "10376" }, { "name": "Go", "bytes": "172" }, { "name": "Golo", "bytes": "1649" }, { "name": "Gosu", "bytes": "2853" }, { "name": "Groovy", "bytes": "2586" }, { "name": "Haskell", "bytes": "49593" }, { "name": "Haxe", "bytes": "16812" }, { "name": "Hy", "bytes": "7237" }, { "name": "IDL", "bytes": "2098" }, { "name": "Idris", "bytes": "2771" }, { "name": "Inform 7", "bytes": "2046" }, { "name": "Ioke", "bytes": "469" }, { "name": "Isabelle", "bytes": "21392" }, { "name": "Jasmin", "bytes": "9428" }, { "name": "Java", "bytes": "81613" }, { "name": "JavaScript", "bytes": "1453" }, { "name": "Julia", "bytes": "27687" }, { "name": "Kotlin", "bytes": "971" }, { "name": "LSL", "bytes": "160" }, { "name": "Lasso", "bytes": "18650" }, { "name": "LiveScript", "bytes": "972" }, { "name": "Logos", "bytes": "306" }, { "name": "Logtalk", "bytes": "7260" }, { "name": "Lua", "bytes": "8677" }, { "name": "Makefile", "bytes": "65407" }, { "name": "Mathematica", "bytes": "191" }, { "name": "Modelica", "bytes": "6213" }, { "name": "Monkey", "bytes": "2587" }, { "name": "Moocode", "bytes": "3343" }, { "name": "MoonScript", "bytes": "14862" }, { "name": "Nemerle", "bytes": "1517" }, { "name": "NewLisp", "bytes": "42726" }, { "name": "Nimrod", "bytes": "37191" }, { "name": "Nit", "bytes": "55581" }, { "name": "Nix", "bytes": "2448" }, { "name": "OCaml", "bytes": "42416" }, { "name": "Objective-C", "bytes": "3385" }, { "name": "Objective-J", "bytes": "15340" }, { "name": "Opa", "bytes": "172" }, { "name": "OpenEdge ABL", "bytes": "318" }, { "name": "PAWN", "bytes": "6555" }, { "name": "PHP", "bytes": "17354" }, { "name": "Pan", "bytes": "1241" }, { "name": "Pascal", "bytes": "84519" }, { "name": "Perl", "bytes": "2714" }, { "name": "Perl6", "bytes": "49676" }, { "name": "PigLatin", "bytes": "6657" }, { "name": "Pike", "bytes": "8479" }, { "name": "PowerShell", "bytes": "6127" }, { "name": "Prolog", "bytes": "738" }, { "name": "Puppet", "bytes": "130" }, { "name": "Python", "bytes": "2624129" }, { "name": "R", "bytes": "4057" }, { "name": "Racket", "bytes": "11341" }, { "name": "Rebol", "bytes": "1887" }, { "name": "Red", "bytes": "10792" }, { "name": "Ruby", "bytes": "91403" }, { "name": "Rust", "bytes": "6788" }, { "name": "Scala", "bytes": "730" }, { "name": "Scheme", "bytes": "46097" }, { "name": "Scilab", "bytes": "943" }, { "name": "Shell", "bytes": "118660" }, { "name": "ShellSession", "bytes": "320" }, { "name": "Smalltalk", "bytes": "156665" }, { "name": "SourcePawn", "bytes": "130" }, { "name": "Standard ML", "bytes": "36869" }, { "name": "Swift", "bytes": "2035" }, { "name": "SystemVerilog", "bytes": "265" }, { "name": "TypeScript", "bytes": "535" }, { "name": "VHDL", "bytes": "4446" }, { "name": "VimL", "bytes": "16922" }, { "name": "Visual Basic", "bytes": "17210" }, { "name": "XQuery", "bytes": "4289" }, { "name": "XSLT", "bytes": "755" }, { "name": "Xtend", "bytes": "727" }, { "name": "Zephir", "bytes": "485" }, { "name": "eC", "bytes": "26388" }, { "name": "nesC", "bytes": "23697" }, { "name": "xBase", "bytes": "3349" } ], "symlink_target": "" }
"""The definitions.""" DATA_TYPE_BOOLEAN = 'boolean' DATA_TYPE_BINARY_DATA = 'binary_data' DATA_TYPE_DOUBLE = 'double' DATA_TYPE_FAT_DATE_TIME = 'fat_date_time' DATA_TYPE_FILETIME = 'filetime' DATA_TYPE_FLOAT = 'float' DATA_TYPE_FLOATINGTIME = 'floatingtime' DATA_TYPE_HFS_TIME = 'hfs_time' DATA_TYPE_GUID = 'guid' DATA_TYPE_INT = 'int' DATA_TYPE_INT32 = 'int32' DATA_TYPE_NARROW_STRING = 'narrow_string' DATA_TYPE_NONE = 'none' DATA_TYPE_OBJECT = 'object' DATA_TYPE_OFF64 = 'off64' DATA_TYPE_POSIX_TIME = 'posix_time' DATA_TYPE_SIZE32 = 'size32' DATA_TYPE_SIZE64 = 'size64' DATA_TYPE_STRING = 'string' DATA_TYPE_UINT8 = 'uint8' DATA_TYPE_UINT16 = 'uint16' DATA_TYPE_UINT32 = 'uint32' DATA_TYPE_UINT64 = 'uint64' DATA_TYPE_UUID = 'uuid' FUNCTION_TYPE_CLOSE = 'close' FUNCTION_TYPE_COPY = 'copy' FUNCTION_TYPE_COPY_FROM = 'copy_from' FUNCTION_TYPE_COPY_TO = 'copy_to' FUNCTION_TYPE_FREE = 'free' FUNCTION_TYPE_GET = 'get' FUNCTION_TYPE_GET_BY_INDEX = 'get_by_index' FUNCTION_TYPE_GET_BY_IDENTIFIER = 'get_by_identifier' FUNCTION_TYPE_GET_BY_NAME = 'get_by_name' FUNCTION_TYPE_GET_BY_PATH = 'get_by_path' FUNCTION_TYPE_INITIALIZE = 'initialize' FUNCTION_TYPE_IS = 'is' FUNCTION_TYPE_OPEN = 'open' FUNCTION_TYPE_READ = 'read' FUNCTION_TYPE_SEEK = 'seek' FUNCTION_TYPE_SET = 'set' FUNCTION_TYPE_UTILITY = 'utility' FUNCTION_TYPE_WRITE = 'write'
{ "content_hash": "15790e88cdda0bc90a974669e21a63a8", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 53, "avg_line_length": 29.217391304347824, "alnum_prop": 0.7172619047619048, "repo_name": "libyal/libyal", "id": "cca475a0f1db09cd3099ae3d9181b8fd8152afaf", "size": "1368", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "yaldevtools/definitions.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1616472" }, { "name": "M4", "bytes": "435083" }, { "name": "Makefile", "bytes": "7291" }, { "name": "PowerShell", "bytes": "37768" }, { "name": "Python", "bytes": "912826" }, { "name": "Shell", "bytes": "87438" } ], "symlink_target": "" }
""" Test model using model engine, this model has two int values and a boolean value """ from mongoengine import Document, IntField, BooleanField class ModelOne(Document): """ A sample model class """ int_value1 = IntField() int_value2 = IntField() boolean_value = BooleanField(required=True, default=False) @classmethod def get_model_one_by_value1(cls, value): """Class method to get objects by value one """ return cls.objects(int_value1=value) @classmethod def get_model_one_by_boolean_value(cls, value): """Class method to get objects by boolean value """ return cls.objects(boolean_value=value)
{ "content_hash": "42454df5d1c04a77e24697f4ff1067e4", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 64, "avg_line_length": 29.08695652173913, "alnum_prop": 0.680119581464873, "repo_name": "mbanton/nose-mongoengine", "id": "b4ec5980456b165f8d8682abe030ec1801735e40", "size": "688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/model_one.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "13153" } ], "symlink_target": "" }
import numpy as np import matplotlib.pyplot as plt import pyart cmap_list = ["pyart_" + m for m in pyart.graph.cm.datad if not m.endswith("_r")] nrows = len(cmap_list) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) # borrows from colormaps_reference matplotlib example fig, axes = plt.subplots(nrows=nrows, figsize=(8, 8)) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) axes[0].set_title('Py-ART colormaps', fontsize=14) axl = [] for ax, name in zip(axes, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) axl.append((ax, name)) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() for ax, name in axl: extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) fig.savefig( 'artview/icons/colormaps/%s.png' % name, dpi=20, bbox_inches=extent) fig.show()
{ "content_hash": "691127081eb579a3d36826959700a250", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 79, "avg_line_length": 31.742857142857144, "alnum_prop": 0.6642664266426642, "repo_name": "nguy/artview", "id": "cf2dbd461849a85e2910485765e4a5942c884d0e", "size": "1111", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "reprint_colormaps.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "626745" } ], "symlink_target": "" }
import json import os from manager import OVERWATCH_DIR from pyow.casc import CASCManager from pyow.dll_loader import load_dll import time load_dll() # noinspection PyUnresolvedReferences from PyOWLib import Utils # noinspection PyUnresolvedReferences from System.Collections.Generic import Dictionary if __name__ == '__main__': man = CASCManager(OVERWATCH_DIR) # inp = Dictionary[str, str]() # inp['hello'] = 'world' with open('versions\\1.13.0.0.38215\\data.json') as data: j_data = json.load(data) with open('versions\\1.13.0.0.38170\\data.json') as data2: j_data_last = json.load(data2) extract_jobs = ['004', '04D', '03F', '0B2', '07C', '0A9'] good_raw_this_list = [] good_raw_last = set() for job in extract_jobs: good_raw_this_list.extend(man.get_files_by_pattern('*.{}'.format(job))) for f_type in j_data_last['good_raw']: for file in j_data_last['good_raw'][f_type]: good_raw_last.add(os.path.normpath(file)) preexisting_files_set = set(good_raw_this_list) & good_raw_last mod_vers = j_data_last['all_raw'] inp = Dictionary[str, str]() for x in preexisting_files_set: inp[x] = mod_vers[x] # Utils.compareFiles(inp, man) s = time.time() print("start: {}".format(s)) out = Utils.compareFiles(inp, man.storage_location, man.locale_flags, man.content_flags) print(out) print(list(out['changed'])) print(list(out['failed'])) print(time.time()-s)
{ "content_hash": "d3847fb22db918eb2e0057fd92155ca2", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 92, "avg_line_length": 30, "alnum_prop": 0.6426666666666667, "repo_name": "ZingBallyhoo/OverwatchDataManager", "id": "264cfbf79f3aa4c84eec11f940b21e4d9b87b74b", "size": "1515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trials & tests/new_comp.py", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "6241" }, { "name": "Python", "bytes": "144896" } ], "symlink_target": "" }
""" Deprecated! Use WebHdfs instead. Only some utils and Hdfs are still used. Interfaces for Hadoop filesystem access via the HADOOP-4707 Thrift APIs. """ import errno import logging import os import posixpath import random import stat as statconsts import subprocess import urlparse import threading from thrift.transport import TTransport from django.utils.encoding import smart_str, force_unicode from django.utils.translation import ugettext as _ from desktop.lib import thrift_util, i18n from desktop.lib.conf import validate_port from hadoop.api.hdfs import Namenode, Datanode from hadoop.api.hdfs.constants import QUOTA_DONT_SET, QUOTA_RESET from hadoop.api.common.ttypes import RequestContext, IOException import hadoop.conf from hadoop.fs import normpath, SEEK_SET, SEEK_CUR, SEEK_END from hadoop.fs.exceptions import PermissionDeniedException LOG = logging.getLogger(__name__) DEFAULT_USER = "webui" # The number of bytes to read if not specified DEFAULT_READ_SIZE = 1024*1024 # 1MB # The buffer size of the pipe to hdfs -put during upload WRITE_BUFFER_SIZE = 128*1024 # 128K # Class that we translate into PermissionDeniedException HADOOP_ACCESSCONTROLEXCEPTION = "org.apache.hadoop.security.AccessControlException" # Timeout for thrift calls to NameNode NN_THRIFT_TIMEOUT = 15 DN_THRIFT_TIMEOUT = 3 # Encoding used by HDFS namespace HDFS_ENCODING = 'utf-8' def encode_fs_path(path): """encode_fs_path(path) -> byte string in utf8""" return smart_str(path, HDFS_ENCODING, errors='strict') def decode_fs_path(path): """decode_fs_path(bytestring) -> unicode path""" return force_unicode(path, HDFS_ENCODING, errors='strict') def test_fs_configuration(fs_config, hadoop_bin_conf): """Test FS configuration. Returns list of (confvar, error).""" TEST_FILE = '/tmp/.hue_config_test.%s' % (random.randint(0, 9999999999)) res = [ ] res.extend(validate_port(fs_config.NN_THRIFT_PORT)) res.extend(validate_port(fs_config.NN_HDFS_PORT)) if res: return res # Check thrift plugin try: fs = HadoopFileSystem.from_config( fs_config, hadoop_bin_path=hadoop_bin_conf.get()) fs.setuser(fs.superuser) ls = fs.listdir('/') except TTransport.TTransportException: msg = 'Failed to contact Namenode plugin at %s:%s.' % \ (fs_config.NN_HOST.get(), fs_config.NN_THRIFT_PORT.get()) LOG.exception(msg) res.append((fs_config, msg)) return res except (IOError, IOException): msg = 'Failed to see HDFS root directory at %s. Please check HDFS configuration.' % (fs.uri,) LOG.exception(msg) res.append((fs_config, msg)) return res if 'tmp' not in ls: return res # Check nn port (via upload) try: w_file = fs.open(TEST_FILE, 'w') except OSError, ex: msg = 'Failed to execute Hadoop (%s)' % (hadoop_bin_conf.get(),) LOG.exception(msg) res.append((hadoop_bin_conf, msg)) return res try: try: w_file.write('hello world') w_file.close() except IOError: msg = 'Failed to upload files using %s' % (fs.uri,) LOG.exception(msg) res.append((fs_config.NN_HDFS_PORT, msg)) return res # Check dn plugin (via read) try: r_file = fs.open(TEST_FILE, 'r') r_file.read() except Exception: msg = 'Failed to read file. Are all datanodes configured with the HUE plugin?' LOG.exception(msg) res.append((fs_config, msg)) finally: # Cleanup. Ignore if file not found. try: if fs.exists(TEST_FILE): fs.remove(TEST_FILE) except Exception, ex: LOG.error('Failed to cleanup test file "%s:%s": %s' % (fs.uri, TEST_FILE, ex)) return res def _coerce_exceptions(function): """ Decorator that causes exceptions thrown by the decorated function to be coerced into generic exceptions from the hadoop.fs.exceptions module. """ def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except IOException, e: e.msg = force_unicode(e.msg, errors='replace') e.stack = force_unicode(e.stack, errors='replace') LOG.exception("Exception in Hadoop FS call " + function.__name__) if e.clazz == HADOOP_ACCESSCONTROLEXCEPTION: raise PermissionDeniedException(e.msg, e) else: raise return wrapper class Hdfs(object): """ An abstract HDFS proxy """ @staticmethod def basename(path): return posixpath.basename(path) @staticmethod def dirname(path): return posixpath.dirname(path) @staticmethod def split(path): return posixpath.split(path) @staticmethod def join(first, *comp_list): return posixpath.join(first, *comp_list) @staticmethod def abspath(path): return posixpath.abspath(path) @staticmethod def normpath(path): res = posixpath.normpath(path) # Python normpath() doesn't eliminate leading double slashes if res.startswith('//'): return res[1:] return res @staticmethod def urlsplit(url): """ Take an HDFS path (hdfs://nn:port/foo) or just (/foo) and split it into the standard urlsplit's 5-tuple. """ i = url.find('://') if i == -1: # Not found. Treat the entire argument as an HDFS path return ('hdfs', '', normpath(url), '', '') schema = url[:i] if schema not in ('hdfs', 'viewfs'): # Default to standard for non-hdfs return urlparse.urlsplit(url) url = url[i+3:] i = url.find('/') if i == -1: # Everything is netloc. Assume path is root. return (schema, url, '/', '', '') netloc = url[:i] path = url[i:] return (schema, netloc, normpath(path), '', '') def listdir_recursive(self, path, glob=None): """ listdir_recursive(path, glob=None) -> [ entry names ] Get directory entry names without stats, recursively. """ paths = [path] while paths: path = paths.pop() if self.isdir(path): hdfs_paths = self.listdir_stats(path, glob) paths[:0] = [x.path for x in hdfs_paths] yield path def create_home_dir(self, home_path=None): if home_path is None: home_path = self.get_home_dir() if not self.exists(home_path): user = self.user try: try: self.setuser(self.superuser) self.mkdir(home_path) self.chmod(home_path, 0755) self.chown(home_path, user, user) except IOError: msg = 'Failed to create home dir ("%s") as superuser %s' %\ (home_path, self.superuser) LOG.exception(msg) raise finally: self.setuser(user) def copyFromLocal(self, local_src, remote_dst, mode=0755): remote_dst = remote_dst.endswith(posixpath.sep) and remote_dst[:-1] or remote_dst local_src = local_src.endswith(posixpath.sep) and local_src[:-1] or local_src if os.path.isdir(local_src): self._copy_dir(local_src, remote_dst, mode) else: (basename, filename) = os.path.split(local_src) self._copy_file(local_src, self.isdir(remote_dst) and self.join(remote_dst, filename) or remote_dst) def _copy_dir(self, local_dir, remote_dir, mode=0755): self.mkdir(remote_dir, mode=mode) for f in os.listdir(local_dir): local_src = os.path.join(local_dir, f) remote_dst = self.join(remote_dir, f) if os.path.isdir(local_src): self._copy_dir(local_src, remote_dst, mode) else: self._copy_file(local_src, remote_dst) def _copy_file(self, local_src, remote_dst, chunk_size=1024 * 1024 * 64): if os.path.isfile(local_src): if self.exists(remote_dst): LOG.info(_('%(remote_dst)s already exists. Skipping.') % {'remote_dst': remote_dst}) return else: LOG.info(_('%(remote_dst)s does not exist. Trying to copy.') % {'remote_dst': remote_dst}) src = file(local_src) try: try: self.create(remote_dst, permission=0755) chunk = src.read(chunk_size) while chunk: self.append(remote_dst, chunk) chunk = src.read(chunk_size) LOG.info(_('Copied %s -> %s.') % (local_src, remote_dst)) except: LOG.error(_('Copying %s -> %s failed.') % (local_src, remote_dst)) raise finally: src.close() else: LOG.info(_('Skipping %s (not a file).') % local_src) @_coerce_exceptions def mktemp(self, subdir='', prefix='tmp', basedir=None): """ mktemp(prefix) -> <temp_dir or basedir>/<subdir>/prefix.<rand> Return a unique temporary filename with prefix in the cluster's temp dir. """ RANDOM_BITS = 64 base = self.join(basedir or self._temp_dir, subdir) if not self.isdir(base): self.mkdir(base) while True: name = prefix + '.' + str(random.getrandbits(RANDOM_BITS)) candidate = self.join(base, name) if not self.exists(candidate): return candidate def mkswap(self, filename, subdir='', suffix='swp', basedir=None): """ mkswap(filename, suffix) -> <temp_dir or basedir>/<subdir>/filename.<suffix> Return a unique temporary filename with prefix in the cluster's temp dir. """ RANDOM_BITS = 64 base = self.join(basedir or self._temp_dir, subdir) if not self.isdir(base): self.mkdir(base) candidate = self.join(base, "%s.%s" % (filename, suffix)) return candidate def exists(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'exists'}) def do_as_user(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'do_as_user'}) def create(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'exists'}) def append(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'append'}) def mkdir(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'mkdir'}) def isdir(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'isdir'}) def listdir_stats(self): raise NotImplementedError(_("%(function)s has not been implemented.") % {'function': 'listdir_stats'}) """ Deprecated! Use WebHdfs instead """ class HadoopFileSystem(Hdfs): """ Implementation of Filesystem APIs through Thrift to a Hadoop cluster. """ def __init__(self, host, thrift_port, hdfs_port=8020, nn_kerberos_principal="hdfs", dn_kerberos_principal="hdfs", security_enabled=False, hadoop_bin_path="hadoop", temp_dir='/tmp'): """ @param host hostname or IP of the namenode @param thrift_port port on which the Thrift plugin is listening @param hdfs_port port on which NameNode IPC is listening @param hadoop_bin_path path to find the hadoop wrapper script on the installed system - default is fine if it is in the user's PATH env @param temp_dir Temporary directory, for mktemp() """ self.host = host self.thrift_port = thrift_port self.hdfs_port = hdfs_port self.security_enabled = security_enabled self.nn_kerberos_principal = nn_kerberos_principal self.dn_kerberos_principal = dn_kerberos_principal self.hadoop_bin_path = hadoop_bin_path self._resolve_hadoop_path() self.security_enabled = security_enabled self._temp_dir = temp_dir self.nn_client = thrift_util.get_client( Namenode.Client, host, thrift_port, service_name="HDFS Namenode HUE Plugin", use_sasl=security_enabled, kerberos_principal=nn_kerberos_principal, timeout_seconds=NN_THRIFT_TIMEOUT) # The file systems are cached globally. We store # user information in a thread-local variable so that # safety can be preserved there. self.thread_local = threading.local() self.setuser(DEFAULT_USER) LOG.debug("Initialized HadoopFS: %s:%d (%s)", host, thrift_port, hadoop_bin_path) @classmethod def from_config(cls, fs_config, hadoop_bin_path="hadoop"): return cls(host=fs_config.NN_HOST.get(), thrift_port=fs_config.NN_THRIFT_PORT.get(), hdfs_port=fs_config.NN_HDFS_PORT.get(), security_enabled=fs_config.SECURITY_ENABLED.get(), nn_kerberos_principal=fs_config.NN_KERBEROS_PRINCIPAL.get(), dn_kerberos_principal=fs_config.DN_KERBEROS_PRINCIPAL.get(), hadoop_bin_path=hadoop_bin_path) def _get_hdfs_base(self): return "hdfs://%s:%d" % (self.host, self.hdfs_port) # TODO(todd) fetch the port from the NN thrift def _resolve_hadoop_path(self): """The hadoop_bin_path configuration may be a non-absolute path, in which case it's checked against $PATH. If the hadoop binary can't be found anywhere, raises an Exception. """ for path_dir in os.getenv("PATH", "").split(os.pathsep): path = os.path.join(path_dir, self.hadoop_bin_path) if os.path.exists(path): self.hadoop_bin_path = os.path.abspath(path) return raise OSError(errno.ENOENT, "Hadoop binary (%s) does not exist." % (self.hadoop_bin_path,)) @property def uri(self): return self._get_hdfs_base() @property def superuser(self): """ Retrieves the user that Hadoop considers as "superuser" by looking at ownership of /. This is slightly inaccurate. """ return self.stats("/")["user"] def setuser(self, user): # Hadoop determines the groups the user belongs to on the server side. self.thread_local.request_context = RequestContext() if not self.request_context.confOptions: self.request_context.confOptions = {} self.thread_local.request_context.confOptions['effective_user'] = user self.thread_local.user = user @property def user(self): return self.thread_local.user @property def groups(self): return self.thread_local.groups @property def request_context(self): return self.thread_local.request_context @_coerce_exceptions def open(self, path, mode="r", *args, **kwargs): if mode == "w": return FileUpload(self, path, mode, *args, **kwargs) return File(self, path, mode, *args, **kwargs) @_coerce_exceptions def remove(self, path): path = encode_fs_path(path) stat = self._hadoop_stat(path) if not stat: raise IOError(errno.ENOENT, "File not found: %s" % path) if stat.isDir: raise IOError(errno.EISDIR, "Is a directory: %s" % path) success = self.nn_client.unlink( self.request_context, normpath(path), recursive=False) if not success: raise IOError("Unlink failed") @_coerce_exceptions def mkdir(self, path, mode=0755): # TODO(todd) there should be a mkdir that isn't mkdirHIER # (this is mkdir -p I think) path = encode_fs_path(path) success = self.nn_client.mkdirhier(self.request_context, normpath(path), mode) if not success: raise IOError("mkdir failed") def _rmdir(self, path, recursive=False): path = encode_fs_path(path) stat = self._hadoop_stat(path) if not stat: raise IOError(errno.ENOENT, "Directory not found: %s" % (path,)) if not stat.isDir: raise IOError(errno.EISDIR, "Is not a directory: %s" % (path,)) success = self.nn_client.unlink( self.request_context, normpath(path), recursive=recursive) if not success: raise IOError("Unlink failed") @_coerce_exceptions def rmdir(self, path): return self._rmdir(path) @_coerce_exceptions def rmtree(self, path): return self._rmdir(path, True) @_coerce_exceptions def listdir(self, path): path = encode_fs_path(path) stats = self.nn_client.ls(self.request_context, normpath(path)) return [self.basename(decode_fs_path(stat.path)) for stat in stats] @_coerce_exceptions def listdir_stats(self, path): path = encode_fs_path(path) stats = self.nn_client.ls(self.request_context, normpath(path)) return [self._unpack_stat(s) for s in stats] @_coerce_exceptions def get_content_summaries(self, paths): paths = [ normpath(encode_fs_path(path)) for path in paths ] summaries = self.nn_client.multiGetContentSummary(self.request_context, paths) def _fix_summary(summary): summary.path = decode_fs_path(summary.path) return summary return [_fix_summary(s) for s in summaries] @_coerce_exceptions def rename(self, old, new): old = encode_fs_path(old) new = encode_fs_path(new) success = self.nn_client.rename( self.request_context, normpath(old), normpath(new)) if not success: #TODO(todd) these functions should just throw if failed raise IOError("Rename failed") @_coerce_exceptions def rename_star(self, old_dir, new_dir): """Equivalent to `mv old_dir/* new""" if not self.isdir(old_dir): raise IOError(errno.ENOTDIR, "'%s' is not a directory" % (old_dir,)) if not self.exists(new_dir): self.mkdir(new_dir) elif not self.isdir(new_dir): raise IOError(errno.ENOTDIR, "'%s' is not a directory" % (new_dir,)) ls = self.listdir(old_dir) for dirent in ls: self.rename(HadoopFileSystem.join(old_dir, dirent), HadoopFileSystem.join(new_dir, dirent)) @_coerce_exceptions def exists(self, path): stat = self._hadoop_stat(path) return stat is not None @_coerce_exceptions def isfile(self, path): stat = self._hadoop_stat(path) if stat is None: return False return not stat.isDir @_coerce_exceptions def isdir(self, path): stat = self._hadoop_stat(path) if stat is None: return False return stat.isDir @_coerce_exceptions def stats(self, path, raise_on_fnf=True): stat = self._hadoop_stat(path) if not stat: if raise_on_fnf: raise IOError(errno.ENOENT, "File %s not found" % (path,)) else: return None ret = self._unpack_stat(stat) return ret @_coerce_exceptions def chmod(self, path, mode): path = encode_fs_path(path) self.nn_client.chmod(self.request_context, normpath(path), mode) @_coerce_exceptions def chown(self, path, user, group): path = encode_fs_path(path) self.nn_client.chown(self.request_context, normpath(path), user, group) @_coerce_exceptions def get_namenode_info(self): (capacity, used, available) = self.nn_client.df(self.request_context) return dict( usage=dict(capacity_bytes=capacity, used_bytes=used, available_bytes=available), ) @_coerce_exceptions def _get_blocks(self, path, offset, length): """ Get block locations from the Name Node. Returns an array of Block instances that might look like: [ Block(path='/user/todd/motd', genStamp=1001, blockId=5564389078175231298, nodes=[DatanodeInfo(xceiverCount=1, capacity=37265149952, name='127.0.0.1:50010', thriftPort=53417, state=1, remaining=18987925504, host='127.0.0.1', storageID='DS-1238582576-127.0.1.1-50010-1240968238474', dfsUsed=36864)], numBytes=424)] """ path = encode_fs_path(path) blocks = self.nn_client.getBlocks(self.request_context, normpath(path), offset, length) def _fix_block(blk): blk.path = decode_fs_path(blk.path) return blk return [_fix_block(blk) for blk in blocks] def _hadoop_stat(self, path): """Returns None if file does not exist.""" path = encode_fs_path(path) try: stat = self.nn_client.stat(self.request_context, normpath(path)) stat.path = decode_fs_path(stat.path) return stat except IOException, ioe: if ioe.clazz == 'java.io.FileNotFoundException': return None raise @_coerce_exceptions def _read_block(self, block, offset, len): """ Reads a chunk of data from the given block from the first available datanode that serves it. @param block a thrift Block object @param offset offset from the beginning of the block (not file) @param len the number of bytes to read """ errs = [] unipath = block.path block.path = encode_fs_path(block.path) try: for node in block.nodes: dn_conn = self._connect_dn(node) try: try: data = dn_conn.readBlock(self.request_context, block, offset, len) return data.data except Exception, e: errs.append(e) finally: dn_conn.close() finally: block.path = unipath raise IOError("Could not read block %s from any replicas: %s" % (block, repr(errs))) @_coerce_exceptions def set_diskspace_quota(self, path, size): """ Set the diskspace quota of a given path. @param path The path to the given hdfs resource @param size The amount of bytes that a given subtree of files can grow to. """ path = encode_fs_path(path) if normpath(path) == '/': raise ValueError('Cannot set quota for "/"') if size < 0: raise ValueError("The size quota should be 0 or positive or unset") self.nn_client.setQuota(self.request_context, normpath(path), QUOTA_DONT_SET, size) @_coerce_exceptions def set_namespace_quota(self, path, num_files): """ Set the maximum number of files of a given path. @param path The path to the given hdfs resource @param num_files The amount of files that can exist within that subtree. """ path = encode_fs_path(path) if normpath(path) == '/': raise ValueError('Cannot set quota for "/"') if num_files < 0: raise ValueError("The number of files quota should be 0 or positive or unset") self.nn_client.setQuota(self.request_context, normpath(path), num_files, QUOTA_DONT_SET) @_coerce_exceptions def clear_diskspace_quota(self, path): """ Remove the diskspace quota at a given path """ path = encode_fs_path(path) self.nn_client.setQuota(self.request_context, normpath(path), QUOTA_DONT_SET, QUOTA_RESET) @_coerce_exceptions def clear_namespace_quota(self, path): """ Remove the namespace quota at a given path """ path = encode_fs_path(path) self.nn_client.setQuota(self.request_context, normpath(path), QUOTA_RESET, QUOTA_DONT_SET) @_coerce_exceptions def get_diskspace_quota(self, path): """ Get the current space quota in bytes for disk space. None if it is unset """ path = encode_fs_path(path) space_quota = self.nn_client.getContentSummary(self.request_context, normpath(path)).spaceQuota if space_quota == QUOTA_RESET or space_quota == QUOTA_DONT_SET: return None else: return space_quota @_coerce_exceptions def get_namespace_quota(self, path): """ Get the current quota in number of files. None if it is unset """ path = encode_fs_path(path) file_count_quota = self.nn_client.getContentSummary(self.request_context, normpath(path)).quota if file_count_quota == QUOTA_RESET or file_count_quota == QUOTA_DONT_SET: return None else: return file_count_quota @_coerce_exceptions def get_usage_and_quota(self, path): """ Returns a dictionary with "file_count", "file_quota", "space_used", and "space_quota". The quotas may be None. """ path = encode_fs_path(path) summary = self.nn_client.getContentSummary(self.request_context, normpath(path)) ret = dict() ret["file_count"] = summary.fileCount ret["space_used"] = summary.spaceConsumed if summary.quota in (QUOTA_RESET, QUOTA_DONT_SET): ret["file_quota"] = None else: ret["file_quota"] = summary.quota if summary.spaceQuota in (QUOTA_RESET, QUOTA_DONT_SET): ret["space_quota"] = None else: ret["space_quota"] = summary.spaceQuota return ret @_coerce_exceptions def get_delegation_token(self): # TODO(atm): The second argument here should really be the Hue kerberos # principal, which doesn't exist yet. Todd's working on that. return self.nn_client.getDelegationToken(self.request_context, 'hadoop') def _connect_dn(self, node): dn_conf = thrift_util.ConnectionConfig( Datanode.Client, node.host, node.thriftPort, "HDFS Datanode Thrift", use_sasl=self.security_enabled, kerberos_principal=self.dn_kerberos_principal, timeout_seconds=DN_THRIFT_TIMEOUT) service, protocol, transport = \ thrift_util.connect_to_thrift(dn_conf) transport.open() service.close = lambda: transport.close() return service @staticmethod def _unpack_stat(stat): """Unpack a Thrift "Stat" object into a dictionary that looks like fs.stat""" mode = stat.perms if stat.isDir: mode |= statconsts.S_IFDIR else: mode |= statconsts.S_IFREG return { 'path': decode_fs_path(stat.path), 'size': stat.length, 'mtime': stat.mtime / 1000, 'mode': mode, 'user': stat.owner, 'group': stat.group, 'atime': stat.atime } @staticmethod def urlsplit(url): """ Take an HDFS path (hdfs://nn:port/foo) or just (/foo) and split it into the standard urlsplit's 5-tuple. """ return Hdfs.urlsplit(url) def require_open(func): """ Decorator that ensures that the file instance isn't closed when the function is run. """ def wrapper(self, *args, **kwargs): if self.closed: raise IOError(errno.EBADF, "I/O operation on closed file") return func(self, *args, **kwargs) return wrapper class File(object): """ Represents an open file on HDFS. """ def __init__(self, fs, path, mode="r", buffering=False): self.fs = fs self.path = normpath(path) self.pos = 0 self.closed = False self._block_cache = BlockCache() if buffering or mode != "r": raise Exception("buffering and write support not yet implemented") # NYI stat = self._stat() if stat is None: raise IOError(errno.ENOENT, "No such file or directory: '%s'" % path) if stat.isDir: raise IOError(errno.EISDIR, "Is a directory: '%s'" % path) #TODO(todd) somehow we need to check permissions here - maybe we need an access() call? # Minimal context manager implementation. # See: http://www.python.org/doc/2.5.2/lib/typecontextmanager.html def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False # don't supress exceptions. @require_open def seek(self, offset, whence=0): """ Set the file pointer to the given spot. @see file.seek """ if whence == SEEK_SET: self.pos = offset elif whence == SEEK_CUR: self.pos += offset elif whence == SEEK_END: self.pos = self._stat().length + offset else: raise IOError(errno.EINVAL, "Invalid argument to seek for whence") @require_open def tell(self): return self.pos def _get_block(self, pos): """Return the Block instance that contains the given offset""" cached_block = self._block_cache.find_block(pos) if cached_block: return cached_block # Cache "miss" - fetch ahead 500MB worth of blocks new_blocks = self.fs._get_blocks(self.path, pos, 500*1024*1024) self._block_cache.insert_new_blocks(new_blocks) result = self._block_cache.find_block(pos) if not result: raise IOError("No block for position %d in file %s" % (pos, self.path)) return result @require_open def _read_in_block(self, length=DEFAULT_READ_SIZE): """ Tries to read up to length bytes, but will often read fewer, since a single call will not read across a block boundary. """ end_pos = min(self.pos + length, self._stat().length) # If we're at EOF, return empty string if end_pos == self.pos: return "" block = self._get_block(self.pos) assert _block_contains_pos(block, self.pos) assert block.path == self.path in_block_pos = self.pos - block.startOffset assert in_block_pos >= 0 in_block_len = min(length, block.numBytes - in_block_pos) result = self.fs._read_block(block, in_block_pos, in_block_len) self.pos += len(result) assert self.pos <= end_pos return result @require_open def read(self, length=DEFAULT_READ_SIZE): """ Read the given number of bytes from this file. If EOF has been reached, returns the empty string. @param length the number of bytes wanted """ result = [] read_so_far = 0 while read_so_far < length: this_data = self._read_in_block(length - read_so_far) if this_data == "": # eof break read_so_far += len(this_data) result.append(this_data) return "".join(result) def close(self): self.closed = True def _stat(self): if not hasattr(self, "_stat_cache"): self._stat_cache = self.fs._hadoop_stat(self.path) return self._stat_cache class FileUpload(object): """A write-only file that supports no seeking and cannot exist prior to opening. """ def __init__(self, fs, path, mode="w", block_size=None): self.fs = fs self.closed = False assert mode == "w" extra_confs = [] if block_size: extra_confs.append("-Ddfs.block.size=%d" % block_size) self.subprocess_cmd = [self.fs.hadoop_bin_path, "jar", hadoop.conf.SUDO_SHELL_JAR.get(), self.fs.user, "-Dfs.default.name=" + self.fs.uri] + \ extra_confs + \ ["-put", "-", encode_fs_path(path)] self.subprocess_env = i18n.make_utf8_env() if self.subprocess_env.has_key('HADOOP_CLASSPATH'): self.subprocess_env['HADOOP_CLASSPATH'] += ':' + hadoop.conf.HADOOP_EXTRA_CLASSPATH_STRING.get() else: self.subprocess_env['HADOOP_CLASSPATH'] = hadoop.conf.HADOOP_EXTRA_CLASSPATH_STRING.get() if hadoop.conf.HADOOP_CONF_DIR.get(): self.subprocess_env['HADOOP_CONF_DIR'] = hadoop.conf.HADOOP_CONF_DIR.get() self.path = path self.putter = subprocess.Popen(self.subprocess_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, env=self.subprocess_env, bufsize=WRITE_BUFFER_SIZE) @require_open def write(self, data): """May raise IOError, particularly EPIPE""" self.putter.stdin.write(data) @require_open def close(self): try: (stdout, stderr) = self.putter.communicate() except IOError, ioe: logging.debug("Saw IOError writing %r" % self.path, exc_info=1) if ioe.errno == errno.EPIPE: stdout, stderr = self.putter.communicate() self.closed = True if stderr: LOG.warn("HDFS FileUpload (cmd='%s', env='%s') outputted stderr:\n%s" % (repr(self.subprocess_cmd), repr(self.subprocess_env), stderr)) if stdout: LOG.info("HDFS FileUpload (cmd='%s', env='%s') outputted stdout:\n%s" % (repr(self.subprocess_cmd), repr(self.subprocess_env), stdout)) if self.putter.returncode != 0: raise IOError("hdfs put returned bad code: %d\nstderr: %s" % (self.putter.returncode, stderr)) LOG.info("Completed upload: %s" % repr(self.subprocess_cmd)) @require_open def flush(self): self.putter.stdin.flush() def _block_contains_pos(block, pos): return pos >= block.startOffset and pos < block.startOffset + block.numBytes class BlockCache(object): """ A cache of block locations used by a single HDFS input file. Essentially this keeps the blocks in sorted order and does binary search to find the block that contains a given offset. It also provides the ability to merge in the response of a NN getBlocks response to the cache. """ def __init__(self): self.blocks = [] def find_block(self, pos, _min_idx=0, _max_idx=None): """ Return the Block object that contains the specified position pos, or None if it is not in the cache. """ if _max_idx is None: _max_idx = len(self.blocks) - 1 if _max_idx < _min_idx: return None pivot_idx = (_max_idx + _min_idx) / 2 pivot_block = self.blocks[pivot_idx] if pos < pivot_block.startOffset: return self.find_block(pos, _min_idx, pivot_idx - 1) elif pos >= pivot_block.startOffset + pivot_block.numBytes: return self.find_block(pos, pivot_idx + 1, _max_idx) else: return pivot_block def insert_new_blocks(self, new_blocks): """ Merge a list of Block objects from the NN into the list of cached blocks. If the set of blocks overlaps, the new blocks take precedence. """ # We could do a more efficient merge here since both lists # are already sorted, but these data structures are small, so let's # do the easy thing. blocks_dict = dict( (b.blockId, b) for b in self.blocks ) # Merge in new data to dictionary for nb in new_blocks: blocks_dict[nb.blockId] = nb # Convert back to sorted list block_list = blocks_dict.values() block_list.sort(cmp=lambda a,b: cmp(a.startOffset, b.startOffset)) # Update cache with new data self.blocks = block_list
{ "content_hash": "f393d682eabace95a9187a29d7edac28", "timestamp": "", "source": "github", "line_count": 1050, "max_line_length": 106, "avg_line_length": 31.805714285714284, "alnum_prop": 0.6424721523535752, "repo_name": "2013Commons/hue", "id": "1a2480e2af37b4f608b8788a62986181ac42491c", "size": "34188", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "desktop/libs/hadoop/src/hadoop/fs/hadoopfs.py", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from celery import Celery BROKER_URL = 'redis://localhost:6379/0' app = Celery('tasks', broker=BROKER_URL) @app.task def add(x, y): return x + y
{ "content_hash": "5de7cd796b8b4033fd27787d545cdc3d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 40, "avg_line_length": 15.3, "alnum_prop": 0.6666666666666666, "repo_name": "ybrs/single-beat", "id": "cafc29ea783b088569de73f2f35ec0b511e5f438", "size": "153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/tasks.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "24214" }, { "name": "Shell", "bytes": "854" } ], "symlink_target": "" }
import numpy as np from keras.datasets import reuters from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.normalization import BatchNormalization from keras.utils import np_utils from keras.preprocessing.text import Tokenizer ''' Train and evaluate a simple MLP on the Reuters newswire topic classification task. GPU run command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python examples/reuters_mlp.py CPU run command: python examples/reuters_mlp.py ''' max_words = 10000 batch_size = 16 print "Loading data..." (X_train, y_train), (X_test, y_test) = reuters.load_data(nb_words=max_words, test_split=0.2) print len(X_train), 'train sequences' print len(X_test), 'test sequences' nb_classes = np.max(y_train)+1 print nb_classes, 'classes' print "Vectorizing sequence data..." tokenizer = Tokenizer(nb_words=max_words) X_train = tokenizer.sequences_to_matrix(X_train, mode="binary") X_test = tokenizer.sequences_to_matrix(X_test, mode="binary") print 'X_train shape:', X_train.shape print 'X_test shape:', X_test.shape print "Convert class vector to binary class matrix (for use with categorical_crossentropy)" Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) print 'Y_train shape:', Y_train.shape print 'Y_test shape:', Y_test.shape print "Building model..." model = Sequential() model.add(Dense(max_words, 256, init='normal')) model.add(Activation('relu')) #model.add(BatchNormalization(input_shape=(256,))) # try without batch normalization (doesn't work as well!) model.add(Dropout(0.5)) model.add(Dense(256, nb_classes, init='normal')) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta') print "Training..." model.fit(X_train, Y_train, nb_epoch=5, batch_size=batch_size) score = model.evaluate(X_test, Y_test, batch_size=batch_size) print 'Test score:', score classes = model.predict_classes(X_test, batch_size=batch_size) acc = np_utils.accuracy(classes, y_test) print 'Test accuracy:', acc
{ "content_hash": "d8afbc838facc82aa30aa39f8e6f1573", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 108, "avg_line_length": 33.6031746031746, "alnum_prop": 0.7439773264052905, "repo_name": "seba-1511/gsoc15-demo", "id": "d081ca06cfa13f1e4b4c30cc5fcf6d0b78ba99ea", "size": "2117", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "examples/reuters_mlp.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "77450" } ], "symlink_target": "" }
""" SDoc Copyright 2016 Set Based IT Consultancy Licence MIT """ # ---------------------------------------------------------------------------------------------------------------------- from sdoc.SDoc import SDoc from sdoc.command.BaseCommand import BaseCommand from sdoc.style.SdocStyle import SdocStyle class SDoc2Command(BaseCommand): """ Parses a SDoc2 document """ name = 'sdoc2' arguments = [ { 'name': 'config.cfg', 'description': 'The name of the config file', 'required': True }, { 'name': 'main.sdoc2', 'description': 'The SDoc2 document to parse', 'required': True } ] # ------------------------------------------------------------------------------------------------------------------ def handle(self): """ Reads the arguments and starts SDoc application. """ self._io = SdocStyle(self.input, self.output) sdoc = SDoc() sdoc.io = self._io sdoc.config_path = self.argument('config.cfg') sdoc.init() return sdoc.run_sdoc2(self.argument('main.sdoc2')) # ----------------------------------------------------------------------------------------------------------------------
{ "content_hash": "d591c3d9badc3f82582eee63b9b752a2", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 120, "avg_line_length": 28.06382978723404, "alnum_prop": 0.39651250947687644, "repo_name": "OlegKlimenko/py-sdoc", "id": "4f0e26e0bf3beecd0e8323a7ac2f6428f7a163c4", "size": "1319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdoc/command/SDoc2Command.py", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "7975" }, { "name": "Python", "bytes": "405351" } ], "symlink_target": "" }
from __future__ import print_function from __future__ import division from __future__ import absolute_import import unittest import mock from google.appengine.ext import ndb from dashboard.common import testing_common from dashboard.common import utils from dashboard.models import anomaly_config class AnomalyConfigTest(testing_common.TestCase): def testGetAnomalyConfigDict(self): testing_common.AddTests(['M'], ['b'], {'foo': {'bar': {}}}) test = utils.TestKey('M/b/foo/bar').get() # The sample test has no overridden config. self.assertEqual({}, anomaly_config.GetAnomalyConfigDict(test)) # Override the config for the test added above. # The overridden config is set in the pre-put hook of the TestMetadata. my_config = { '_comment': 'Very particular segment sizes.', 'max_window_size': 721, 'min_segment_size': 123, } my_patterns = [test.test_path] anomaly_config.AnomalyConfig(config=my_config, patterns=my_patterns).put() test.UpdateSheriff() test.put() # The sample test now has an overridden config which is used. # Extraneous "comment" keys are ignored. expected = { 'max_window_size': 721, 'min_segment_size': 123, } self.assertEqual(expected, anomaly_config.GetAnomalyConfigDict(test)) @mock.patch('logging.warning') def testGetAnomalyConfigDict_OverriddenConfigNotFound( self, mock_logging_warning): testing_common.AddTests(['M'], ['b'], {'foo': {'bar': {}}}) test = utils.TestKey('M/b/foo/bar').get() test.overridden_anomaly_config = ndb.Key('AnomalyConfig', 'Non-existent') self.assertEqual({}, anomaly_config.GetAnomalyConfigDict(test)) mock_logging_warning.assert_called_once_with( 'No AnomalyConfig fetched from key %s for test %s', ndb.Key('AnomalyConfig', 'Non-existent'), 'M/b/foo/bar') self.assertIsNone(test.key.get().overridden_anomaly_config) if __name__ == '__main__': unittest.main()
{ "content_hash": "462420fa063910f3c74d51f516bc985e", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 78, "avg_line_length": 33.67796610169491, "alnum_prop": 0.6844489179667841, "repo_name": "endlessm/chromium-browser", "id": "fbd3e7dd3b49c9ea285ca41d010d6c4765e27722", "size": "2150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/catapult/dashboard/dashboard/models/anomaly_config_test.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import re import sys import eventlet eventlet.monkey_patch() from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log as logging import oslo_messaging from neutron.agent.common import config from neutron.agent.linux import ip_lib from neutron.agent.linux import utils from neutron.common import config as common_cfg from neutron.common import rpc from neutron.common import utils as neutron_utils from neutron.db import agents_db from neutron.i18n import _LE, _LI from neutron import manager from neutron.openstack.common import periodic_task from neutron.openstack.common import service as svc from neutron.plugins.ml2.drivers.cisco.apic import mechanism_apic as ma from neutron.plugins.ml2.drivers import type_vlan # noqa from neutron import service ACI_PORT_DESCR_FORMATS = [ r'topology/pod-1/node-(\d+)/sys/conng/path-\[eth(\d+)/(\d+)\]', r'topology/pod-1/paths-(\d+)/pathep-\[eth(\d+)/(\d+)\]', ] AGENT_FORCE_UPDATE_COUNT = 100 BINARY_APIC_SERVICE_AGENT = 'neutron-cisco-apic-service-agent' BINARY_APIC_HOST_AGENT = 'neutron-cisco-apic-host-agent' TOPIC_APIC_SERVICE = 'apic-service' TYPE_APIC_SERVICE_AGENT = 'cisco-apic-service-agent' TYPE_APIC_HOST_AGENT = 'cisco-apic-host-agent' LOG = logging.getLogger(__name__) class ApicTopologyService(manager.Manager): target = oslo_messaging.Target(version='1.1') def __init__(self, host=None): if host is None: host = neutron_utils.get_hostname() super(ApicTopologyService, self).__init__(host=host) self.conf = cfg.CONF.ml2_cisco_apic self.conn = None self.peers = {} self.invalid_peers = [] self.dispatcher = None self.state = None self.state_agent = None self.topic = TOPIC_APIC_SERVICE self.apic_manager = ma.APICMechanismDriver.get_apic_manager(False) def init_host(self): LOG.info(_LI("APIC service agent starting ...")) self.state = { 'binary': BINARY_APIC_SERVICE_AGENT, 'host': self.host, 'topic': self.topic, 'configurations': {}, 'start_flag': True, 'agent_type': TYPE_APIC_SERVICE_AGENT, } self.conn = rpc.create_connection(new=True) self.dispatcher = [self, agents_db.AgentExtRpcCallback()] self.conn.create_consumer( self.topic, self.dispatcher, fanout=True) self.conn.consume_in_threads() def after_start(self): LOG.info(_LI("APIC service agent started")) def report_send(self, context): if not self.state_agent: return LOG.debug("APIC service agent: sending report state") try: self.state_agent.report_state(context, self.state) self.state.pop('start_flag', None) except AttributeError: # This means the server does not support report_state # ignore it return except Exception: LOG.exception(_LE("APIC service agent: failed in reporting state")) @lockutils.synchronized('apic_service') def update_link(self, context, host, interface, mac, switch, module, port): LOG.debug("APIC service agent: received update_link: %s", ", ".join(map(str, [host, interface, mac, switch, module, port]))) nlink = (host, interface, mac, switch, module, port) clink = self.peers.get((host, interface), None) if switch == 0: # this is a link delete, remove it if clink is not None: self.apic_manager.remove_hostlink(*clink) self.peers.pop((host, interface)) else: if clink is None: # add new link to database self.apic_manager.add_hostlink(*nlink) self.peers[(host, interface)] = nlink elif clink != nlink: # delete old link and add new one (don't update in place) self.apic_manager.remove_hostlink(*clink) self.peers.pop((host, interface)) self.apic_manager.add_hostlink(*nlink) self.peers[(host, interface)] = nlink class ApicTopologyServiceNotifierApi(object): def __init__(self): target = oslo_messaging.Target(topic=TOPIC_APIC_SERVICE, version='1.0') self.client = rpc.get_client(target) def update_link(self, context, host, interface, mac, switch, module, port): cctxt = self.client.prepare(version='1.1', fanout=True) cctxt.cast(context, 'update_link', host=host, interface=interface, mac=mac, switch=switch, module=module, port=port) def delete_link(self, context, host, interface): cctxt = self.client.prepare(version='1.1', fanout=True) cctxt.cast(context, 'delete_link', host=host, interface=interface, mac=None, switch=0, module=0, port=0) class ApicTopologyAgent(manager.Manager): def __init__(self, host=None): if host is None: host = neutron_utils.get_hostname() super(ApicTopologyAgent, self).__init__(host=host) self.conf = cfg.CONF.ml2_cisco_apic self.count_current = 0 self.count_force_send = AGENT_FORCE_UPDATE_COUNT self.interfaces = {} self.lldpcmd = None self.peers = {} self.port_desc_re = map(re.compile, ACI_PORT_DESCR_FORMATS) self.service_agent = ApicTopologyServiceNotifierApi() self.state = None self.state_agent = None self.topic = TOPIC_APIC_SERVICE self.uplink_ports = [] self.invalid_peers = [] def init_host(self): LOG.info(_LI("APIC host agent: agent starting on %s"), self.host) self.state = { 'binary': BINARY_APIC_HOST_AGENT, 'host': self.host, 'topic': self.topic, 'configurations': {}, 'start_flag': True, 'agent_type': TYPE_APIC_HOST_AGENT, } self.uplink_ports = [] for inf in self.conf.apic_host_uplink_ports: if ip_lib.device_exists(inf): self.uplink_ports.append(inf) else: # ignore unknown interfaces LOG.error(_LE("No such interface (ignored): %s"), inf) self.lldpcmd = ['lldpctl', '-f', 'keyvalue'] + self.uplink_ports def after_start(self): LOG.info(_LI("APIC host agent: started on %s"), self.host) @periodic_task.periodic_task def _check_for_new_peers(self, context): LOG.debug("APIC host agent: _check_for_new_peers") if not self.lldpcmd: return try: # Check if we must send update even if there is no change force_send = False self.count_current += 1 if self.count_current >= self.count_force_send: force_send = True self.count_current = 0 # Check for new peers new_peers = self._get_peers() new_peers = self._valid_peers(new_peers) # Make a copy of current interfaces curr_peers = {} for interface in self.peers: curr_peers[interface] = self.peers[interface] # Based curr -> new updates, add the new interfaces self.peers = {} for interface in new_peers: peer = new_peers[interface] self.peers[interface] = peer if (interface in curr_peers and curr_peers[interface] != peer): self.service_agent.update_link( context, peer[0], peer[1], None, 0, 0, 0) if (interface not in curr_peers or curr_peers[interface] != peer or force_send): self.service_agent.update_link(context, *peer) if interface in curr_peers: curr_peers.pop(interface) # Any interface still in curr_peers need to be deleted for peer in curr_peers.values(): self.service_agent.update_link( context, peer[0], peer[1], None, 0, 0, 0) except Exception: LOG.exception(_LE("APIC service agent: exception in LLDP parsing")) def _get_peers(self): peers = {} lldpkeys = utils.execute(self.lldpcmd, run_as_root=True) for line in lldpkeys.splitlines(): if '=' not in line: continue fqkey, value = line.split('=', 1) lldp, interface, key = fqkey.split('.', 2) if key == 'port.descr': for regexp in self.port_desc_re: match = regexp.match(value) if match: mac = self._get_mac(interface) switch, module, port = match.group(1, 2, 3) peer = (self.host, interface, mac, switch, module, port) if interface not in peers: peers[interface] = [] peers[interface].append(peer) return peers def _valid_peers(self, peers): # Reduce the peers array to one valid peer per interface # NOTE: # There is a bug in lldpd daemon that it keeps reporting # old peers even after their updates have stopped # we keep track of that report remove them from peers valid_peers = {} invalid_peers = [] for interface in peers: curr_peer = None for peer in peers[interface]: if peer in self.invalid_peers or curr_peer: invalid_peers.append(peer) else: curr_peer = peer if curr_peer is not None: valid_peers[interface] = curr_peer self.invalid_peers = invalid_peers return valid_peers def _get_mac(self, interface): if interface in self.interfaces: return self.interfaces[interface] try: mac = ip_lib.IPDevice(interface).link.address self.interfaces[interface] = mac return mac except Exception: # we can safely ignore it, it is only needed for debugging LOG.exception( _LE("APIC service agent: can not get MACaddr for %s"), interface) def report_send(self, context): if not self.state_agent: return LOG.debug("APIC host agent: sending report state") try: self.state_agent.report_state(context, self.state) self.state.pop('start_flag', None) except AttributeError: # This means the server does not support report_state # ignore it return except Exception: LOG.exception(_LE("APIC host agent: failed in reporting state")) def launch(binary, manager, topic=None): cfg.CONF(project='neutron') common_cfg.init(sys.argv[1:]) config.setup_logging() report_period = cfg.CONF.ml2_cisco_apic.apic_agent_report_interval poll_period = cfg.CONF.ml2_cisco_apic.apic_agent_poll_interval server = service.Service.create( binary=binary, manager=manager, topic=topic, report_interval=report_period, periodic_interval=poll_period) svc.launch(server).wait() def service_main(): launch( BINARY_APIC_SERVICE_AGENT, 'neutron.plugins.ml2.drivers.' + 'cisco.apic.apic_topology.ApicTopologyService', TOPIC_APIC_SERVICE) def agent_main(): launch( BINARY_APIC_HOST_AGENT, 'neutron.plugins.ml2.drivers.' + 'cisco.apic.apic_topology.ApicTopologyAgent')
{ "content_hash": "fd59f0d186e22f80b86ef19c50699bf7", "timestamp": "", "source": "github", "line_count": 329, "max_line_length": 79, "avg_line_length": 36.14589665653495, "alnum_prop": 0.5782038345105953, "repo_name": "cisco-openstack/networking-cisco", "id": "68beaa797955cd9db0e16b3df10a770a3f0d926e", "size": "12530", "binary": false, "copies": "1", "ref": "refs/heads/staging/libertyplus", "path": "networking_cisco/plugins/ml2/drivers/cisco/apic/apic_topology.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1180075" }, { "name": "Shell", "bytes": "636" } ], "symlink_target": "" }
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import collections import logging import os import sys import tempfile from flexget import plugin from flexget.event import event log = logging.getLogger('subtitles') try: from subliminal.extensions import provider_manager PROVIDERS = provider_manager.names() except ImportError: PROVIDERS = [ 'opensubtitles', 'thesubdb', 'podnapisi', 'addic7ed', 'tvsubtitles' ] AUTHENTICATION_SCHEMA = dict((provider, {'type': 'object'}) for provider in PROVIDERS) class PluginSubliminal(object): """ Search and download subtitles using Subliminal by Antoine Bertin (https://pypi.python.org/pypi/subliminal). Example (complete task):: subs: find: path: - d:\media\incoming regexp: '.*\.(avi|mkv|mp4)$' recursive: yes accept_all: yes subliminal: languages: - ita alternatives: - eng exact_match: no providers: addic7ed, opensubtitles single: no directory: /disk/subtitles hearing_impaired: yes authentication: addic7ed: username: myuser passsword: mypassword """ schema = { 'type': 'object', 'properties': { 'languages': {'type': 'array', 'items': {'type': 'string'}, 'minItems': 1}, 'alternatives': {'type': 'array', 'items': {'type': 'string'}}, 'exact_match': {'type': 'boolean', 'default': True}, 'providers': {'type': 'array', 'items': {'type': 'string', 'enum': PROVIDERS}}, 'single': {'type': 'boolean', 'default': True}, 'directory': {'type:': 'string'}, 'hearing_impaired': {'type': 'boolean', 'default': False}, 'authentication': {'type': 'object', 'properties': AUTHENTICATION_SCHEMA}, }, 'required': ['languages'], 'additionalProperties': False } def on_task_start(self, task, config): if list(sys.version_info) < [2, 7]: raise plugin.DependencyError('subliminal', 'Python 2.7', 'Subliminal plugin requires python 2.7.') try: import babelfish except ImportError as e: log.debug('Error importing Babelfish: %s', e) raise plugin.DependencyError('subliminal', 'babelfish', 'Babelfish module required. ImportError: %s' % e) try: import subliminal except ImportError as e: log.debug('Error importing Subliminal: %s', e) raise plugin.DependencyError('subliminal', 'subliminal', 'Subliminal module required. ImportError: %s' % e) def on_task_output(self, task, config): """ Configuration:: subliminal: languages: List of languages (as IETF codes) in order of preference. At least one is required. alternatives: List of second-choice languages; subs will be downloaded but entries rejected. exact_match: Use file hash only to search for subs, otherwise Subliminal will try to guess by filename. providers: List of providers from where to download subtitles. single: Download subtitles in single mode (no language code added to subtitle filename). directory: Path to directory where to save the subtitles, default is next to the video. hearing_impaired: Prefer subtitles for the hearing impaired when available authentication: > Dictionary of configuration options for different providers. Keys correspond to provider names, and values are dictionaries, usually specifying `username` and `password`. """ if not task.accepted: log.debug('nothing accepted, aborting') return from babelfish import Language from dogpile.cache.exception import RegionAlreadyConfigured import subliminal from subliminal.cli import MutexLock from subliminal.score import episode_scores, movie_scores try: subliminal.region.configure('dogpile.cache.dbm', arguments={ 'filename': os.path.join(tempfile.gettempdir(), 'cachefile.dbm'), 'lock_factory': MutexLock, }) except RegionAlreadyConfigured: pass # Let subliminal be more verbose if our logger is set to DEBUG if log.isEnabledFor(logging.DEBUG): logging.getLogger("subliminal").setLevel(logging.INFO) else: logging.getLogger("subliminal").setLevel(logging.CRITICAL) logging.getLogger("dogpile").setLevel(logging.CRITICAL) logging.getLogger("enzyme").setLevel(logging.WARNING) try: languages = set([Language.fromietf(s) for s in config.get('languages', [])]) alternative_languages = set([Language.fromietf(s) for s in config.get('alternatives', [])]) except ValueError as e: raise plugin.PluginError(e) # keep all downloaded subtitles and save to disk when done (no need to write every time) downloaded_subtitles = collections.defaultdict(list) providers_list = config.get('providers', None) provider_configs = config.get('authentication', None) # test if only one language was provided, if so we will download in single mode # (aka no language code added to subtitle filename) # unless we are forced not to by configuration # if we pass 'yes' for single in configuration but choose more than one language # we ignore the configuration and add the language code to the # potentially downloaded files single_mode = config.get('single', '') and len(languages | alternative_languages) <= 1 hearing_impaired = config.get('hearing_impaired', False) with subliminal.core.ProviderPool(providers=providers_list, provider_configs=provider_configs) as provider_pool: for entry in task.accepted: if 'location' not in entry: log.warning('Cannot act on entries that do not represent a local file.') continue if not os.path.exists(entry['location']): entry.fail('file not found: %s' % entry['location']) continue if '$RECYCLE.BIN' in entry['location']: # ignore deleted files in Windows shares continue try: entry_languages = set(entry.get('subtitle_languages', [])) or languages video = subliminal.scan_video(entry['location']) # use metadata refiner to get mkv metadata refiner = ('metadata',) subliminal.core.refine(video, episode_refiners=refiner, movie_refiners=refiner) existing_subtitles = set(subliminal.core.search_external_subtitles(entry['location']).values()) video.subtitle_languages |= existing_subtitles if isinstance(video, subliminal.Episode): title = video.series hash_scores = episode_scores['hash'] else: title = video.title hash_scores = movie_scores['hash'] log.info('Name computed for %s was %s', entry['location'], title) msc = hash_scores if config['exact_match'] else 0 if entry_languages.issubset(video.subtitle_languages) or (single_mode and video.subtitle_languages): log.debug('All preferred languages already exist for "%s"', entry['title']) entry['subtitles_missing'] = set() continue # subs for preferred lang(s) already exists else: # Gather the subtitles for the alternative languages too, to avoid needing to search the sites # again. They'll just be ignored if the main languages are found. all_subtitles = provider_pool.list_subtitles(video, entry_languages | alternative_languages) subtitles = provider_pool.download_best_subtitles(all_subtitles, video, entry_languages, min_score=msc, hearing_impaired=hearing_impaired) if subtitles: downloaded_subtitles[video].extend(subtitles) log.info('Subtitles found for %s', entry['location']) else: # only try to download for alternatives that aren't alread downloaded subtitles = provider_pool.download_best_subtitles(all_subtitles, video, alternative_languages, min_score=msc, hearing_impaired=hearing_impaired) if subtitles: downloaded_subtitles[video].extend(subtitles) entry.fail('subtitles found for a second-choice language.') else: entry.fail('cannot find any subtitles for now.') downloaded_languages = set([Language.fromietf(str(l.language)) for l in subtitles]) if entry_languages: entry['subtitles_missing'] = entry_languages - downloaded_languages if len(entry['subtitles_missing']) > 0: entry.fail('Subtitles for all primary languages not found') except ValueError as e: log.error('subliminal error: %s', e) entry.fail() if downloaded_subtitles: if task.options.test: log.verbose('Test mode. Found subtitles:') # save subtitles to disk for video, subtitle in downloaded_subtitles.items(): if subtitle: _directory = config.get('directory') if _directory: _directory = os.path.expanduser(_directory) if task.options.test: log.verbose(' FOUND LANGUAGES %s for %s', [str(l.language) for l in subtitle], video.name) continue subliminal.save_subtitles(video, subtitle, single=single_mode, directory=_directory) @event('plugin.register') def register_plugin(): plugin.register(PluginSubliminal, 'subliminal', api_ver=2)
{ "content_hash": "652d77ba898134c1fae046ff3b46acb1", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 120, "avg_line_length": 48.74025974025974, "alnum_prop": 0.5554667377209344, "repo_name": "tarzasai/Flexget", "id": "071987ac59a87f2dda87de96212d27e8bcff982c", "size": "11259", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "flexget/plugins/output/subtitles_subliminal.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10540" }, { "name": "HTML", "bytes": "71698" }, { "name": "JavaScript", "bytes": "251546" }, { "name": "Python", "bytes": "2803014" }, { "name": "SRecode Template", "bytes": "3" } ], "symlink_target": "" }
from collections import namedtuple import itertools import operator import re import processing.comparators.base_comparator as base_comparator from models.match_singlet import MatchHalf import processing.comparators.match_concatenator as concatenator from utilities.suffix_array import matcher as suffix_apps from processing.comparators import spacer MatchBlock = namedtuple('MatchBlock', ['a', 'b', 'size']) class Comparator(base_comparator.BaseComparator): def _find_matching_blocks(self, matching_passages): """ Find matchblocks from matching passages :param matching_passages: strings representing matching passages in both docs :return: list of concatenator.MatchTuples sorted by where they appear in document a """ blocks = set() for passage in matching_passages: a_matches = re.finditer(passage, self.a_strip) a_starts = (i.start() for i in a_matches) b_matches = re.finditer(passage, self.b_strip) b_starts = (j.start() for j in b_matches) l = len(passage) for i, j in itertools.product(a_starts, b_starts): new_block = concatenator.MatchTuple(i, j, i+l, j+l) blocks.add(new_block) # Concerned that sorting on a may adversely impact # concat on the b side blocks = sorted(blocks, key=operator.attrgetter('a')) return blocks def get_matching_passages(self): """ Get common passages between document :return: set of common passages """ matching_passages = suffix_apps.acs_no_substrings(a=self.a_strip, b=self.b_strip) return matching_passages def compare(self): """ Compare texts :return: list of singlet pairs """ matching_passages = self.get_matching_passages() blocks = self._find_matching_blocks(matching_passages) # Concatenate blocks by gap length combined_blocks = self._combine_blocks(blocks) # Filter blocks by length filtered_blocks = self._filter_blocks(combined_blocks) # Get actual blocks passage_blocks = self._tuples_to_passages(filtered_blocks) return self._get_singlet_pairs(passage_blocks) def _combine_blocks(self, matching_blocks): """ :param matching_blocks: list of tuples (i, j, n) """ cat = concatenator.MatchConcatenator(matching_blocks, self.gap_length) return cat.concatenate() def _filter_blocks(self, combined_blocks): """ Filter match blocks based on length Blocks must be at least match_length long in either a or b """ filtered = [] for block in combined_blocks: a_len = block.a_end - block.a if a_len >= self.match_length: filtered.append(block) else: b_len = block.b_end - block.b if b_len >= self.match_length: filtered.append(block) return filtered def _tuples_to_passages(self, filtered_blocks): """ Get passages from concatenator blocks :param filtered_blocks: list of concatenator blocks :return: list of tuples containing the passage in a and in b """ a_spaces = spacer.get_space_locations(self.a) b_spaces = spacer.get_space_locations(self.b) passages = [] for tup in filtered_blocks: # Strings without spaces a = self.a_strip[tup.a:tup.a_end] b = self.b_strip[tup.b:tup.b_end] # Replace spaces to get actual passages a_passage = spacer.add_spaces(space_locations=a_spaces, offset=tup.a, target=a) b_passage = spacer.add_spaces(space_locations=b_spaces, offset=tup.b, target=b) passage_tup = (a_passage, b_passage) passages.append(passage_tup) return passages @staticmethod def _pass_gen(strip_body, blocks): """ Generator for passages """ for b in blocks: yield strip_body[b.tup] @staticmethod def _get_singlet_pairs(passage_blocks): """ Get the match singlet from passage pairs :param passage_blocks: list of passage pair tuples :return: list of singlet pair tuples """ singlet_pairs = [] for p_a, p_b in passage_blocks: s_a = MatchHalf(passage=p_a) s_b = MatchHalf(passage=p_b) singlet_pairs.append((s_a, s_b)) return singlet_pairs
{ "content_hash": "8f79779199c4f9f00a06dbad77f9125a", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 78, "avg_line_length": 35.05, "alnum_prop": 0.5728551049521092, "repo_name": "gnarph/DIRT", "id": "3d6591d75bca132a5d36be7c42a43c35459ea703", "size": "4907", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "processing/comparators/simple.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "153884" }, { "name": "Shell", "bytes": "274" } ], "symlink_target": "" }
"""Demo of the tfdbg curses UI: A TF network computing Fibonacci sequence.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from tensorflow.python.debug import local_cli flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer("tensor_size", 30, "Size of tensor. E.g., if the value is 30, the tensors " "will have shape [30, 30].") flags.DEFINE_integer("length", 20, "Length of the fibonacci sequence to compute.") def main(_): sess = tf.Session() # Construct the TensorFlow network. n0 = tf.Variable(np.ones([FLAGS.tensor_size] * 2), name="node_00") n1 = tf.Variable(np.ones([FLAGS.tensor_size] * 2), name="node_01") if FLAGS.length > 100: raise ValueError("n is too big.") for i in xrange(2, FLAGS.length): n0, n1 = n1, tf.add(n0, n1, name="node_%.2d" % i) sess.run(tf.initialize_all_variables()) # Wrap the TensorFlow Session object for debugging. sess = local_cli.LocalCLIDebugWrapperSession(sess) sess.run(n1) if __name__ == "__main__": tf.app.run()
{ "content_hash": "28772b093fbcc7881b6c9d0472a39790", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 77, "avg_line_length": 28.790697674418606, "alnum_prop": 0.6591276252019386, "repo_name": "juharris/tensorflow", "id": "18eb0a4fa306f304415df2cc777f67912b23a9bd", "size": "1927", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tensorflow/python/debug/examples/debug_fibonacci.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "156005" }, { "name": "C++", "bytes": "9229239" }, { "name": "CMake", "bytes": "29372" }, { "name": "CSS", "bytes": "1297" }, { "name": "HTML", "bytes": "783708" }, { "name": "Java", "bytes": "39181" }, { "name": "JavaScript", "bytes": "10779" }, { "name": "Jupyter Notebook", "bytes": "1773496" }, { "name": "Protocol Buffer", "bytes": "112087" }, { "name": "Python", "bytes": "6699482" }, { "name": "Shell", "bytes": "185658" }, { "name": "TypeScript", "bytes": "410434" } ], "symlink_target": "" }
import numpy from scipy.optimize import minimize_scalar from scipy.stats import norm def lhs( n_factors, n_samples, genepool=10000, random_in_cell=True ): """ Parameters ---------- n_factors : int The number of columns to sample n_samples : int The number of Latin hypercube samples (rows) genepool : int The nubmer of random permutation from which to find good (uncorrelated) columns random_in_cell : bool, default True If true, a uniform random point in each hypercube cell is chosen, otherwise the center point in each cell is chosen. Returns ------- ndarray """ candidates = numpy.empty([genepool, n_samples], dtype=numpy.float64) for i in range(genepool): candidates[i,:] = numpy.random.permutation(n_samples) corr = numpy.fabs(numpy.corrcoef(candidates)) keepers = [0] keeper_gross_corr = 0 for j in range(n_factors-1): keeper_gross_corr += corr[keepers[-1], :] k = numpy.argmin(keeper_gross_corr) keepers.append(k) lhs = candidates[keepers, :].copy() if random_in_cell: lhs += numpy.random.rand(*(lhs.shape)) else: lhs += 0.5 lhs /= n_samples return lhs def _avg_off_diag(a): upper = numpy.triu_indices(a.shape[0], 1) lower = numpy.tril_indices(a.shape[0], -1) return (a[upper].mean() + a[lower].mean()) / 2 def _stduniform_to_stdnormal(x): return norm(0,1).ppf(x) def _stdnormal_to_stduniform(x): return norm(0,1).cdf(x) def _make_correlated(x, corr, dim=0): d = x.shape[dim] s = numpy.full([d,d], fill_value=corr) + numpy.eye(d)*(1-corr) chol = numpy.linalg.cholesky(s) return numpy.dot(chol, x) def _induce_correlation(x, approx_corr, return_actual_corr=False): x = _stduniform_to_stdnormal(x) x = _make_correlated(x,approx_corr) if return_actual_corr: result = _stdnormal_to_stduniform(x) return _avg_off_diag(numpy.corrcoef(result)) return _stdnormal_to_stduniform(x) def induce_correlation(h, corr, rows=None, inplace=False): h_full = h if rows: h = h[rows,:] _target_corr = lambda m: (_induce_correlation(h, m, return_actual_corr=True) - corr) ** 2 result = minimize_scalar(_target_corr, bounds=(0, 1), method='Bounded') h_result = _induce_correlation(h,result.x) if inplace: if rows: h_full[rows,:] = h_result[:] else: h[:] = h_result[:] else: return h_result def lhs_corr(n_factors, n_samples, genepool=10, sigma=None, random_in_cell=True): """ Correlated LHS. Works only in theory, or for low correllation / small sample sizes Parameters ---------- n_factors : int The number of columns to sample n_samples : int The number of Latin hypercube samples (rows) genepool : int The nubmer of random permutation from which to find good (uncorrelated) columns sigma : array The desired correlation matrix random_in_cell : bool, default True If true, a uniform random point in each hypercube cell is chosen, otherwise the center point in each cell is chosen. Returns ------- ndarray """ keepers = [] candidates = numpy.empty([genepool, n_samples], dtype=numpy.float64) keeper_corr = numpy.zeros([n_factors, genepool]) corr = None def _reroll(): nonlocal candidates, keepers, corr for i in range(genepool): if i not in keepers: candidates[i, :] = numpy.random.permutation(n_samples) corr = numpy.corrcoef(candidates) o_corr = corr[corr < 0.999] # print("max_o_corr",numpy.max(o_corr)) for j in range(len(keepers)): keeper_corr[j, :] = corr[keepers[j], :] _reroll() if sigma is None: sigma = numpy.eye(n_factors) # initially keep the first column keepers.append(0) for j in range(n_factors - 1): # load in the previously determined correlation row keeper_corr[j, :] = corr[keepers[-1], :] # ident the relevant part of sigma for comparing sig_part = sigma[j + 1, :j + 1] print("sig_part", sig_part) for repeat in range(50000): # find the closest match in the gene pool for target correlation kc = keeper_corr[:j + 1, :] kc = kc[kc < 0.999] if repeat % 1000 == 0: print(repeat, "max_corr", numpy.max(kc)) sq_diff_from_target = ((keeper_corr[:j + 1, :] - sig_part[:, None]) ** 2).sum(0) k = numpy.argmin(sq_diff_from_target) if sq_diff_from_target[k] < 0.001: break else: _reroll() keepers.append(k) print(keepers) lhs = candidates[keepers, :].copy() if random_in_cell: lhs += numpy.random.rand(*(lhs.shape)) else: lhs += 0.5 lhs /= n_samples return lhs
{ "content_hash": "6c8cfb0ce6627482b5f40ba44ab7db03", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 90, "avg_line_length": 25.70175438596491, "alnum_prop": 0.6748577929465301, "repo_name": "jpn--/pines", "id": "08592db1bc4326c1dda2086e4246d0609558bc83", "size": "4396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pines/latin_hypercube.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "106" }, { "name": "Python", "bytes": "246656" }, { "name": "Shell", "bytes": "674" } ], "symlink_target": "" }
import ort_flatbuffers_py.experimental.fbs as fbs class FbsTypeInfo: "Class to provide conversion between ORT flatbuffers schema values and C++ types" tensordatatype_to_string = { fbs.TensorDataType.TensorDataType.FLOAT: 'float', fbs.TensorDataType.TensorDataType.UINT8: 'uint8_t', fbs.TensorDataType.TensorDataType.INT8: 'int8_t', fbs.TensorDataType.TensorDataType.UINT16: 'uint16_t', fbs.TensorDataType.TensorDataType.INT16: 'int16_t', fbs.TensorDataType.TensorDataType.INT32: 'int32_t', fbs.TensorDataType.TensorDataType.INT64: 'int64_t', fbs.TensorDataType.TensorDataType.STRING: 'std::string', fbs.TensorDataType.TensorDataType.BOOL: 'bool', fbs.TensorDataType.TensorDataType.FLOAT16: 'MLFloat16', fbs.TensorDataType.TensorDataType.DOUBLE: 'double', fbs.TensorDataType.TensorDataType.UINT32: 'uint32_t', fbs.TensorDataType.TensorDataType.UINT64: 'uint64_t', # fbs.TensorDataType.TensorDataType.COMPLEX64: 'complex64 is not supported', # fbs.TensorDataType.TensorDataType.COMPLEX128: 'complex128 is not supported', fbs.TensorDataType.TensorDataType.BFLOAT16: 'BFloat16' } @staticmethod def typeinfo_to_str(type: fbs.TypeInfo): value_type = type.ValueType() value = type.Value() type_str = 'unknown' if value_type == fbs.TypeInfoValue.TypeInfoValue.tensor_type: tensor_type_and_shape = fbs.TensorTypeAndShape.TensorTypeAndShape() tensor_type_and_shape.Init(value.Bytes, value.Pos) elem_type = tensor_type_and_shape.ElemType() type_str = FbsTypeInfo.tensordatatype_to_string[elem_type] elif value_type == fbs.TypeInfoValue.TypeInfoValue.map_type: map_type = fbs.MapType.MapType() map_type.init(value.Bytes, value.Pos) key_type = map_type.KeyType() # TensorDataType key_type_str = FbsTypeInfo.tensordatatype_to_string[key_type] value_type = map_type.ValueType() # TypeInfo value_type_str = FbsTypeInfo.typeinfo_to_str(value_type) type_str = 'std::map<{},{}>'.format(key_type_str, value_type_str) elif value_type == fbs.TypeInfoValue.TypeInfoValue.sequence_type: sequence_type = fbs.SequenceType.SequenceType() sequence_type.Init(value.Bytes, value.Pos) elem_type = sequence_type.ElemType() # TypeInfo elem_type_str = FbsTypeInfo.typeinfo_to_str(elem_type) # TODO: Decide if we need to wrap the type in a std::vector. Issue is that the element type is internal # to the onnxruntime::Tensor class so we're really returning the type inside the Tensor not vector<Tensor>. # For now, return the element type (which will be the Tensor element type, or a map<A,B>) as # an operator input or output will either be a sequence or a not, so we don't need to disambiguate # between the two (i.e. we know if the returned value refers to the contents of a sequence, and can # handle whether it's the element type of a Tensor in the sequence, or the map type in a sequence of maps # due to this). type_str = elem_type_str else: raise ValueError('Unknown or missing value type of {}'.format(value_type)) return type_str def get_typeinfo(name: str, value_name_to_typeinfo: dict) -> fbs.TypeInfo: 'Lookup a name in a dictionary mapping value name to TypeInfo.' if name not in value_name_to_typeinfo: raise RuntimeError('Missing TypeInfo entry for ' + name) return value_name_to_typeinfo[name] # TypeInfo object def value_name_to_typestr(name: str, value_name_to_typeinfo: dict): 'Lookup TypeInfo for value name and convert to a string representing the C++ type.' type = get_typeinfo(name, value_name_to_typeinfo) type_str = FbsTypeInfo.typeinfo_to_str(type) return type_str
{ "content_hash": "b412e5a47328ed86dbc387baac3533b2", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 119, "avg_line_length": 52.064935064935064, "alnum_prop": 0.6729857819905213, "repo_name": "ryfeus/lambda-packs", "id": "76e69615b403f380a0921fa8c22155589e9ea556", "size": "4104", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ONNX-ARM/lambda-onnx-arm-3.8/onnxruntime/tools/ort_format_model/types.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9768343" }, { "name": "C++", "bytes": "76566960" }, { "name": "CMake", "bytes": "191097" }, { "name": "CSS", "bytes": "153538" }, { "name": "Cuda", "bytes": "61768" }, { "name": "Cython", "bytes": "3110222" }, { "name": "Fortran", "bytes": "110284" }, { "name": "HTML", "bytes": "248658" }, { "name": "JavaScript", "bytes": "62920" }, { "name": "MATLAB", "bytes": "17384" }, { "name": "Makefile", "bytes": "152150" }, { "name": "Python", "bytes": "549307737" }, { "name": "Roff", "bytes": "26398" }, { "name": "SWIG", "bytes": "142" }, { "name": "Shell", "bytes": "7790" }, { "name": "Smarty", "bytes": "4090" }, { "name": "TeX", "bytes": "152062" }, { "name": "XSLT", "bytes": "305540" } ], "symlink_target": "" }
from __future__ import unicode_literals, print_function import os import pathspec from pathlib2 import PurePath, Path from gcdt.gcdt_logging import getLogger log = getLogger(__name__) # based on: https://github.com/finklabs/botodeploy/blob/master/botodeploy/utils_static.py def glob_files(root_dir, includes=None, excludes=None, gcdtignore=None): """Powerful and flexible utility to search and tag files using patterns. :param root_dir: directory where we start the search :param includes: list or iterator of include pattern tuples (pattern, tag) :param excludes: list or iterator of exclude patterns :param gcdtignore: list of ignore patterns (gitwildcard format) :return: iterator of (absolute_path, relative_path) """ # docu here: https://docs.python.org/3/library/pathlib.html if not includes: includes = ['**'] else: # we need to iterate multiple times (iterator safeguard) includes = list(includes) if excludes: # we need to iterate multiple times (iterator safeguard) excludes = list(excludes) if gcdtignore: spec = pathspec.PathSpec.from_lines('gitwildmatch', gcdtignore) log.debug('gcdtignore patterns: %s', gcdtignore) while includes: pattern = includes.pop(0) # for compatibility with std. python Lib/glop.py: # >>>If recursive is true, the pattern '**' will match any files and # zero or more directories and subdirectories.<<< if pattern.endswith('**'): pattern += '/*' matches = list(Path(root_dir).glob(pattern)) for m in matches: if m.is_dir(): continue # some discussion on how to convert a pattern into regex: # http://stackoverflow.com/questions/27726545/python-glob-but-against-a-list-of-strings-rather-than-the-filesystem pp = PurePath(m) # check if m is contained in remaining include patterns # (last one wins) if includes and any(map(lambda p: pp.match(p), includes)): continue # check if m is contained in exclude pattern if excludes and any(map(lambda p: pp.match(p), excludes)): continue # check if m is contained in gcdtignore if gcdtignore and spec.match_file(str(m)): log.debug('Skipped file \'%s\' due to gcdtignore pattern', str(m.relative_to(root_dir))) continue yield (str(m), str(m.relative_to(root_dir))) def get_path_info(path): # helper to get (base, rel_path, target) # path is full path! path_to_zip = path.get('source') if not os.path.isabs(path_to_zip): # transform relative to absolute path if necessary path_to_zip = os.path.join(os.getcwd(), path_to_zip) # keep folder configs backwards compatible (we did not use glob before) if os.path.isdir(path_to_zip): # turn folder into glob if not path_to_zip.endswith('/'): path_to_zip += '/' path_to_zip += '**' # extract base!! s = path_to_zip.rsplit('/', 1) base = s[0] ptz = s[1] target = path.get('target', ptz) if not target.endswith('/'): target += '/' return base, ptz, target
{ "content_hash": "155c7af95ac806f54aa68b4f7ee714ff", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 126, "avg_line_length": 34.05102040816327, "alnum_prop": 0.6152232544201378, "repo_name": "glomex/gcdt-bundler", "id": "7c1823cbb887b5039d6955b5c51ea3fc3ba41035", "size": "3361", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "gcdt_bundler/bundler_utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "50674" }, { "name": "Shell", "bytes": "227" }, { "name": "Smarty", "bytes": "271" } ], "symlink_target": "" }
'''Unit tests for grit.tool.rc2grd''' from __future__ import print_function import os import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) import re import unittest from six import StringIO from grit import grd_reader from grit import util from grit.node import base from grit.tool import rc2grd class Rc2GrdUnittest(unittest.TestCase): def testPlaceholderize(self): tool = rc2grd.Rc2Grd() original = "Hello %s, how are you? I'm $1 years old!" msg = tool.Placeholderize(original) self.failUnless(msg.GetPresentableContent() == "Hello TODO_0001, how are you? I'm TODO_0002 years old!") self.failUnless(msg.GetRealContent() == original) def testHtmlPlaceholderize(self): tool = rc2grd.Rc2Grd() original = "Hello <b>[USERNAME]</b>, how are you? I'm [AGE] years old!" msg = tool.Placeholderize(original) self.failUnless(msg.GetPresentableContent() == "Hello BEGIN_BOLDX_USERNAME_XEND_BOLD, how are you? I'm X_AGE_X years old!") self.failUnless(msg.GetRealContent() == original) def testMenuWithoutWhitespaceRegression(self): # There was a problem in the original regular expression for parsing out # menu sections, that would parse the following block of text as a single # menu instead of two. two_menus = ''' // Hyper context menus IDR_HYPERMENU_FOLDER MENU BEGIN POPUP "HyperFolder" BEGIN MENUITEM "Open Containing Folder", IDM_OPENFOLDER END END IDR_HYPERMENU_FILE MENU BEGIN POPUP "HyperFile" BEGIN MENUITEM "Open Folder", IDM_OPENFOLDER END END ''' self.failUnless(len(rc2grd._MENU.findall(two_menus)) == 2) def testRegressionScriptWithTranslateable(self): tool = rc2grd.Rc2Grd() # test rig class DummyNode(base.Node): def AddChild(self, item): self.node = item verbose = False extra_verbose = False tool.not_localizable_re = re.compile('') tool.o = DummyNode() rc_text = '''STRINGTABLE\nBEGIN\nID_BINGO "<SPAN id=hp style='BEHAVIOR: url(#default#homepage)'></SPAN><script>if (!hp.isHomePage('[$~HOMEPAGE~$]')) {document.write(""<a href=\\""[$~SETHOMEPAGEURL~$]\\"" >Set As Homepage</a> - "");}</script>"\nEND\n''' tool.AddMessages(rc_text, tool.o) self.failUnless(tool.o.node.GetCdata().find('Set As Homepage') != -1) # TODO(joi) Improve the HTML parser to support translateables inside # <script> blocks? self.failUnless(tool.o.node.attrs['translateable'] == 'false') def testRoleModel(self): rc_text = ('STRINGTABLE\n' 'BEGIN\n' ' // This should not show up\n' ' IDS_BINGO "Hello %s, how are you?"\n' ' // The first description\n' ' IDS_BONGO "Hello %s, my name is %s, and yours?"\n' ' IDS_PROGRAMS_SHUTDOWN_TEXT "Google Desktop Search needs to close the following programs:\\n\\n$1\\nThe installation will not proceed if you choose to cancel."\n' 'END\n') tool = rc2grd.Rc2Grd() tool.role_model = grd_reader.Parse(StringIO( '''<?xml version="1.0" encoding="UTF-8"?> <grit latest_public_release="2" source_lang_id="en-US" current_release="3" base_dir="."> <release seq="3"> <messages> <message name="IDS_BINGO"> Hello <ph name="USERNAME">%s<ex>Joi</ex></ph>, how are you? </message> <message name="IDS_BONGO" desc="The other description"> Hello <ph name="USERNAME">%s<ex>Jakob</ex></ph>, my name is <ph name="ADMINNAME">%s<ex>Joi</ex></ph>, and yours? </message> <message name="IDS_PROGRAMS_SHUTDOWN_TEXT" desc="LIST_OF_PROGRAMS is replaced by a bulleted list of program names."> Google Desktop Search needs to close the following programs: <ph name="LIST_OF_PROGRAMS">$1<ex>Program 1, Program 2</ex></ph> The installation will not proceed if you choose to cancel. </message> </messages> </release> </grit>'''), dir='.') # test rig class DummyOpts(object): verbose = False extra_verbose = False tool.o = DummyOpts() result = tool.Process(rc_text, '.\resource.rc') self.failUnless( result.children[2].children[2].children[0].attrs['desc'] == '') self.failUnless( result.children[2].children[2].children[0].children[0].attrs['name'] == 'USERNAME') self.failUnless( result.children[2].children[2].children[1].attrs['desc'] == 'The other description') self.failUnless( result.children[2].children[2].children[1].attrs['meaning'] == '') self.failUnless( result.children[2].children[2].children[1].children[0].attrs['name'] == 'USERNAME') self.failUnless( result.children[2].children[2].children[1].children[1].attrs['name'] == 'ADMINNAME') self.failUnless( result.children[2].children[2].children[2].children[0].attrs['name'] == 'LIST_OF_PROGRAMS') def testRunOutput(self): """Verify basic correct Run behavior.""" tool = rc2grd.Rc2Grd() class DummyOpts(object): verbose = False extra_verbose = False with util.TempDir({}) as output_dir: rcfile = os.path.join(output_dir.GetPath(), 'foo.rc') open(rcfile, 'w').close() self.assertIsNone(tool.Run(DummyOpts(), [rcfile])) self.assertTrue(os.path.exists(os.path.join(output_dir.GetPath(), 'foo.grd'))) def testMissingOutput(self): """Verify failure with no args.""" tool = rc2grd.Rc2Grd() class DummyOpts(object): verbose = False extra_verbose = False ret = tool.Run(DummyOpts(), []) self.assertIsNotNone(ret) self.assertGreater(ret, 0) if __name__ == '__main__': unittest.main()
{ "content_hash": "35b41996080a9e939b941065c0802cf2", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 256, "avg_line_length": 36.765822784810126, "alnum_prop": 0.6316061284214151, "repo_name": "ric2b/Vivaldi-browser", "id": "c599032f2ec05fc690268efffe8c97afa5e75f23", "size": "5999", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chromium/tools/grit/grit/tool/rc2grd_unittest.py", "mode": "33261", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import lda import itertools import numpy as np import codecs from temporal import doc_topic_strengths_over_periods from sklearn.feature_extraction.text import CountVectorizer from mynlp.preprocess import (transform, ALL_PIPELINE_NAMES) from util import load_line_corpus def main(): # parameters collection_name = "nips" years = xrange(2008, 2015) # 10 ~ 14 n_topics = 6 n_top_words = 15 # load corpus corpus_paths = map(lambda y: "data/{}-{}.dat".format(collection_name, y), years) all_corpus = [] year2corpus = {} for year, path in zip(years, corpus_paths): corpus = list(load_line_corpus(path)) all_corpus.append(corpus) year2corpus[year] = corpus all_corpus = list(itertools.chain.from_iterable(all_corpus)) preprocessor = lambda doc: ' '.join(transform(doc, ALL_PIPELINE_NAMES)) tokenizer = lambda doc: doc.split() with codecs.open('data/lemur-stopwords.txt', 'r' 'utf8') as f: stop_words = map(lambda s: s.strip(), f.readlines()) vectorizer = CountVectorizer(preprocessor=preprocessor, tokenizer=tokenizer, stop_words=stop_words, min_df=5) X = vectorizer.fit_transform(all_corpus) id2word = {id_: word for word, id_ in vectorizer.vocabulary_.items()} # build the model model = lda.LDA(n_topics=n_topics, n_iter=700, # alpha=1.0, eta=1.0, random_state=1) model.fit(X) # print topics for i, topic_dist in enumerate(model.topic_word_): top_word_ids = np.argsort(topic_dist)[:-n_top_words:-1] topic_words = [id2word[id_] for id_ in top_word_ids] print('Topic {}: {}'.format(i, ' '.join(topic_words))) year2docs = {} start_document_index = 0 for year in years: corpus_size = len(year2corpus[year]) end_document_index = start_document_index + corpus_size year2docs[year] = np.arange(start_document_index, end_document_index) start_document_index = end_document_index tbl = doc_topic_strengths_over_periods(model.doc_topic_, year2docs) print tbl print np.array(tbl.values()) if __name__ == "__main__": main()
{ "content_hash": "72e132fb688e5560d5078ef816d954d9", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 77, "avg_line_length": 31.263157894736842, "alnum_prop": 0.5892255892255892, "repo_name": "xiaohan2012/temporal-topic-mining", "id": "1660c863212350b52715cca7f13e3dfa16e7485c", "size": "2376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lda_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "15156" }, { "name": "Shell", "bytes": "469" } ], "symlink_target": "" }
import zof from ..http import HttpServer from ..pktview import pktview_from_list, pktview_to_list APP = zof.Application('rest_api') APP.http_endpoint = '127.0.0.1:8080' WEB = HttpServer(logger=APP.logger) # WEB.define_var('dpid', _parse_dpid) @APP.event('start') async def start(_): await WEB.start(APP.http_endpoint) @APP.event('stop') async def stop(_): await WEB.stop() @WEB.get('/stats/switches', 'json') def get_switches(): return [d.datapath_id for d in zof.get_datapaths()] @WEB.get('/stats/flow/{dpid}', 'json') async def get_flows(dpid): result = [] async for ofmsg in FLOWDESC_REQ.request(datapath_id=_parse_dpid(dpid)): _translate_flows(ofmsg['msg']) result.extend(ofmsg['msg']) return {dpid: result} @WEB.post('/stats/flow/{dpid}', 'json') async def post_flows(dpid, post_data): match = pktview_to_list(post_data.get('match', {})) flow_req = zof.compile({ 'type': 'REQUEST.FLOW_DESC', 'msg': { 'table_id': post_data.get('table_id', 'ALL'), 'out_port': post_data.get('out_port', 'ANY'), 'out_group': post_data.get('out_group', 'ANY'), 'cookie': post_data.get('cookie', 0), 'cookie_mask': post_data.get('cookie_mask', 0), 'match': match } }) result = [] async for ofmsg in flow_req.request(datapath_id=_parse_dpid(dpid)): _translate_flows(ofmsg['msg']) result.extend(ofmsg['msg']) return {dpid: result} @WEB.get('/stats/groupdesc/{dpid}', 'json') async def get_groupdesc(dpid): result = await GROUPDESC_REQ.request(datapath_id=_parse_dpid(dpid)) _translate_groups(result['msg']) return {dpid: result['msg']} @WEB.get('/stats/port/{dpid}/{port_no}', 'json') async def get_portstats_specific(dpid, port_no): result = await PORTSTATS_REQ.request( datapath_id=_parse_dpid(dpid), port_no=_parse_port(port_no)) return {dpid: result['msg']} @WEB.get('/stats/port/{dpid}', 'json') async def get_portstats(dpid): result = await PORTSTATS_REQ.request( datapath_id=_parse_dpid(dpid), port_no='ANY') return {dpid: result['msg']} @WEB.post('/stats/portdesc/modify', 'json') async def modify_portdesc(post_data): dpid = _parse_dpid(post_data['dpid']) port_no = _parse_port(post_data['port_no']) port = zof.find_port(datapath_id=dpid, port_no=port_no) PORTMOD_REQ.send( datapath_id=dpid, port_no=port_no, hw_addr=port.hw_addr, config=post_data['config'], mask=post_data['mask']) # FIXME(bfish): This code does not handle OpenFlow errors elicited from the PortMod # message. Any errors returned will only show up in the log. The barrier here is # just a cheap trick to verify that the portmod *should* have been acted on. result = await BARRIER_REQ.request(datapath_id=dpid) return result['msg'] @WEB.get('/stats/portdesc/{dpid}/{port}', 'json') async def get_portdesc_specific(dpid, port): # FIXME(bfish): Filter by port... return await get_portdesc(dpid) @WEB.get('/stats/portdesc/{dpid}', 'json') async def get_portdesc(dpid): result = await PORTDESC_REQ.request(datapath_id=_parse_dpid(dpid)) return {dpid: result['msg']} FLOWDESC_REQ = zof.compile(''' type: REQUEST.FLOW_DESC msg: table_id: ALL out_port: ANY out_group: ANY cookie: 0 cookie_mask: 0 match: [] ''') GROUPDESC_REQ = zof.compile(''' type: REQUEST.GROUP_DESC ''') PORTSTATS_REQ = zof.compile(''' type: REQUEST.PORT_STATS msg: port_no: $port_no ''') PORTDESC_REQ = zof.compile(''' type: REQUEST.PORT_DESC ''') PORTMOD_REQ = zof.compile(''' type: PORT_MOD msg: port_no: $port_no hw_addr: $hw_addr config: [$config] mask: [$mask] advertise: [] ''') BARRIER_REQ = zof.compile(''' type: BARRIER_REQUEST ''') def _parse_dpid(dpid): if isinstance(dpid, int): return _convert_dpid(dpid) if ':' in dpid: return dpid return _convert_dpid(int(dpid, 0)) def _convert_dpid(dpid): hexstr = '%16.16x' % dpid return ':'.join(hexstr[2 * i:2 * i + 2] for i in range(8)) def _parse_port(port_no): if isinstance(port_no, int): return port_no return int(port_no, 0) def _translate_flows(msgs): for msg in msgs: if 'match' in msg: msg['match'] = pktview_from_list(msg['match'], slash_notation=True) if 'instructions' in msg: msg['actions'] = _translate_instructions(msg['instructions']) def _translate_groups(msgs): for msg in msgs: for bkt in msg['buckets']: if 'actions' in bkt: bkt['actions'] = _translate_actions(bkt['actions']) def _translate_instructions(instrs): result = [] for instr in instrs: result += _translate_instruction(instr) return result def _translate_instruction(instr): if instr['instruction'] == 'APPLY_ACTIONS': return _translate_actions(instr['actions']) return [str(instr)] def _translate_actions(actions): return [_translate_action(act) for act in actions] def _translate_action(action): action_type = action['action'] if action_type == 'OUTPUT': return 'OUTPUT:%s' % action['port_no'] if action_type == 'GROUP': return 'GROUP:%s' % action['group_id'] if action_type == 'SET_FIELD': return 'SET_FIELD: {%s:%s}' % (action['field'].lower(), action['value']) if len(action) == 1: return '%s' % action_type return str(action) if __name__ == '__main__': zof.run()
{ "content_hash": "7ad027b99c18c35eaf774533cb638f66", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 87, "avg_line_length": 26.61214953271028, "alnum_prop": 0.6035118525021949, "repo_name": "byllyfish/pylibofp", "id": "5d5a99737b57e2e342f6d03239815500f490000b", "size": "5695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zof/demo/rest_api.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "155886" }, { "name": "Shell", "bytes": "443" } ], "symlink_target": "" }
import json import os import re import time from urlparse import urlparse from proboscis.asserts import fail from troveclient.compat.client import TroveHTTPClient from trove.tests.config import CONFIG print_req = True def shorten_url(url): parsed = urlparse(url) if parsed.query: method_url = parsed.path + '?' + parsed.query else: method_url = parsed.path return method_url class SnippetWriter(object): def __init__(self, conf, get_replace_list): self.conf = conf self.get_replace_list = get_replace_list def output_request(self, user_details, name, url, output_headers, body, content_type, method, static_auth_token=True): headers = [] parsed = urlparse(url) method_url = shorten_url(url) headers.append("%s %s HTTP/1.1" % (method, method_url)) headers.append("User-Agent: %s" % output_headers['User-Agent']) headers.append("Host: %s" % parsed.netloc) # static_auth_token option for documentation purposes if static_auth_token: output_token = '87c6033c-9ff6-405f-943e-2deb73f278b7' else: output_token = output_headers['X-Auth-Token'] headers.append("X-Auth-Token: %s" % output_token) headers.append("Accept: %s" % output_headers['Accept']) print("OUTPUT HEADERS: %s" % output_headers) headers.append("Content-Type: %s" % output_headers['Content-Type']) self.write_file(user_details, name, "-%s.txt" % content_type, url, method, "request", output='\n'.join(headers)) pretty_body = self.format_body(body, content_type) self.write_file(user_details, name, ".%s" % content_type, url, method, "request", output=pretty_body) def output_response(self, user_details, name, content_type, url, method, resp, body): version = "1.1" # if resp.version == 11 else "1.0" lines = [ ["HTTP/%s %s %s" % (version, resp.status, resp.reason)], ["Content-Type: %s" % resp['content-type']], ] if 'via' in resp: lines.append(["Via: %s" % resp['via']]) lines.append(["Content-Length: %s" % resp['content-length']]) lines.append(["Date: Mon, 18 Mar 2013 19:09:17 GMT"]) if 'server' in resp: lines.append(["Server: %s" % resp["server"]]) new_lines = [x[0] for x in lines] joined_lines = '\n'.join(new_lines) self.write_file(user_details, name, "-%s.txt" % content_type, url, method, "response", output=joined_lines) if body: pretty_body = self.format_body(body, content_type) self.write_file(user_details, name, ".%s" % content_type, url, method, "response", output=pretty_body) def format_body(self, body, content_type): assert content_type == 'json' try: if self.conf['replace_dns_hostname']: before = r'\"hostname\": \"[a-zA-Z0-9-_\.]*\"' after = '\"hostname\": \"%s\"' % self.conf[ 'replace_dns_hostname'] body = re.sub(before, after, body) return json.dumps(json.loads(body), sort_keys=True, indent=4) except Exception: return body or '' def write_request_file(self, user_details, name, content_type, url, method, req_headers, request_body): if print_req: print("\t%s req url:%s" % (content_type, url)) print("\t%s req method:%s" % (content_type, method)) print("\t%s req headers:%s" % (content_type, req_headers)) print("\t%s req body:%s" % (content_type, request_body)) self.output_request(user_details, name, url, req_headers, request_body, content_type, method) def write_response_file(self, user_details, name, content_type, url, method, resp, resp_content): if print_req: print("\t%s resp:%s" % (content_type, resp)) print("\t%s resp content:%s" % (content_type, resp_content)) self.output_response(user_details, name, content_type, url, method, resp, resp_content) def write_file(self, user_details, name, content_type, url, method, in_or_out, output): output = output.replace(user_details['tenant'], '1234') if self.conf['replace_host']: output = output.replace(user_details['api_url'], self.conf['replace_host']) pre_host_port = urlparse(user_details['service_url']).netloc post_host = urlparse(self.conf['replace_host']).netloc output = output.replace(pre_host_port, post_host) output = output.replace("fake_host", "hostname") output = output.replace("FAKE_", "") for resource in self.get_replace_list(): output = output.replace(str(resource[0]), str(resource[1])) filename = "%s/db-%s-%s%s" % (self.conf['directory'], name.replace('_', '-'), in_or_out, content_type) self._write_file(filename, output) def _write_file(self, filename, output): empty = len(output.strip()) == 0 # Manipulate actual data to appease doc niceness checks actual = [line.rstrip() for line in output.split("\n")] if not empty and actual[len(actual) - 1] != '': actual.append("") def goofy_diff(a, b): diff = [] for i in range(len(a)): if i < len(b): if a[i].rstrip() != b[i].rstrip(): diff.append('Expected line %d :%s\n' ' Actual line %d :%s' % (i + 1, a[i], i + 1, b[i])) else: diff.append("Expected line %d :%s" % (i + 1, a[i])) for j in range(len(b) - len(a)): i2 = len(a) + j diff.append(" Actual line %d :%s" % (i2 + 1, b[i2])) return diff def write_actual_file(): # Always write the file. with open(filename, "w") as file: for line in actual: file.write("%s\n" % line) def assert_output_matches(): if os.path.isfile(filename): with open(filename, 'r') as original_file: original = original_file.read() if empty: fail('Error: output missing in new snippet generation ' 'for %s. Old content follows:\n"""%s"""' % (filename, original)) elif filename.endswith('.json'): assert_json_matches(original) else: assert_file_matches(original) elif not empty: fail('Error: new file necessary where there was no file ' 'before. Filename=%s\nContent follows:\n"""%s"""' % (filename, output)) def assert_file_matches(original): expected = original.split('\n') # Remove the last item which will look like a duplicated # file ending newline expected.pop() diff = '\n'.join(goofy_diff(expected, actual)) if diff: fail('Error: output files differ for %s:\n%s' % (filename, diff)) def assert_json_matches(original): try: expected = json.loads(original) actual = json.loads(output) except ValueError: fail('Invalid json!\nExpected: %s\nActual: %s' % (original, output)) if expected != actual: # Re-Use the same failure output if the json is different assert_file_matches(original) if not os.environ.get('TESTS_FIX_EXAMPLES'): assert_output_matches() elif not empty: write_actual_file() # This method is mixed into the client class. # It requires the following fields: snippet_writer, content_type, and # "name," the last of which must be set before each call. def write_to_snippet(self, args, kwargs, resp, body): if self.name is None: raise RuntimeError("'name' not set before call.") url = args[0] method = args[1] request_headers = kwargs['headers'] request_body = kwargs.get('body', None) response_headers = resp response_body = body # Log request user_details = { 'api_url': self.service_url, 'service_url': self.service_url, 'tenant': self.tenant, } self.snippet_writer.write_request_file(user_details, self.name, self.content_type, url, method, request_headers, request_body) self.snippet_writer.write_response_file(user_details, self.name, self.content_type, url, method, response_headers, response_body) # Create a short url to assert against. short_url = url base_url = self.service_url for prefix in (base_url): if short_url.startswith(prefix): short_url = short_url[len(prefix):] self.old_info = { 'url': shorten_url(short_url), 'method': method, 'request_headers': request_headers, 'request_body': request_body, 'response_headers': response_headers, 'response_body': response_body } def add_fake_response_headers(headers): """ Fakes other items that would appear if you were using, just to make up an example, a proxy. """ conf = CONFIG.examples if 'via' in conf and 'via' not in headers: headers['via'] = conf['via'] if 'server' in conf and 'server' not in headers: headers['server'] = conf['server'] if 'date' not in headers: date_string = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) headers['date'] = date_string class JsonClient(TroveHTTPClient): content_type = 'json' def http_log(self, args, kwargs, resp, body): add_fake_response_headers(resp) self.pretty_log(args, kwargs, resp, body) def write_snippet(): return write_to_snippet(self, args, kwargs, resp, body) self.write_snippet = write_snippet
{ "content_hash": "f4d42f6fa0093ae7ffae1699b2af5d3b", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 79, "avg_line_length": 39.9365671641791, "alnum_prop": 0.5355507801550967, "repo_name": "cp16net/trove", "id": "f8fa1a019e2696d5d40678b81c4bbf4bb7b72d1d", "size": "11308", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "trove/tests/examples/client.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "88" }, { "name": "CSS", "bytes": "21914" }, { "name": "JavaScript", "bytes": "60526" }, { "name": "Python", "bytes": "2872713" }, { "name": "Shell", "bytes": "15002" }, { "name": "XSLT", "bytes": "50542" } ], "symlink_target": "" }
from .action_py3 import Action class ImageAction(Action): """Defines an image action. You probably want to use the sub-classes and not this class directly. Known sub-classes are: ImageEntityAction, ImageModuleAction, ImageRecipesAction, ImageRelatedSearchesAction, ImageShoppingSourcesAction Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param _type: Required. Constant filled by server. :type _type: str :ivar id: A String identifier. :vartype id: str :ivar read_link: The URL that returns this resource. To use the URL, append query parameters as appropriate and include the Ocp-Apim-Subscription-Key header. :vartype read_link: str :ivar web_search_url: The URL to Bing's search result for this item. :vartype web_search_url: str :ivar name: The name of the thing represented by this object. :vartype name: str :ivar url: The URL to get more information about the thing represented by this object. :vartype url: str :ivar image: An image of the item. :vartype image: ~azure.cognitiveservices.search.visualsearch.models.ImageObject :ivar description: A short description of the item. :vartype description: str :ivar alternate_name: An alias for the item. :vartype alternate_name: str :ivar bing_id: An ID that uniquely identifies this item. :vartype bing_id: str :ivar thumbnail_url: The URL to a thumbnail of the item. :vartype thumbnail_url: str :ivar provider: The source of the creative work. :vartype provider: list[~azure.cognitiveservices.search.visualsearch.models.Thing] :ivar date_published: The date on which the CreativeWork was published. :vartype date_published: str :ivar text: Text content of this creative work. :vartype text: str :ivar result: The result produced in the action. :vartype result: list[~azure.cognitiveservices.search.visualsearch.models.Thing] :ivar display_name: A display name for the action. :vartype display_name: str :ivar is_top_action: A Boolean representing whether this result is the top action. :vartype is_top_action: bool :ivar service_url: Use this URL to get additional data to determine how to take the appropriate action. For example, the serviceUrl might return JSON along with an image URL. :vartype service_url: str :ivar action_type: A string representing the type of action. :vartype action_type: str """ _validation = { '_type': {'required': True}, 'id': {'readonly': True}, 'read_link': {'readonly': True}, 'web_search_url': {'readonly': True}, 'name': {'readonly': True}, 'url': {'readonly': True}, 'image': {'readonly': True}, 'description': {'readonly': True}, 'alternate_name': {'readonly': True}, 'bing_id': {'readonly': True}, 'thumbnail_url': {'readonly': True}, 'provider': {'readonly': True}, 'date_published': {'readonly': True}, 'text': {'readonly': True}, 'result': {'readonly': True}, 'display_name': {'readonly': True}, 'is_top_action': {'readonly': True}, 'service_url': {'readonly': True}, 'action_type': {'readonly': True}, } _attribute_map = { '_type': {'key': '_type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'read_link': {'key': 'readLink', 'type': 'str'}, 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, 'image': {'key': 'image', 'type': 'ImageObject'}, 'description': {'key': 'description', 'type': 'str'}, 'alternate_name': {'key': 'alternateName', 'type': 'str'}, 'bing_id': {'key': 'bingId', 'type': 'str'}, 'thumbnail_url': {'key': 'thumbnailUrl', 'type': 'str'}, 'provider': {'key': 'provider', 'type': '[Thing]'}, 'date_published': {'key': 'datePublished', 'type': 'str'}, 'text': {'key': 'text', 'type': 'str'}, 'result': {'key': 'result', 'type': '[Thing]'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'is_top_action': {'key': 'isTopAction', 'type': 'bool'}, 'service_url': {'key': 'serviceUrl', 'type': 'str'}, 'action_type': {'key': 'actionType', 'type': 'str'}, } _subtype_map = { '_type': {'ImageEntityAction': 'ImageEntityAction', 'ImageModuleAction': 'ImageModuleAction', 'ImageRecipesAction': 'ImageRecipesAction', 'ImageRelatedSearchesAction': 'ImageRelatedSearchesAction', 'ImageShoppingSourcesAction': 'ImageShoppingSourcesAction'} } def __init__(self, **kwargs) -> None: super(ImageAction, self).__init__(**kwargs) self.action_type = None self._type = 'ImageAction'
{ "content_hash": "88a72c84b52b5ac53eaa0b44ffdc1760", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 265, "avg_line_length": 43.043103448275865, "alnum_prop": 0.6212697776887642, "repo_name": "Azure/azure-sdk-for-python", "id": "535a934682ee739c6ba9c398edb8341575128609", "size": "5467", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/cognitiveservices/azure-cognitiveservices-search-visualsearch/azure/cognitiveservices/search/visualsearch/models/image_action_py3.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1224" }, { "name": "Bicep", "bytes": "24196" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "4892" }, { "name": "HTML", "bytes": "12058" }, { "name": "JavaScript", "bytes": "8137" }, { "name": "Jinja", "bytes": "10377" }, { "name": "Jupyter Notebook", "bytes": "272022" }, { "name": "PowerShell", "bytes": "518535" }, { "name": "Python", "bytes": "715484989" }, { "name": "Shell", "bytes": "3631" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0016_auto_20161204_1654'), ] operations = [ migrations.AlterField( model_name='lan', name='paytypes', field=main.models.ChoiceArrayField(base_field=models.CharField(choices=[('mp', 'MobilePay'), ('cash', 'Kontant')], max_length=127), null=True, size=None, verbose_name='betalingstyper'), ), migrations.AlterField( model_name='lanprofile', name='paid', field=models.NullBooleanField(verbose_name='betalt?'), ), migrations.AlterField( model_name='lanprofile', name='paytype', field=models.CharField(blank=True, choices=[('mp', 'MobilePay'), ('cash', 'Kontant')], max_length=255, null=True, verbose_name='betalingstype'), ), ]
{ "content_hash": "f9f44b03b1d934e631211becabe0d39a", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 197, "avg_line_length": 33.62068965517241, "alnum_prop": 0.598974358974359, "repo_name": "bomjacob/htxaarhuslan", "id": "d108d446b310fce66748a1c29c4c00ced38a019a", "size": "1048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/migrations/0017_auto_20161205_2209.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35691" }, { "name": "HTML", "bytes": "59480" }, { "name": "JavaScript", "bytes": "19475" }, { "name": "Python", "bytes": "148411" } ], "symlink_target": "" }
from myhdl import * from pihdf import * from myhdl_lib import * #--- Custom code begin ---# #--- Custom code end ---# def TIncr_rtl(rst, clk, mode, inc_out, rdy_en, rdy_buff, DELAY_BITS): '''| | Top-level MyHDL description. This is converted to RTL velilog... |________''' """ Interface signals """ mode_ready, mode_valid, mode_data = mode.get_snk_signals() # consume data inc_out_ready, inc_out_valid, inc_out_data = inc_out.get_src_signals() # produce data rdy_en_ready, rdy_en_valid, rdy_en_data = rdy_en.get_src_signals() # produce data rdy_buff_ready, rdy_buff_valid, rdy_buff_data = rdy_buff.get_src_signals() # produce data #--- Custom code begin ---# sl_vld, sl_vld_out = [Signal(bool(0)) for _ in range(2)] hsd_en = Signal(bool(0)) hsd_en_inst = mode.enable(rst, clk, inc_out_ready, sl_vld, hsd_en) delay_cnt = Signal(modbv(0, min=0, max=2**DELAY_BITS)) # should have full bit vector range count = Signal(modbv(0, min=0, max=2**2)) @always_seq(clk.posedge, reset=rst) def clk_prcs_dly(): if hsd_en: # Always increment odd numbers +1, otherwise we can miss the condition (delay_cnt == 0) if (mode_data == 0) or (delay_cnt[0] == 1): delay_cnt.next = delay_cnt + 1 else: delay_cnt.next = delay_cnt + 2 @always_comb def vld_prcs(): sl_vld_out.next = (delay_cnt == 0) and sl_vld @always_seq(clk.posedge, reset=rst) def clk_prcs_cnt(): if sl_vld_out: count.next = count + 1 @always_comb def out_prcs(): rdy_en_data.next = mode_valid rdy_buff_data.next = inc_out_ready inc_out_data.next = count inc_out_valid.next = sl_vld_out #--- Custom code end ---# return all_instances(rst, clk)
{ "content_hash": "14281e0dd23a9d1768e96194b5b6d67d", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 99, "avg_line_length": 31.47457627118644, "alnum_prop": 0.5794291868605277, "repo_name": "hnikolov/pihdf", "id": "090a3cd8cea466328f84b334a4953edfb0ada6f3", "size": "1857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/hsd_struct/src/modules/TIncr/src/TIncr_rtl.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "382722" }, { "name": "Verilog", "bytes": "2205" } ], "symlink_target": "" }
"""Small example showing the use of nested types in PyTables. The program creates an output file, 'nested-tut.h5'. You can view it with ptdump or any HDF5 generic utility. :Author: F. Alted :Date: 2005/06/10 """ from __future__ import print_function import numpy import tables #'-**-**-**-**- The sample nested class description -**-**-**-**-**-' class Info(tables.IsDescription): """A sub-structure of Test""" _v_pos = 2 # The position in the whole structure name = tables.StringCol(10) value = tables.Float64Col(pos=0) colors = tables.Enum(['red', 'green', 'blue']) class NestedDescr(tables.IsDescription): """A description that has several nested columns.""" color = tables.EnumCol(colors, 'red', base='uint32') info1 = Info() class info2(tables.IsDescription): _v_pos = 1 name = tables.StringCol(10) value = tables.Float64Col(pos=0) class info3(tables.IsDescription): x = tables.Float64Col(dflt=1) y = tables.UInt8Col(dflt=1) print() print('-**-**-**-**-**-**- file creation -**-**-**-**-**-**-**-') filename = "nested-tut.h5" print("Creating file:", filename) fileh = tables.open_file(filename, "w") print() print('-**-**-**-**-**- nested table creation -**-**-**-**-**-') table = fileh.create_table(fileh.root, 'table', NestedDescr) # Fill the table with some rows row = table.row for i in range(10): row['color'] = colors[['red', 'green', 'blue'][i % 3]] row['info1/name'] = "name1-%s" % i row['info2/name'] = "name2-%s" % i row['info2/info3/y'] = i # All the rest will be filled with defaults row.append() table.flush() # flush the row buffer to disk print(repr(table.nrows)) nra = table[::4] print(repr(nra)) # Append some additional rows table.append(nra) print(repr(table.nrows)) # Create a new table table2 = fileh.create_table(fileh.root, 'table2', nra) print(repr(table2[:])) # Read also the info2/name values with color == colors.red names = [x['info2/name'] for x in table if x['color'] == colors.red] print() print("**** info2/name elements satisfying color == 'red':", repr(names)) print() print('-**-**-**-**-**-**- table data reading & selection -**-**-**-**-**-') # Read the data print() print("**** table data contents:\n", table[:]) print() print("**** table.info2 data contents:\n", repr(table.cols.info2[1:5])) print() print("**** table.info2.info3 data contents:\n", repr(table.cols.info2.info3[1:5])) print("**** _f_col() ****") print(repr(table.cols._f_col('info2'))) print(repr(table.cols._f_col('info2/info3/y'))) print() print('-**-**-**-**-**-**- table metadata -**-**-**-**-**-') # Read description metadata print() print("**** table description (short):\n", repr(table.description)) print() print("**** more from manual, period ***") print(repr(table.description.info1)) print(repr(table.description.info2.info3)) print(repr(table.description._v_nested_names)) print(repr(table.description.info1._v_nested_names)) print() print("**** now some for nested records, take that ****") print(repr(table.description._v_nested_descr)) print(repr(numpy.rec.array(None, shape=0, dtype=table.description._v_nested_descr))) print(repr(numpy.rec.array(None, shape=0, dtype=table.description.info2._v_nested_descr))) print() print("**** and some iteration over descriptions, too ****") for coldescr in table.description._f_walk(): print("column-->", coldescr) print() print("**** info2 sub-structure description:\n", table.description.info2) print() print("**** table representation (long form):\n", repr(table)) # Remember to always close the file fileh.close()
{ "content_hash": "e8462212e563e1cb39a5f383c189ac28", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 77, "avg_line_length": 27.834586466165412, "alnum_prop": 0.6323608860075635, "repo_name": "jack-pappas/PyTables", "id": "9d5ec9ca9753dfdda8a498e78a4d9ef741e05bcf", "size": "3702", "binary": false, "copies": "12", "ref": "refs/heads/develop", "path": "examples/nested-tut.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "901914" }, { "name": "C++", "bytes": "97381" }, { "name": "CSS", "bytes": "2717" }, { "name": "Gnuplot", "bytes": "2104" }, { "name": "JavaScript", "bytes": "3491" }, { "name": "Makefile", "bytes": "11351" }, { "name": "Objective-C", "bytes": "31966" }, { "name": "Python", "bytes": "3594491" }, { "name": "Shell", "bytes": "23613" } ], "symlink_target": "" }
from msrest.serialization import Model class Policy(Model): """A Policy. :param description: The description of the policy. :type description: str :param status: The status of the policy. Possible values include: 'Enabled', 'Disabled' :type status: str or :class:`PolicyStatus <azure.mgmt.devtestlabs.models.PolicyStatus>` :param fact_name: The fact name of the policy. Possible values include: 'UserOwnedLabVmCount', 'LabVmCount', 'LabVmSize', 'GalleryImage', 'UserOwnedLabVmCountInSubnet' :type fact_name: str or :class:`PolicyFactName <azure.mgmt.devtestlabs.models.PolicyFactName>` :param fact_data: The fact data of the policy. :type fact_data: str :param threshold: The threshold of the policy. :type threshold: str :param evaluator_type: The evaluator type of the policy. Possible values include: 'AllowedValuesPolicy', 'MaxValuePolicy' :type evaluator_type: str or :class:`PolicyEvaluatorType <azure.mgmt.devtestlabs.models.PolicyEvaluatorType>` :param provisioning_state: The provisioning status of the resource. :type provisioning_state: str :param unique_identifier: The unique immutable identifier of a resource (Guid). :type unique_identifier: str :param id: The identifier of the resource. :type id: str :param name: The name of the resource. :type name: str :param type: The type of the resource. :type type: str :param location: The location of the resource. :type location: str :param tags: The tags of the resource. :type tags: dict """ _attribute_map = { 'description': {'key': 'properties.description', 'type': 'str'}, 'status': {'key': 'properties.status', 'type': 'str'}, 'fact_name': {'key': 'properties.factName', 'type': 'str'}, 'fact_data': {'key': 'properties.factData', 'type': 'str'}, 'threshold': {'key': 'properties.threshold', 'type': 'str'}, 'evaluator_type': {'key': 'properties.evaluatorType', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'unique_identifier': {'key': 'properties.uniqueIdentifier', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, description=None, status=None, fact_name=None, fact_data=None, threshold=None, evaluator_type=None, provisioning_state=None, unique_identifier=None, id=None, name=None, type=None, location=None, tags=None): self.description = description self.status = status self.fact_name = fact_name self.fact_data = fact_data self.threshold = threshold self.evaluator_type = evaluator_type self.provisioning_state = provisioning_state self.unique_identifier = unique_identifier self.id = id self.name = name self.type = type self.location = location self.tags = tags
{ "content_hash": "7d425384f0a0ed7e61786131b9b799cf", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 229, "avg_line_length": 43.861111111111114, "alnum_prop": 0.6409119696010133, "repo_name": "rjschwei/azure-sdk-for-python", "id": "843303c337d14648e8676815f12cd4fd3a574b75", "size": "3632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/policy.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "8317911" } ], "symlink_target": "" }
from __future__ import absolute_import, print_function, division import unittest from theano.compat import izip from six import iteritems import numpy import theano import theano.tensor as T from theano.tensor import TensorType from theano.tensor.basic import alloc # Don't import test classes otherwise they get tested as part of the file from theano.tensor.tests import test_basic from theano.tensor.tests.test_basic import rand, safe_make_node from theano.tests import unittest_tools as utt from ..type import (GpuArrayType, get_context, gpuarray_shared_constructor) from ..basic_ops import ( host_from_gpu, HostFromGpu, GpuFromHost, GpuReshape, GpuToGpu, GpuAlloc, GpuAllocEmpty, GpuContiguous, gpu_join, GpuJoin, GpuSplit, GpuEye, gpu_contiguous) from ..subtensor import GpuSubtensor from .config import mode_with_gpu, mode_without_gpu, test_ctx_name from pygpu import gpuarray utt.seed_rng() rng = numpy.random.RandomState(seed=utt.fetch_seed()) def inplace_func(inputs, outputs, mode=None, allow_input_downcast=False, on_unused_input='raise', name=None): if mode is None: mode = mode_with_gpu return theano.function(inputs, outputs, mode=mode, allow_input_downcast=allow_input_downcast, accept_inplace=True, on_unused_input=on_unused_input, name=name) def fake_shared(value, name=None, strict=False, allow_downcast=None, **kwargs): from theano.tensor.sharedvar import tensor_constructor, scalar_constructor for c in (gpuarray_shared_constructor, tensor_constructor, scalar_constructor): try: return c(value, name=name, strict=strict, allow_downcast=allow_downcast, **kwargs) except TypeError: continue def rand_gpuarray(*shape, **kwargs): r = rng.rand(*shape) * 2 - 1 dtype = kwargs.pop('dtype', theano.config.floatX) cls = kwargs.pop('cls', None) if len(kwargs) != 0: raise TypeError('Unexpected argument %s', list(kwargs.keys())[0]) return gpuarray.array(r, dtype=dtype, cls=cls, context=get_context(test_ctx_name)) def makeTester(name, op, gpu_op, cases, checks=None, mode_gpu=mode_with_gpu, mode_nogpu=mode_without_gpu, skip=False, eps=1e-10): if checks is None: checks = {} _op = op _gpu_op = gpu_op _cases = cases _skip = skip _checks = checks class Checker(unittest.TestCase, utt.TestOptimizationMixin): op = staticmethod(_op) gpu_op = staticmethod(_gpu_op) cases = _cases skip = _skip checks = _checks def setUp(self): eval(self.__class__.__module__ + '.' + self.__class__.__name__) def test_all(self): if skip: from nose.plugins.skip import SkipTest raise SkipTest(skip) for testname, inputs in iteritems(cases): self.run_case(testname, inputs) def run_case(self, testname, inputs): inputs_ref = [theano.shared(inp) for inp in inputs] inputs_tst = [theano.shared(inp) for inp in inputs] try: node_ref = safe_make_node(self.op, *inputs_ref) node_tst = safe_make_node(self.op, *inputs_tst) except Exception as exc: err_msg = ("Test %s::%s: Error occured while making " "a node with inputs %s") % (self.gpu_op, testname, inputs) exc.args += (err_msg,) raise try: f_ref = inplace_func([], node_ref.outputs, mode=mode_nogpu) f_tst = inplace_func([], node_tst.outputs, mode=mode_gpu) except Exception as exc: err_msg = ("Test %s::%s: Error occured while trying to " "make a Function") % (self.gpu_op, testname) exc.args += (err_msg,) raise self.assertFunctionContains1(f_tst, self.gpu_op) ref_e = None try: expecteds = f_ref() except Exception as exc: ref_e = exc try: variables = f_tst() except Exception as exc: if ref_e is None: err_msg = ("Test %s::%s: exception when calling the " "Function") % (self.gpu_op, testname) exc.args += (err_msg,) raise else: # if we raised an exception of the same type we're good. if isinstance(exc, type(ref_e)): return else: err_msg = ("Test %s::%s: exception raised during test " "call was not the same as the reference " "call (got: %s, expected %s)" % (self.gpu_op, testname, type(exc), type(ref_e))) exc.args += (err_msg,) raise for i, (variable, expected) in \ enumerate(izip(variables, expecteds)): if variable.dtype != expected.dtype or \ variable.shape != expected.shape or \ not TensorType.values_eq_approx(variable, expected): self.fail(("Test %s::%s: Output %s gave the wrong " "value. With inputs %s, expected %s " "(dtype %s), got %s (dtype %s)." % (self.op, testname, i, inputs, expected, expected.dtype, variable, variable.dtype))) for description, check in iteritems(self.checks): if not check(inputs, variables): self.fail(("Test %s::%s: Failed check: %s " "(inputs were %s, ouputs were %s)") % (self.op, testname, description, inputs, variables)) Checker.__name__ = name return Checker def test_transfer_cpu_gpu(): a = T.fmatrix('a') g = GpuArrayType(dtype='float32', broadcastable=(False, False))('g') av = numpy.asarray(rng.rand(5, 4), dtype='float32') gv = gpuarray.array(av, context=get_context(test_ctx_name)) f = theano.function([a], GpuFromHost(test_ctx_name)(a)) fv = f(av) assert GpuArrayType.values_eq(fv, gv) f = theano.function([g], host_from_gpu(g)) fv = f(gv) assert numpy.all(fv == av) def test_transfer_gpu_gpu(): g = GpuArrayType(dtype='float32', broadcastable=(False, False), context_name=test_ctx_name)() av = numpy.asarray(rng.rand(5, 4), dtype='float32') gv = gpuarray.array(av, context=get_context(test_ctx_name)) mode = mode_with_gpu.excluding('cut_gpua_host_transfers', 'local_cut_gpua_host_gpua') f = theano.function([g], GpuToGpu(test_ctx_name)(g), mode=mode) topo = f.maker.fgraph.toposort() assert len(topo) == 1 assert isinstance(topo[0].op, GpuToGpu) fv = f(gv) assert GpuArrayType.values_eq(fv, gv) def test_transfer_strided(): # This is just to ensure that it works in theano # libgpuarray has a much more comprehensive suit of tests to # ensure correctness a = T.fmatrix('a') g = GpuArrayType(dtype='float32', broadcastable=(False, False))('g') av = numpy.asarray(rng.rand(5, 8), dtype='float32') gv = gpuarray.array(av, context=get_context(test_ctx_name)) av = av[:, ::2] gv = gv[:, ::2] f = theano.function([a], GpuFromHost(test_ctx_name)(a)) fv = f(av) assert GpuArrayType.values_eq(fv, gv) f = theano.function([g], host_from_gpu(g)) fv = f(gv) assert numpy.all(fv == av) def gpu_alloc_expected(x, *shp): g = gpuarray.empty(shp, dtype=x.dtype, context=get_context(test_ctx_name)) g[:] = x return g GpuAllocTester = makeTester( name="GpuAllocTester", op=alloc, gpu_op=GpuAlloc(test_ctx_name), cases=dict( correct01=(rand(), numpy.int32(7)), # just gives a DeepCopyOp with possibly wrong results on the CPU # correct01_bcast=(rand(1), numpy.int32(7)), correct02=(rand(), numpy.int32(4), numpy.int32(7)), correct12=(rand(7), numpy.int32(4), numpy.int32(7)), correct13=(rand(7), numpy.int32(2), numpy.int32(4), numpy.int32(7)), correct23=(rand(4, 7), numpy.int32(2), numpy.int32(4), numpy.int32(7)), bad_shape12=(rand(7), numpy.int32(7), numpy.int32(5)), ) ) class TestAlloc(test_basic.TestAlloc): dtype = "float32" mode = mode_with_gpu shared = staticmethod(gpuarray_shared_constructor) allocs = [GpuAlloc(test_ctx_name), GpuAlloc(test_ctx_name), T.Alloc()] def test_alloc_empty(): for dt in ['float32', 'int8']: f = theano.function([], GpuAllocEmpty(dt, context_name=test_ctx_name)(2, 3)) assert len(f.maker.fgraph.apply_nodes) == 1 out = f() assert out.shape == (2, 3) assert out.dtype == dt f = theano.function([], [GpuAllocEmpty('uint64', test_ctx_name)(3, 2), GpuAllocEmpty('uint64', test_ctx_name)(3, 2)]) out = f() assert out[0].shape == (3, 2) assert out[0].dtype == 'uint64' assert out[1].shape == (3, 2) assert out[1].dtype == 'uint64' assert len([node for node in f.maker.fgraph.apply_nodes if isinstance(node.op, GpuAllocEmpty)]) == 1 def test_shape(): x = GpuArrayType(dtype='float32', broadcastable=[False, False, False])() v = gpuarray.zeros((3, 4, 5), dtype='float32', context=get_context(test_ctx_name)) f = theano.function([x], x.shape) topo = f.maker.fgraph.toposort() assert numpy.all(f(v) == (3, 4, 5)) if theano.config.mode != 'FAST_COMPILE': assert len(topo) == 4 assert isinstance(topo[0].op, T.opt.Shape_i) assert isinstance(topo[1].op, T.opt.Shape_i) assert isinstance(topo[2].op, T.opt.Shape_i) assert isinstance(topo[3].op, T.opt.MakeVector) mode = mode_with_gpu.excluding("local_shape_to_shape_i") f = theano.function([x], x.shape, mode=mode) topo = f.maker.fgraph.toposort() assert numpy.all(f(v) == (3, 4, 5)) assert len(topo) == 1 assert isinstance(topo[0].op, T.Shape) def test_gpu_contiguous(): a = T.fmatrix('a') i = T.iscalar('i') a_val = numpy.asarray(numpy.random.rand(4, 5), dtype='float32') # The reshape is needed otherwise we make the subtensor on the CPU # to transfer less data. f = theano.function([a, i], gpu_contiguous(a.reshape((5, 4))[::i]), mode=mode_with_gpu) topo = f.maker.fgraph.toposort() assert any([isinstance(node.op, GpuSubtensor) for node in topo]) assert any([isinstance(node.op, GpuContiguous) for node in topo]) assert f(a_val, 1).flags.c_contiguous assert f(a_val, 2).flags.c_contiguous assert f(a_val, 2).flags.c_contiguous class G_reshape(test_basic.T_reshape): def shortDescription(self): return None def __init__(self, name): test_basic.T_reshape.__init__( self, name, shared=gpuarray_shared_constructor, op=GpuReshape, mode=mode_with_gpu, ignore_topo=(HostFromGpu, GpuFromHost, theano.compile.DeepCopyOp, theano.gpuarray.elemwise.GpuElemwise, theano.tensor.opt.Shape_i, theano.tensor.opt.MakeVector)) assert self.op == GpuReshape class G_comparison(test_basic.test_comparison): def setUp(self): utt.seed_rng() self.mode = mode_with_gpu self.shared = gpuarray_shared_constructor self.dtypes = ['float64', 'float32'] class G_Join_and_Split(test_basic.T_Join_and_Split): def setUp(self): super(G_Join_and_Split, self).setUp() self.mode = mode_with_gpu.excluding('constant_folding') self.join_op = GpuJoin() self.split_op_class = GpuSplit # Use join instead of MakeVector since there is no MakeVector on GPU self.make_vector_op = GpuJoin() # this is to avoid errors with limited devices self.floatX = 'float32' self.hide_error = theano.config.mode not in ['DebugMode', 'DEBUG_MODE'] self.shared = gpuarray_shared_constructor def test_gpusplit_opt(self): rng = numpy.random.RandomState(seed=utt.fetch_seed()) m = self.shared(rng.rand(4, 6).astype(self.floatX)) o = T.Split(2)(m, 0, [2, 2]) f = theano.function([], o, mode=self.mode) assert any([isinstance(node.op, self.split_op_class) for node in f.maker.fgraph.toposort()]) o1, o2 = f() assert numpy.allclose(o1, m.get_value(borrow=True)[:2]) assert numpy.allclose(o2, m.get_value(borrow=True)[2:]) def test_gpujoin_gpualloc(): a = T.fmatrix('a') a_val = numpy.asarray(numpy.random.rand(4, 5), dtype='float32') b = T.fmatrix('b') b_val = numpy.asarray(numpy.random.rand(3, 5), dtype='float32') f = theano.function([a, b], T.join(0, T.zeros_like(a), T.ones_like(b)) + 4, mode=mode_without_gpu) f_gpu = theano.function([a, b], T.join(0, T.zeros_like(a), T.ones_like(b)), mode=mode_with_gpu) f_gpu2 = theano.function([a, b], T.join(0, T.zeros_like(a), T.ones_like(b)) + 4, mode=mode_with_gpu) assert sum([node.op == T.alloc for node in f.maker.fgraph.toposort()]) == 2 assert sum([node.op == T.join for node in f.maker.fgraph.toposort()]) == 1 assert sum([isinstance(node.op, GpuAlloc) for node in f_gpu.maker.fgraph.toposort()]) == 2 assert sum([node.op == gpu_join for node in f_gpu.maker.fgraph.toposort()]) == 1 assert sum([isinstance(node.op, GpuAlloc) for node in f_gpu2.maker.fgraph.toposort()]) == 2 assert sum([node.op == gpu_join for node in f_gpu2.maker.fgraph.toposort()]) == 1 assert numpy.allclose(f(a_val, b_val), f_gpu2(a_val, b_val)) def test_gpueye(): def check(dtype, N, M_=None): # Theano does not accept None as a tensor. # So we must use a real value. M = M_ # Currently DebugMode does not support None as inputs even if this is # allowed. if M is None: M = N N_symb = T.iscalar() M_symb = T.iscalar() k_symb = numpy.asarray(0) out = T.eye(N_symb, M_symb, k_symb, dtype=dtype) f = theano.function([N_symb, M_symb], out, mode=mode_with_gpu) result = numpy.asarray(f(N, M)) assert numpy.allclose(result, numpy.eye(N, M_, dtype=dtype)) assert result.dtype == numpy.dtype(dtype) assert any([isinstance(node.op, GpuEye) for node in f.maker.fgraph.toposort()]) for dtype in ['float32', 'int32', 'float16']: yield check, dtype, 3 # M != N, k = 0 yield check, dtype, 3, 5 yield check, dtype, 5, 3 def test_hostfromgpu_shape_i(): """ Test that the shape is lifted over hostfromgpu """ m = mode_with_gpu.including('local_dot_to_dot22', 'local_dot22_to_dot22scalar', 'specialize') a = T.fmatrix('a') ca = theano.gpuarray.type.GpuArrayType('float32', (False, False))() av = numpy.asarray(numpy.random.rand(5, 4), dtype='float32') cv = gpuarray.asarray(numpy.random.rand(5, 4), dtype='float32', context=get_context(test_ctx_name)) f = theano.function([a], GpuFromHost(test_ctx_name)(a), mode=m) assert any(isinstance(x.op, GpuFromHost) for x in f.maker.fgraph.toposort()) f = theano.function([a], GpuFromHost(test_ctx_name)(a).shape, mode=m) topo = f.maker.fgraph.toposort() assert isinstance(topo[0].op, T.opt.Shape_i) assert isinstance(topo[1].op, T.opt.Shape_i) assert isinstance(topo[2].op, T.opt.MakeVector) assert tuple(f(av)) == (5, 4) f = theano.function([ca], host_from_gpu(ca), mode=m) assert host_from_gpu in [x.op for x in f.maker.fgraph.toposort()] f = theano.function([ca], host_from_gpu(ca).shape, mode=m) topo = f.maker.fgraph.toposort() assert isinstance(topo[0].op, theano.compile.Shape_i) assert isinstance(topo[1].op, theano.compile.Shape_i) assert isinstance(topo[2].op, theano.tensor.opt.MakeVector) assert tuple(f(cv)) == (5, 4)
{ "content_hash": "36fa7cbd935f3fd93025adafa01fff80", "timestamp": "", "source": "github", "line_count": 447, "max_line_length": 89, "avg_line_length": 38.24384787472036, "alnum_prop": 0.5638490786779761, "repo_name": "JazzeYoung/VeryDeepAutoEncoder", "id": "20aa2d09fbe37ca2730f9c8175c1401a22fdfbb6", "size": "17095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "theano/gpuarray/tests/test_basic_ops.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "260790" }, { "name": "C++", "bytes": "323987" }, { "name": "CSS", "bytes": "1750" }, { "name": "Cuda", "bytes": "2767955" }, { "name": "HTML", "bytes": "4611" }, { "name": "Jupyter Notebook", "bytes": "4603376" }, { "name": "Makefile", "bytes": "116" }, { "name": "Python", "bytes": "16514506" }, { "name": "Shell", "bytes": "16447" } ], "symlink_target": "" }
import textwrap from datetime import date import os from collections import OrderedDict # Custom modules. from weather_config_ghcnd import * from weather_config_mshr import * from weather_download_files import * class WeatherConvertToXML: STATES = OrderedDict({ 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MP': 'Northern Mariana Islands', 'MS': 'Mississippi', 'MT': 'Montana', 'NA': 'National', 'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'PR': 'Puerto Rico', 'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VI': 'Virgin Islands', 'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia', 'WY': 'Wyoming' }) MONTHS = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] token = "" def __init__(self, base_path, save_path, debug_output): self.save_path = save_path self.debug_output = debug_output # Extra support files. self.ghcnd_countries = base_path + '/ghcnd-countries.txt' self.ghcnd_inventory = base_path + '/ghcnd-inventory.txt' self.ghcnd_states = base_path + '/ghcnd-states.txt' self.ghcnd_stations = base_path + '/ghcnd-stations.txt' # MSHR support files. self.mshr_stations = base_path + '/mshr_enhanced_201402.txt' def set_token(self, token): self.token = token def get_field_from_definition(self, row, field_definition): return row[(field_definition[FIELD_INDEX_START] - 1):field_definition[FIELD_INDEX_END]] def get_field(self, fields_array, row, index): return row[(fields_array[index][FIELD_INDEX_START] - 1):fields_array[index][FIELD_INDEX_END]] def get_dly_field(self, row, index): return self.get_field(DLY_FIELDS, row, index) def print_row_files(self, row): for field in DLY_FIELDS: print str(field[FIELD_INDEX_NAME]) + " = '" + row[(field[FIELD_INDEX_START] - 1):field[FIELD_INDEX_END]] + "'" def save_file(self, filename, contents): file = open(filename, 'w') file.write(contents) file.close() return filename def get_folder_size(self, folder_name): total_size = 0 for dirpath, dirnames, filenames in os.walk(folder_name): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size def process_one_month_sensor_set(self, records, page): # Default return 0 def process_station_data(self, row): # Default return 0 def get_base_folder(self, station_id, data_type="sensors"): return build_base_save_folder(self.save_path, station_id, data_type) def process_inventory_file(self): print "Processing inventory file" file_stream = open(self.ghcnd_inventory, 'r') csv_header = ['ID', 'SENSORS', 'SENSORS_COUNT', 'MAX_YEARS', 'TOTAL_YEARS_FOR_ALL_SENSORS'] row = file_stream.readline() csv_inventory = {} for row in file_stream: id = self.get_field_from_definition(row, INVENTORY_FIELDS['ID']) sensor_id = self.get_field_from_definition(row, INVENTORY_FIELDS['ELEMENT']) start = int(self.get_field_from_definition(row, INVENTORY_FIELDS['FIRSTYEAR'])) end = int(self.get_field_from_definition(row, INVENTORY_FIELDS['LASTYEAR'])) if id in csv_inventory: new_count = str(int(csv_inventory[id][2]) + 1) new_max = str(max(int(csv_inventory[id][3]), (end - start))) new_total = str(int(csv_inventory[id][3]) + end - start) csv_inventory[id] = [id, (csv_inventory[id][1] + "," + sensor_id), new_count, new_max, new_total] else: csv_inventory[id] = [id, sensor_id, str(1), str(end - start), str(end - start)] path = self.save_path + "/inventory.csv" self.save_csv_file(path, csv_inventory, csv_header) def save_csv_file(self, path, csv_inventory, header): csv_content = "|".join(header) + "\n" for row_id in csv_inventory: csv_content += "|".join(csv_inventory[row_id]) + "\n" self.save_file(path, csv_content) def process_station_file(self, file_name): print "Processing station file: " + file_name file_stream = open(file_name, 'r') row = file_stream.readline() return self.process_station_data(row) def process_sensor_file(self, file_name, max_files, sensor_max=99): print "Processing sensor file: " + file_name file_stream = open(file_name, 'r') month_last = 0 year_last = 0 records = [] page = 0 sensor_count = 0 file_count = 0 for row in file_stream: month = self.get_dly_field(row, DLY_FIELD_MONTH) year = self.get_dly_field(row, DLY_FIELD_YEAR) if (month_last != 0 and year_last != 0) and (sensor_count >= sensor_max or month != month_last or year != year_last): # process set file_count += self.process_one_month_sensor_set(records, page) records = [] if sensor_count >= sensor_max and month == month_last and year == year_last: # start a new page. page += 1 else: # start over. page = 0 sensor_count = 0 records.append(row) sensor_count += 1 if max_files != 0 and file_count >= max_files: # Stop creating more files after the max is reached. break month_last = month year_last = year station_id = self.get_dly_field(records[0], DLY_FIELD_ID) data_size = self.get_folder_size(self.get_base_folder(station_id) + "/" + station_id) print "Created " + str(file_count) + " XML files for a data size of " + str(data_size) + "." return (file_count, data_size) def convert_c2f(self, c): return (9 / 5 * c) + 32 def default_xml_web_service_start(self): field_xml = "" field_xml += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" return field_xml def default_xml_data_start(self, total_records): field_xml = "" field_xml += "<dataCollection pageCount=\"1\" totalCount=\"" + str(total_records) + "\">\n" return field_xml def default_xml_station_start(self): field_xml = "" field_xml = "<stationCollection pageSize=\"100\" pageCount=\"1\" totalCount=\"1\">\n" return field_xml def default_xml_field_date(self, report_date, indent=2): field_xml = "" field_xml += self.get_indent_space(indent) + "<date>" + str(report_date.year) + "-" + str(report_date.month).zfill(2) + "-" + str(report_date.day).zfill(2) + "T00:00:00.000</date>\n" return field_xml def default_xml_mshr_station_additional(self, station_id): """The web service station data is generate from the MSHR data supplemented with GHCN-Daily.""" station_mshr_row = "" stations_mshr_file = open(self.mshr_stations, 'r') for line in stations_mshr_file: if station_id == self.get_field_from_definition(line, MSHR_FIELDS['GHCND_ID']).strip(): station_mshr_row = line break if station_mshr_row == "": return "" additional_xml = "" county = self.get_field_from_definition(station_mshr_row, MSHR_FIELDS['COUNTY']).strip() if county != "": additional_xml += self.default_xml_location_labels("CNTY", "FIPS:-9999", county) country_code = self.get_field_from_definition(station_mshr_row, MSHR_FIELDS['FIPS_COUNTRY_CODE']).strip() country_name = self.get_field_from_definition(station_mshr_row, MSHR_FIELDS['FIPS_COUNTRY_NAME']).strip() if country_code != "" and country_name != "": additional_xml += self.default_xml_location_labels("CNTRY", "FIPS:" + country_code, country_name) return additional_xml def default_xml_location_labels(self, type, id, display_name): label_xml = "" label_xml += self.default_xml_start_tag("locationLabels", 2) label_xml += self.default_xml_element("type", type, 3) label_xml += self.default_xml_element("id", id, 3) label_xml += self.default_xml_element("displayName", display_name, 3) label_xml += self.default_xml_end_tag("locationLabels", 2) return label_xml def default_xml_web_service_station(self, station_id): """The web service station data is generate from available historical sources.""" station_ghcnd_row = "" stations_ghcnd_file = open(self.ghcnd_stations, 'r') for line in stations_ghcnd_file: if station_id == self.get_field_from_definition(line, STATIONS_FIELDS['ID']): station_ghcnd_row = line break xml_station = "" xml_station += self.default_xml_start_tag("station", 1) xml_station += self.default_xml_element("id", "GHCND:" + station_id, 2) xml_station += self.default_xml_element("displayName", self.get_field_from_definition(station_ghcnd_row, STATIONS_FIELDS['NAME']).strip(), 2) xml_station += self.default_xml_element("latitude", self.get_field_from_definition(station_ghcnd_row, STATIONS_FIELDS['LATITUDE']).strip(), 2) xml_station += self.default_xml_element("longitude", self.get_field_from_definition(station_ghcnd_row, STATIONS_FIELDS['LONGITUDE']).strip(), 2) elevation = self.get_field_from_definition(station_ghcnd_row, STATIONS_FIELDS['ELEVATION']).strip() if elevation != "-999.9": xml_station += self.default_xml_element("elevation", elevation, 2) state_code = self.get_field_from_definition(station_ghcnd_row, STATIONS_FIELDS['STATE']).strip() if state_code != "" and state_code in self.STATES: xml_station += self.default_xml_location_labels("ST", "FIPS:" + str(self.STATES.keys().index(state_code)), self.STATES[state_code]) # Add the MSHR data to the station generated information. xml_station += self.default_xml_mshr_station_additional(station_id) xml_station += self.default_xml_end_tag("station", 1) return xml_station def default_xml_day_reading_as_field(self, row, day): day_index = DLY_FIELD_DAY_OFFSET + ((day - 1) * DLY_FIELD_DAY_FIELDS) value = self.get_dly_field(row, day_index); if value == "-9999": return "" field_xml = "" field_id = self.get_dly_field(row, DLY_FIELD_ELEMENT) if field_id in ("MDTN", "MDTX", "MNPN", "MXPN", "TMAX", "TMIN", "TOBS",): # Add both the celcius and fahrenheit temperatures. celcius = float(value) / 10 field_xml += " <" + field_id + "_c>" + str(celcius) + "</" + field_id + "_c>\n" fahrenheit = self.convert_c2f(celcius) field_xml += " <" + field_id + "_f>" + str(fahrenheit) + "</" + field_id + "_f>\n" elif field_id in ("AWND", "EVAP", "PRCP", "THIC", "WESD", "WESF", "WSF1", "WSF2", "WSF5", "WSFG", "WSFI", "WSFM",): # Field values that are in tenths. converted_value = float(value) / 10 field_xml += " <" + field_id + ">" + str(converted_value) + "</" + field_id + ">\n" elif field_id in ("ACMC", "ACMH", "ACSC", "ACSH", "PSUN",): # Fields is a percentage. field_xml += " <" + field_id + ">" + value.strip() + "</" + field_id + ">\n" elif field_id in ("FMTM", "PGTM",): # Fields is a time value HHMM. field_xml += " <" + field_id + ">" + value.strip() + "</" + field_id + ">\n" elif field_id in ("DAEV", "DAPR", "DASF", "DATN", "DATX", "DAWM", "DWPR", "FRGB", "FRGT", "FRTH", "GAHT", "MDSF", "MDWM", "MDEV", "MDPR", "SNOW", "SNWD", "TSUN", "WDF1", "WDF2", "WDF5", "WDFG", "WDFI", "WDFM", "WDMV",): # Fields with no alternation needed. field_xml += " <" + field_id + ">" + value.strip() + "</" + field_id + ">\n" else: field_xml += " <unknown>" + field_id + "</unknown>\n" # print field_xml return field_xml def default_xml_day_reading(self, row, day, indent=2): day_index = DLY_FIELD_DAY_OFFSET + ((day - 1) * DLY_FIELD_DAY_FIELDS) value = self.get_dly_field(row, day_index); mflag = self.get_dly_field(row, day_index + 1); qflag = self.get_dly_field(row, day_index + 2); sflag = self.get_dly_field(row, day_index + 3); if value == "-9999": return "" indent_space = self.get_indent_space(indent) field_id = self.get_dly_field(row, DLY_FIELD_ELEMENT) station_id = "GHCND:" + self.get_dly_field(row, DLY_FIELD_ID) field_xml = "" field_xml += indent_space + "<dataType>" + field_id + "</dataType>\n" field_xml += indent_space + "<station>" + station_id + "</station>\n" field_xml += indent_space + "<value>" + value.strip() + "</value>\n" field_xml += indent_space + "<attributes>\n" field_xml += indent_space + indent_space + "<attribute>" + mflag.strip() + "</attribute>\n" field_xml += indent_space + indent_space + "<attribute>" + qflag.strip() + "</attribute>\n" field_xml += indent_space + indent_space + "<attribute>" + sflag.strip() + "</attribute>\n" field_xml += indent_space + indent_space + "<attribute></attribute>\n" field_xml += indent_space + "</attributes>\n" # print field_xml return field_xml def default_xml_end(self): return textwrap.dedent("""\ </ghcnd_observation>""") def default_xml_data_end(self): return self.default_xml_end_tag("dataCollection", 0) def default_xml_station_end(self): return self.default_xml_end_tag("stationCollection", 0) def default_xml_element(self, tag, data, indent=1): return self.get_indent_space(indent) + "<" + tag + ">" + data + "</" + tag + ">\n" def default_xml_start_tag(self, tag, indent=1): return self.get_indent_space(indent) + "<" + tag + ">\n" def default_xml_end_tag(self, tag, indent=1): return self.get_indent_space(indent) + "</" + tag + ">\n" def get_indent_space(self, indent): return (" " * (4 * indent)) class WeatherWebServiceMonthlyXMLFile(WeatherConvertToXML): """The web service class details how to create files similar to the NOAA web service.""" skip_downloading = False # Station data def process_station_data(self, row): """Adds a single station record file either from downloading the data or generating a similar record.""" station_id = self.get_dly_field(row, DLY_FIELD_ID) download = 0 if self.token is not "" and not self.skip_downloading: download = self.download_station_data(station_id, self.token, True) if download == 0: self.skip_downloading = True # If not downloaded, generate. if download != 0: return download else: # Information for each daily file. station_xml_file = self.default_xml_web_service_start() station_xml_file += self.default_xml_station_start() station_xml_file += self.default_xml_web_service_station(station_id) station_xml_file += self.default_xml_station_end() # Remove white space. station_xml_file = station_xml_file.replace("\n", ""); station_xml_file = station_xml_file.replace(self.get_indent_space(1), ""); # Make sure the station folder is available. ghcnd_xml_station_path = self.get_base_folder(station_id, "stations") if not os.path.isdir(ghcnd_xml_station_path): os.makedirs(ghcnd_xml_station_path) # Save XML string to disk. save_file_name = ghcnd_xml_station_path + station_id + ".xml" save_file_name = self.save_file(save_file_name, station_xml_file) if save_file_name is not "": if self.debug_output: print "Wrote file: " + save_file_name return 1 else: return 0 # Station data def download_station_data(self, station_id, token, reset=False): """Downloads the station data from the web service.""" import time time.sleep(2) # Make sure the station folder is available. ghcnd_xml_station_path = self.get_base_folder(station_id, "stations") if not os.path.isdir(ghcnd_xml_station_path): os.makedirs(ghcnd_xml_station_path) # Build download URL. url = "http://www.ncdc.noaa.gov/cdo-services/services/datasets/GHCND/stations/GHCND:" + station_id + ".xml?token=" + token url_file = urllib.urlopen(url) station_xml_file = "" while (True): line = url_file.readline() if not line: break station_xml_file += line if station_xml_file.find("<cdoError>") != -1: if self.debug_output: print "Error in station download" return 0 # Save XML string to disk. save_file_name = ghcnd_xml_station_path + station_id + ".xml" save_file_name = self.save_file(save_file_name, station_xml_file) if save_file_name is not "": if self.debug_output: print "Wrote file: " + save_file_name return 2 else: return 0 # Sensor data def process_one_month_sensor_set(self, records, page): """Generates records for a station using the web service xml layout.""" found_data = False year = int(self.get_dly_field(records[0], DLY_FIELD_YEAR)) month = int(self.get_dly_field(records[0], DLY_FIELD_MONTH)) station_id = self.get_dly_field(records[0], DLY_FIELD_ID) # Information for each daily file. count = 0 daily_xml_file = "" for day in range(1, 32): try: # TODO find out what is a valid python date range? 1889? # Attempt to see if this is valid date. report_date = date(year, month, day) for record in records: record_xml_snip = self.default_xml_day_reading(record, report_date.day) if record_xml_snip is not "": daily_xml_file += self.default_xml_start_tag("data") daily_xml_file += self.default_xml_field_date(report_date) daily_xml_file += record_xml_snip daily_xml_file += self.default_xml_end_tag("data") found_data = True count += 1 except ValueError: pass daily_xml_file = self.default_xml_web_service_start() + self.default_xml_data_start(count) + daily_xml_file + self.default_xml_data_end() daily_xml_file = daily_xml_file.replace("\n", ""); daily_xml_file = daily_xml_file.replace(self.get_indent_space(1), ""); if not found_data: return 0 # Make sure the station folder is available. ghcnd_xml_station_path = self.get_base_folder(station_id) + "/" + station_id + "/" + str(report_date.year) + "/" if not os.path.isdir(ghcnd_xml_station_path): os.makedirs(ghcnd_xml_station_path) # Save XML string to disk. save_file_name = ghcnd_xml_station_path + build_sensor_save_filename(station_id, report_date, page) save_file_name = self.save_file(save_file_name, daily_xml_file) if save_file_name is not "": if self.debug_output: print "Wrote file: " + save_file_name return 1 else: return 0 def build_base_save_folder(save_path, station_id, data_type="sensors"): # Default station_prefix = station_id[:3] return save_path + data_type + "/" + station_prefix + "/" def build_sensor_save_filename(station_id, report_date, page): # Default return station_id + "_" + str(report_date.year).zfill(4) + str(report_date.month).zfill(2) + "_" + str(page) + ".xml"
{ "content_hash": "429b34e4ad21c6f987c14bdda7b52f31", "timestamp": "", "source": "github", "line_count": 538, "max_line_length": 227, "avg_line_length": 41.446096654275095, "alnum_prop": 0.5500044847071486, "repo_name": "shivani1494/vxquery", "id": "5db090a5171acc421dac81b31889b5c3c2b8fe2a", "size": "23103", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "vxquery-benchmark/src/main/resources/noaa-ghcn-daily/scripts/weather_convert_to_xml.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2383504" }, { "name": "Python", "bytes": "120795" }, { "name": "Shell", "bytes": "36536" }, { "name": "XQuery", "bytes": "252721" }, { "name": "XSLT", "bytes": "17909" } ], "symlink_target": "" }
from __future__ import annotations import json import os import unittest import uuid from contextlib import closing from unittest import mock import MySQLdb.cursors import pytest from parameterized import parameterized from airflow.models import Connection from airflow.models.dag import DAG from airflow.providers.mysql.hooks.mysql import MySqlHook from airflow.utils import timezone SSL_DICT = {"cert": "/tmp/client-cert.pem", "ca": "/tmp/server-ca.pem", "key": "/tmp/client-key.pem"} class TestMySqlHookConn(unittest.TestCase): def setUp(self): super().setUp() self.connection = Connection( conn_type="mysql", login="login", password="password", host="host", schema="schema", ) self.db_hook = MySqlHook() self.db_hook.get_connection = mock.Mock() self.db_hook.get_connection.return_value = self.connection @mock.patch("MySQLdb.connect") def test_get_conn(self, mock_connect): self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["user"] == "login" assert kwargs["passwd"] == "password" assert kwargs["host"] == "host" assert kwargs["db"] == "schema" @mock.patch("MySQLdb.connect") def test_get_uri(self, mock_connect): self.connection.extra = json.dumps({"charset": "utf-8"}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert self.db_hook.get_uri() == "mysql://login:password@host/schema?charset=utf-8" @mock.patch("MySQLdb.connect") def test_get_conn_from_connection(self, mock_connect): conn = Connection(login="login-conn", password="password-conn", host="host", schema="schema") hook = MySqlHook(connection=conn) hook.get_conn() mock_connect.assert_called_once_with( user="login-conn", passwd="password-conn", host="host", db="schema", port=3306 ) @mock.patch("MySQLdb.connect") def test_get_conn_from_connection_with_schema(self, mock_connect): conn = Connection(login="login-conn", password="password-conn", host="host", schema="schema") hook = MySqlHook(connection=conn, schema="schema-override") hook.get_conn() mock_connect.assert_called_once_with( user="login-conn", passwd="password-conn", host="host", db="schema-override", port=3306 ) @mock.patch("MySQLdb.connect") def test_get_conn_port(self, mock_connect): self.connection.port = 3307 self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["port"] == 3307 @mock.patch("MySQLdb.connect") def test_get_conn_charset(self, mock_connect): self.connection.extra = json.dumps({"charset": "utf-8"}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["charset"] == "utf-8" assert kwargs["use_unicode"] is True @mock.patch("MySQLdb.connect") def test_get_conn_cursor(self, mock_connect): self.connection.extra = json.dumps({"cursor": "sscursor"}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["cursorclass"] == MySQLdb.cursors.SSCursor @mock.patch("MySQLdb.connect") def test_get_conn_local_infile(self, mock_connect): self.connection.extra = json.dumps({"local_infile": True}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["local_infile"] == 1 @mock.patch("MySQLdb.connect") def test_get_con_unix_socket(self, mock_connect): self.connection.extra = json.dumps({"unix_socket": "/tmp/socket"}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["unix_socket"] == "/tmp/socket" @mock.patch("MySQLdb.connect") def test_get_conn_ssl_as_dictionary(self, mock_connect): self.connection.extra = json.dumps({"ssl": SSL_DICT}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["ssl"] == SSL_DICT @mock.patch("MySQLdb.connect") def test_get_conn_ssl_as_string(self, mock_connect): self.connection.extra = json.dumps({"ssl": json.dumps(SSL_DICT)}) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["ssl"] == SSL_DICT @mock.patch("MySQLdb.connect") @mock.patch("airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.get_client_type") def test_get_conn_rds_iam(self, mock_client, mock_connect): self.connection.extra = '{"iam":true}' mock_client.return_value.generate_db_auth_token.return_value = "aws_token" self.db_hook.get_conn() mock_connect.assert_called_once_with( user="login", passwd="aws_token", host="host", db="schema", port=3306, read_default_group="enable-cleartext-plugin", ) class TestMySqlHookConnMySqlConnectorPython(unittest.TestCase): def setUp(self): super().setUp() self.connection = Connection( login="login", password="password", host="host", schema="schema", extra='{"client": "mysql-connector-python"}', ) self.db_hook = MySqlHook() self.db_hook.get_connection = mock.Mock() self.db_hook.get_connection.return_value = self.connection @mock.patch("mysql.connector.connect") def test_get_conn(self, mock_connect): self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["user"] == "login" assert kwargs["password"] == "password" assert kwargs["host"] == "host" assert kwargs["database"] == "schema" @mock.patch("mysql.connector.connect") def test_get_conn_port(self, mock_connect): self.connection.port = 3307 self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["port"] == 3307 @mock.patch("mysql.connector.connect") def test_get_conn_allow_local_infile(self, mock_connect): extra_dict = self.connection.extra_dejson extra_dict.update(allow_local_infile=True) self.connection.extra = json.dumps(extra_dict) self.db_hook.get_conn() assert mock_connect.call_count == 1 args, kwargs = mock_connect.call_args assert args == () assert kwargs["allow_local_infile"] == 1 class MockMySQLConnectorConnection: DEFAULT_AUTOCOMMIT = "default" def __init__(self): self._autocommit = self.DEFAULT_AUTOCOMMIT @property def autocommit(self): return self._autocommit @autocommit.setter def autocommit(self, autocommit): self._autocommit = autocommit class TestMySqlHook(unittest.TestCase): def setUp(self): super().setUp() self.cur = mock.MagicMock(rowcount=0) self.conn = mock.MagicMock() self.conn.cursor.return_value = self.cur conn = self.conn class SubMySqlHook(MySqlHook): conn_name_attr = "test_conn_id" def get_conn(self): return conn self.db_hook = SubMySqlHook() @parameterized.expand([(True,), (False,)]) def test_set_autocommit_mysql_connector(self, autocommit): conn = MockMySQLConnectorConnection() self.db_hook.set_autocommit(conn, autocommit) assert conn.autocommit is autocommit def test_get_autocommit_mysql_connector(self): conn = MockMySQLConnectorConnection() assert self.db_hook.get_autocommit(conn) == MockMySQLConnectorConnection.DEFAULT_AUTOCOMMIT def test_set_autocommit_mysqldb(self): autocommit = False self.db_hook.set_autocommit(self.conn, autocommit) self.conn.autocommit.assert_called_once_with(autocommit) def test_get_autocommit_mysqldb(self): self.db_hook.get_autocommit(self.conn) self.conn.get_autocommit.assert_called_once() def test_run_without_autocommit(self): sql = "SQL" self.conn.get_autocommit.return_value = False # Default autocommit setting should be False. # Testing default autocommit value as well as run() behavior. self.db_hook.run(sql, autocommit=False) self.conn.autocommit.assert_called_once_with(False) self.cur.execute.assert_called_once_with(sql) assert self.conn.commit.call_count == 1 def test_run_with_autocommit(self): sql = "SQL" self.db_hook.run(sql, autocommit=True) self.conn.autocommit.assert_called_once_with(True) self.cur.execute.assert_called_once_with(sql) self.conn.commit.assert_not_called() def test_run_with_parameters(self): sql = "SQL" parameters = ("param1", "param2") self.db_hook.run(sql, autocommit=True, parameters=parameters) self.conn.autocommit.assert_called_once_with(True) self.cur.execute.assert_called_once_with(sql, parameters) self.conn.commit.assert_not_called() def test_run_multi_queries(self): sql = ["SQL1", "SQL2"] self.db_hook.run(sql, autocommit=True) self.conn.autocommit.assert_called_once_with(True) for i, item in enumerate(self.cur.execute.call_args_list): args, kwargs = item assert len(args) == 1 assert args[0] == sql[i] assert kwargs == {} calls = [mock.call(sql[0]), mock.call(sql[1])] self.cur.execute.assert_has_calls(calls, any_order=True) self.conn.commit.assert_not_called() def test_bulk_load(self): self.db_hook.bulk_load("table", "/tmp/file") self.cur.execute.assert_called_once_with( """ LOAD DATA LOCAL INFILE '/tmp/file' INTO TABLE table """ ) def test_bulk_dump(self): self.db_hook.bulk_dump("table", "/tmp/file") self.cur.execute.assert_called_once_with( """ SELECT * INTO OUTFILE '/tmp/file' FROM table """ ) def test_serialize_cell(self): assert "foo" == self.db_hook._serialize_cell("foo", None) def test_bulk_load_custom(self): self.db_hook.bulk_load_custom( "table", "/tmp/file", "IGNORE", """FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES""", ) self.cur.execute.assert_called_once_with( """ LOAD DATA LOCAL INFILE '/tmp/file' IGNORE INTO TABLE table FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES """ ) DEFAULT_DATE = timezone.datetime(2015, 1, 1) DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat() DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10] TEST_DAG_ID = "unit_test_dag" class MySqlContext: def __init__(self, client): self.client = client self.connection = MySqlHook.get_connection(MySqlHook.default_conn_name) self.init_client = self.connection.extra_dejson.get("client", "mysqlclient") def __enter__(self): self.connection.set_extra(f'{{"client": "{self.client}"}}') def __exit__(self, exc_type, exc_val, exc_tb): self.connection.set_extra(f'{{"client": "{self.init_client}"}}') @pytest.mark.backend("mysql") class TestMySql(unittest.TestCase): def setUp(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} dag = DAG(TEST_DAG_ID, default_args=args) self.dag = dag def tearDown(self): drop_tables = {"test_mysql_to_mysql", "test_airflow"} with closing(MySqlHook().get_conn()) as conn: with closing(conn.cursor()) as cursor: for table in drop_tables: cursor.execute(f"DROP TABLE IF EXISTS {table}") @parameterized.expand( [ ("mysqlclient",), ("mysql-connector-python",), ] ) @mock.patch.dict( "os.environ", { "AIRFLOW_CONN_AIRFLOW_DB": "mysql://root@mysql/airflow?charset=utf8mb4&local_infile=1", }, ) def test_mysql_hook_test_bulk_load(self, client): with MySqlContext(client): records = ("foo", "bar", "baz") import tempfile with tempfile.NamedTemporaryFile() as f: f.write("\n".join(records).encode("utf8")) f.flush() hook = MySqlHook("airflow_db") with closing(hook.get_conn()) as conn: with closing(conn.cursor()) as cursor: cursor.execute( """ CREATE TABLE IF NOT EXISTS test_airflow ( dummy VARCHAR(50) ) """ ) cursor.execute("TRUNCATE TABLE test_airflow") hook.bulk_load("test_airflow", f.name) cursor.execute("SELECT dummy FROM test_airflow") results = tuple(result[0] for result in cursor.fetchall()) assert sorted(results) == sorted(records) @parameterized.expand( [ ("mysqlclient",), ("mysql-connector-python",), ] ) def test_mysql_hook_test_bulk_dump(self, client): with MySqlContext(client): hook = MySqlHook("airflow_db") priv = hook.get_first("SELECT @@global.secure_file_priv") # Use random names to allow re-running if priv and priv[0]: # Confirm that no error occurs hook.bulk_dump( "INFORMATION_SCHEMA.TABLES", os.path.join(priv[0], f"TABLES_{client}-{uuid.uuid1()}"), ) elif priv == ("",): hook.bulk_dump("INFORMATION_SCHEMA.TABLES", f"TABLES_{client}_{uuid.uuid1()}") else: raise pytest.skip("Skip test_mysql_hook_test_bulk_load since file output is not permitted") @parameterized.expand( [ ("mysqlclient",), ("mysql-connector-python",), ] ) @mock.patch("airflow.providers.mysql.hooks.mysql.MySqlHook.get_conn") def test_mysql_hook_test_bulk_dump_mock(self, client, mock_get_conn): with MySqlContext(client): mock_execute = mock.MagicMock() mock_get_conn.return_value.cursor.return_value.execute = mock_execute hook = MySqlHook("airflow_db") table = "INFORMATION_SCHEMA.TABLES" tmp_file = "/path/to/output/file" hook.bulk_dump(table, tmp_file) from tests.test_utils.asserts import assert_equal_ignore_multiple_spaces assert mock_execute.call_count == 1 query = f""" SELECT * INTO OUTFILE '{tmp_file}' FROM {table} """ assert_equal_ignore_multiple_spaces(self, mock_execute.call_args[0][0], query)
{ "content_hash": "f3ae5bbd2cfce94d2fcf5b979dbbd91b", "timestamp": "", "source": "github", "line_count": 452, "max_line_length": 107, "avg_line_length": 35.389380530973455, "alnum_prop": 0.5873343335833958, "repo_name": "nathanielvarona/airflow", "id": "d7270dafdd8adf4988602442eb74fc52207ea8c3", "size": "16783", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/providers/mysql/hooks/test_mysql.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25980" }, { "name": "Dockerfile", "bytes": "70681" }, { "name": "HCL", "bytes": "3786" }, { "name": "HTML", "bytes": "173025" }, { "name": "JavaScript", "bytes": "142848" }, { "name": "Jinja", "bytes": "38895" }, { "name": "Jupyter Notebook", "bytes": "5482" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "23169682" }, { "name": "R", "bytes": "313" }, { "name": "Shell", "bytes": "211967" }, { "name": "TypeScript", "bytes": "484556" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models class AuthGroup(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(unique=True, max_length=80) class Meta: managed = False db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.IntegerField(primary_key=True) group = models.ForeignKey(AuthGroup) permission = models.ForeignKey('AuthPermission') class Meta: managed = False db_table = 'auth_group_permissions' class AuthPermission(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) content_type = models.ForeignKey('DjangoContentType') codename = models.CharField(max_length=100) class Meta: managed = False db_table = 'auth_permission' class AuthUser(models.Model): id = models.IntegerField(primary_key=True) password = models.CharField(max_length=128) last_login = models.DateTimeField() is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=75) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class AuthUserGroups(models.Model): id = models.IntegerField(primary_key=True) user = models.ForeignKey(AuthUser) group = models.ForeignKey(AuthGroup) class Meta: managed = False db_table = 'auth_user_groups' class AuthUserUserPermissions(models.Model): id = models.IntegerField(primary_key=True) user = models.ForeignKey(AuthUser) permission = models.ForeignKey(AuthPermission) class Meta: managed = False db_table = 'auth_user_user_permissions' class CheckIns(models.Model): token = models.ForeignKey('Tokens', unique=True) store = models.ForeignKey('Stores') registration = models.ForeignKey('SaRegistrations', db_column='registration_ID', blank=True, null=True) # Field name made lowercase. date_time = models.DateTimeField() class Meta: managed = False db_table = 'check_ins' class ClientArrivals(models.Model): client = models.ForeignKey('Clients') store = models.ForeignKey('Stores') datetime = models.DateTimeField() status = models.CharField(max_length=8) url = models.CharField(max_length=45, blank=True) class Meta: managed = False db_table = 'client_arrivals' class Clients(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=45) surname = models.CharField(max_length=45, blank=True) email = models.CharField(max_length=45) age = models.IntegerField(blank=True, null=True) sex = models.IntegerField(blank=True, null=True) telephone = models.CharField(max_length=45, blank=True) customer = models.ForeignKey('Customers') external_id = models.CharField(max_length=45, blank=True) isactive = models.CharField(db_column='isActive', max_length=3) # Field name made lowercase. class Meta: managed = False db_table = 'clients' class ContactPoints(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=45) surname = models.CharField(max_length=45, blank=True) telephone = models.CharField(unique=True, max_length=45) email = models.CharField(unique=True, max_length=45) store = models.ForeignKey('Stores', blank=True, null=True) customer = models.ForeignKey('Customers', db_column='customer_ID') # Field name made lowercase. class Meta: managed = False db_table = 'contact_points' class Customers(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=45) social_address = models.CharField(unique=True, max_length=45) contactpoint_id = models.CharField(db_column='ContactPoint_ID', unique=True, max_length=45, blank=True) # Field name made lowercase. billing_address = models.CharField(db_column='Billing_Address', unique=True, max_length=45) # Field name made lowercase. billing_cc = models.CharField(db_column='Billing_CC', unique=True, max_length=45) # Field name made lowercase. class Meta: managed = False db_table = 'customers' class Devices(models.Model): id = models.IntegerField(primary_key=True) mac_address = models.CharField(unique=True, max_length=45) class Meta: managed = False db_table = 'devices' class DjangoAdminLog(models.Model): id = models.IntegerField(primary_key=True) action_time = models.DateTimeField() user = models.ForeignKey(AuthUser) content_type = models.ForeignKey('DjangoContentType', blank=True, null=True) object_id = models.TextField(blank=True) object_repr = models.CharField(max_length=200) action_flag = models.IntegerField() change_message = models.TextField() class Meta: managed = False db_table = 'django_admin_log' class DjangoContentType(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) app_label = models.CharField(max_length=100) model = models.CharField(max_length=100) class Meta: managed = False db_table = 'django_content_type' class DjangoSession(models.Model): session_key = models.CharField(primary_key=True, max_length=40) session_data = models.TextField() expire_date = models.DateTimeField() class Meta: managed = False db_table = 'django_session' class IpCameras(models.Model): id = models.IntegerField(primary_key=True) ip_address = models.CharField(max_length=17) model = models.CharField(max_length=45, blank=True) store = models.ForeignKey('Stores', blank=True, null=True) class Meta: managed = False db_table = 'ip_cameras' class Products(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=45) price = models.CharField(max_length=45) description = models.IntegerField(blank=True, null=True) category = models.IntegerField(blank=True, null=True) subcategory = models.IntegerField(blank=True, null=True) customer = models.ForeignKey(Customers) internal_code = models.CharField(max_length=45, blank=True) class Meta: managed = False db_table = 'products' class ProductsPurchase(models.Model): purchase = models.ForeignKey('Purchases', db_column='purchase_ID') # Field name made lowercase. product = models.ForeignKey(Products) cantidad = models.CharField(max_length=45) ispurchasable = models.IntegerField(db_column='IsPurchasable') # Field name made lowercase. class Meta: managed = False db_table = 'products_purchase' class Projects(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(unique=True, max_length=15) customer = models.ForeignKey(Customers) class Meta: managed = False db_table = 'projects' class Purchases(models.Model): id = models.IntegerField(primary_key=True) date = models.CharField(max_length=45) time = models.DateTimeField(blank=True, null=True) shop_assistant = models.ForeignKey('ShopAssistants', db_column='shop_assistant') store = models.ForeignKey('Stores', blank=True, null=True) invoice_id = models.CharField(max_length=45, blank=True) class Meta: managed = False db_table = 'purchases' class RfidCards(models.Model): id = models.CharField(primary_key=True, max_length=8) other_info = models.CharField(max_length=45, blank=True) status = models.CharField(max_length=9) client = models.ForeignKey(Clients, blank=True, null=True) class Meta: managed = False db_table = 'rfid_cards' class SaRegistrations(models.Model): id = models.CharField(primary_key=True, max_length=255) creation_date = models.DateTimeField() update_date = models.DateTimeField(blank=True, null=True) device = models.ForeignKey(Devices) class Meta: managed = False db_table = 'sa_registrations' class ShopAssistantShifts(models.Model): shop_assistant = models.ForeignKey('ShopAssistants') store = models.ForeignKey('Stores') date_in = models.DateTimeField() data_time_out = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'shop_assistant_shifts' class ShopAssistants(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=45) surname = models.CharField(max_length=45) email = models.CharField(max_length=45) password = models.CharField(max_length=45) telephone = models.CharField(max_length=45) internal_code = models.CharField(max_length=45) hiring_date = models.CharField(max_length=45, blank=True) customer = models.ForeignKey(Customers) status = models.CharField(max_length=9, blank=True) class Meta: managed = False db_table = 'shop_assistants' class Stores(models.Model): id = models.IntegerField(primary_key=True) city = models.CharField(max_length=45, blank=True) address = models.CharField(unique=True, max_length=45) telephone = models.CharField(unique=True, max_length=45, blank=True) email = models.CharField(unique=True, max_length=45, blank=True) customer = models.ForeignKey(Customers) status = models.CharField(max_length=8, blank=True) def __unicode__(self): return self.city class Meta: managed = False db_table = 'stores' class Tokens(models.Model): id = models.CharField(primary_key=True, max_length=255) sa = models.ForeignKey(ShopAssistants, db_column='SA_id') # Field name made lowercase. creation_datetime = models.DateTimeField(db_column='creation_dateTime') # Field name made lowercase. device = models.ForeignKey(Devices, blank=True, null=True) class Meta: managed = False db_table = 'tokens'
{ "content_hash": "762efd7117ed3fd04ae0fdb47fb860a0", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 136, "avg_line_length": 38.20817843866171, "alnum_prop": 0.6942985016540183, "repo_name": "fcgravalos/CEES-API-v1.0", "id": "5d5d6df38fbf8f5858a677f235aaa67bc77ddf39", "size": "10771", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "models.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "101" }, { "name": "Python", "bytes": "59699" } ], "symlink_target": "" }
import sys import os # -- General configuration ------------------------------------------------ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'FastFeed' copyright = u'2014, daniel@desarrolla2.com' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'fastfeed' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_theme'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'help'
{ "content_hash": "effbc22aaabf12e49788d9941b625aca", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 79, "avg_line_length": 33.25471698113208, "alnum_prop": 0.7109219858156028, "repo_name": "FastFeed/FastFeed", "id": "7453517a1a6ece13eccd4f415a5adcaccebde999", "size": "3550", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "doc/conf.py", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "99625" } ], "symlink_target": "" }
import mock import webob.exc from neutron.api import extensions as neutron_extensions from neutron.api.v2 import attributes from neutron import context import neutron.db.api as db from neutron.extensions import portbindings from neutron import manager from neutron.plugins.cisco.common import cisco_constants as c_const from neutron.plugins.cisco.common import cisco_exceptions as c_exc from neutron.plugins.cisco.common import config as c_conf from neutron.plugins.cisco.db import n1kv_db_v2 from neutron.plugins.cisco.db import n1kv_models_v2 from neutron.plugins.cisco.db import network_db_v2 as cdb from neutron.plugins.cisco import extensions from neutron.plugins.cisco.extensions import n1kv from neutron.plugins.cisco.extensions import network_profile from neutron.plugins.cisco.extensions import policy_profile from neutron.plugins.cisco.n1kv import n1kv_client from neutron.plugins.cisco.n1kv import n1kv_neutron_plugin from neutron.tests.unit import _test_extension_portbindings as test_bindings from neutron.tests.unit.api.v2 import test_base from neutron.tests.unit.db import test_db_base_plugin_v2 as test_plugin from neutron.tests.unit.extensions import test_l3 from neutron.tests.unit.plugins.cisco.n1kv import fake_client from neutron.tests.unit.scheduler import test_l3_agent_scheduler PHYS_NET = 'some-phys-net' VLAN_MIN = 100 VLAN_MAX = 110 TENANT_NOT_ADMIN = 'not_admin' TENANT_TEST = 'test' class FakeResponse(object): """ This object is returned by mocked requests lib instead of normal response. Initialize it with the status code, header and buffer contents you wish to return. """ def __init__(self, status, response_text, headers): self.buffer = response_text self.status_code = status self.headers = headers def json(self, *args, **kwargs): return self.buffer def _fake_setup_vsm(self): """Fake establish Communication with Cisco Nexus1000V VSM.""" self.agent_vsm = True self._populate_policy_profiles() class NetworkProfileTestExtensionManager(object): def get_resources(self): # Add the resources to the global attribute map # This is done here as the setup process won't # initialize the main API router which extends # the global attribute map attributes.RESOURCE_ATTRIBUTE_MAP.update( network_profile.RESOURCE_ATTRIBUTE_MAP) return network_profile.Network_profile.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class PolicyProfileTestExtensionManager(object): def get_resources(self): # Add the resources to the global attribute map # This is done here as the setup process won't # initialize the main API router which extends # the global attribute map attributes.RESOURCE_ATTRIBUTE_MAP.update( policy_profile.RESOURCE_ATTRIBUTE_MAP) return policy_profile.Policy_profile.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class N1kvPluginTestCase(test_plugin.NeutronDbPluginV2TestCase): _plugin_name = ('neutron.plugins.cisco.n1kv.' 'n1kv_neutron_plugin.N1kvNeutronPluginV2') tenant_id = "some_tenant" DEFAULT_RESP_BODY = "" DEFAULT_RESP_CODE = 200 DEFAULT_CONTENT_TYPE = "" fmt = "json" def _make_test_policy_profile(self, name='service_profile'): """ Create a policy profile record for testing purpose. :param name: string representing the name of the policy profile to create. Default argument value chosen to correspond to the default name specified in config.py file. """ uuid = test_base._uuid() profile = {'id': uuid, 'name': name} return n1kv_db_v2.create_policy_profile(profile) def _make_test_profile(self, name='default_network_profile', segment_type=c_const.NETWORK_TYPE_VLAN, segment_range='386-400'): """ Create a profile record for testing purposes. :param name: string representing the name of the network profile to create. Default argument value chosen to correspond to the default name specified in config.py file. :param segment_type: string representing the type of network segment. :param segment_range: string representing the segment range for network profile. """ db_session = db.get_session() profile = {'name': name, 'segment_type': segment_type, 'tenant_id': self.tenant_id, 'segment_range': segment_range} if segment_type == c_const.NETWORK_TYPE_OVERLAY: profile['sub_type'] = 'unicast' profile['multicast_ip_range'] = '0.0.0.0' net_p = n1kv_db_v2.create_network_profile(db_session, profile) n1kv_db_v2.sync_vxlan_allocations(db_session, net_p) elif segment_type == c_const.NETWORK_TYPE_VLAN: profile['physical_network'] = PHYS_NET net_p = n1kv_db_v2.create_network_profile(db_session, profile) n1kv_db_v2.sync_vlan_allocations(db_session, net_p) n1kv_db_v2.create_profile_binding(db_session, self.tenant_id, net_p['id'], c_const.NETWORK) n1kv_db_v2.create_profile_binding(db_session, TENANT_NOT_ADMIN, net_p['id'], c_const.NETWORK) n1kv_db_v2.create_profile_binding(db_session, TENANT_TEST, net_p['id'], c_const.NETWORK) return net_p def setUp(self, ext_mgr=NetworkProfileTestExtensionManager()): """ Setup method for n1kv plugin tests. First step is to define an acceptable response from the VSM to our requests. This needs to be done BEFORE the setUp() function of the super-class is called. This default here works for many cases. If you need something extra, please define your own setUp() function in your test class, and set your DEFAULT_RESPONSE value also BEFORE calling the setUp() of the super-function (this one here). If you have set a value already, it will not be overwritten by this code. """ if not self.DEFAULT_RESP_BODY: self.DEFAULT_RESP_BODY = { "icehouse-pp": {"properties": {"name": "icehouse-pp", "id": "some-uuid-1"}}, "havana_pp": {"properties": {"name": "havana_pp", "id": "some-uuid-2"}}, "dhcp_pp": {"properties": {"name": "dhcp_pp", "id": "some-uuid-3"}}, } # Creating a mock HTTP connection object for requests lib. The N1KV # client interacts with the VSM via HTTP. Since we don't have a VSM # running in the unit tests, we need to 'fake' it by patching the HTTP # library itself. We install a patch for a fake HTTP connection class. # Using __name__ to avoid having to enter the full module path. http_patcher = mock.patch(n1kv_client.requests.__name__ + ".request") FakeHttpConnection = http_patcher.start() # Now define the return values for a few functions that may be called # on any instance of the fake HTTP connection class. self.resp_headers = {"content-type": "application/json"} FakeHttpConnection.return_value = (FakeResponse( self.DEFAULT_RESP_CODE, self.DEFAULT_RESP_BODY, self.resp_headers)) # Patch some internal functions in a few other parts of the system. # These help us move along, without having to mock up even more systems # in the background. # Return a dummy VSM IP address mock.patch(n1kv_client.__name__ + ".Client._get_vsm_hosts", new=lambda self: "127.0.0.1").start() # Return dummy user profiles mock.patch(cdb.__name__ + ".get_credential_name", new=lambda self: {"user_name": "admin", "password": "admin_password"}).start() n1kv_neutron_plugin.N1kvNeutronPluginV2._setup_vsm = _fake_setup_vsm neutron_extensions.append_api_extensions_path(extensions.__path__) # Save the original RESOURCE_ATTRIBUTE_MAP self.saved_attr_map = {} for resource, attrs in attributes.RESOURCE_ATTRIBUTE_MAP.items(): self.saved_attr_map[resource] = attrs.copy() # Update the RESOURCE_ATTRIBUTE_MAP with n1kv specific extended attrs. attributes.RESOURCE_ATTRIBUTE_MAP["networks"].update( n1kv.EXTENDED_ATTRIBUTES_2_0["networks"]) attributes.RESOURCE_ATTRIBUTE_MAP["ports"].update( n1kv.EXTENDED_ATTRIBUTES_2_0["ports"]) self.addCleanup(self.restore_resource_attribute_map) super(N1kvPluginTestCase, self).setUp(self._plugin_name, ext_mgr=ext_mgr) # Create some of the database entries that we require. self._make_test_profile() self._make_test_policy_profile() def restore_resource_attribute_map(self): # Restore the original RESOURCE_ATTRIBUTE_MAP attributes.RESOURCE_ATTRIBUTE_MAP = self.saved_attr_map class TestN1kvNetworkProfiles(N1kvPluginTestCase): def _prepare_net_profile_data(self, segment_type, sub_type=None, segment_range=None, mcast_ip_range=None): netp = {'name': 'netp1', 'segment_type': segment_type, 'tenant_id': self.tenant_id} if segment_type == c_const.NETWORK_TYPE_VLAN: netp['segment_range'] = segment_range or '100-110' netp['physical_network'] = PHYS_NET elif segment_type == c_const.NETWORK_TYPE_OVERLAY: netp['segment_range'] = segment_range or '10000-10010' netp['sub_type'] = sub_type or 'enhanced' netp['multicast_ip_range'] = (mcast_ip_range or "224.1.1.1-224.1.1.10") elif segment_type == c_const.NETWORK_TYPE_TRUNK: netp['sub_type'] = c_const.NETWORK_TYPE_VLAN data = {"network_profile": netp} return data def test_create_network_profile_vlan(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_overlay(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_overlay_missing_subtype(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) data['network_profile'].pop('sub_type') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_network_profile_trunk(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_trunk_missing_subtype(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) data['network_profile'].pop('sub_type') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_network_profile_overlay_unreasonable_seg_range(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, segment_range='10000-1000000001') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_plugin(self): net_p_dict = (self. _prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY)) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) data = {'network_profile': {'name': 'netp2'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) def test_update_network_profile_physical_network_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'physical_network': PHYS_NET}} net_p_req = self.new_update_request('network_profiles', data, net_p['id']) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_segment_type_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': { 'segment_type': c_const.NETWORK_TYPE_OVERLAY}} net_p_req = self.new_update_request('network_profiles', data, net_p['id']) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_sub_type_fail(self): net_p_dict = (self. _prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY)) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) data = {'network_profile': {'sub_type': c_const.NETWORK_TYPE_VLAN}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_network_profiles_with_networks_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'segment_range': '200-210'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) net_data = {'network': {'name': 'net1', n1kv.PROFILE_ID: net_p['id'], 'tenant_id': 'some_tenant'}} network_req = self.new_create_request('networks', net_data) network_res = network_req.get_response(self.api) self.assertEqual(network_res.status_int, 201) data = {'network_profile': {'segment_range': '300-310'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 409) def test_create_overlay_network_profile_invalid_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range='1.1.1.1') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_no_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN)) data['network_profile']['multicast_ip_range'] = '' net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_wrong_split_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.1.1.1.224.1.1.3') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_invalid_minip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '10.0.0.1-224.1.1.3') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_invalid_maxip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.1.1.1-20.0.0.1') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_correct_multicast_pass(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_update_overlay_network_profile_correct_multicast_pass(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) def test_create_overlay_network_profile_reservedip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.0.0.100-224.0.1.100') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_overlay_network_profile_reservedip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.0.11-224.0.0.111'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_vlan_network_profile_multicast_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_trunk_network_profile_segment_range_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'segment_range': '100-200'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_trunk_network_profile_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_create_network_profile_populate_vlan_segment_pool(self): db_session = db.get_session() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', net_p_dict) self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) for vlan in range(VLAN_MIN, VLAN_MAX + 1): self.assertIsNotNone(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, vlan)) self.assertFalse(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, vlan).allocated) self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, VLAN_MIN - 1) self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, VLAN_MAX + 1) def test_delete_network_profile_with_network_fail(self): net_p = self._make_test_profile(name='netp1') net_data = {'network': {'name': 'net1', n1kv.PROFILE_ID: net_p['id'], 'tenant_id': 'some_tenant'}} network_req = self.new_create_request('networks', net_data) network_res = network_req.get_response(self.api) self.assertEqual(network_res.status_int, 201) self._delete('network_profiles', net_p['id'], expected_code=409) def test_delete_network_profile_deallocate_vlan_segment_pool(self): db_session = db.get_session() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) self.assertIsNotNone(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, VLAN_MIN)) self._delete('network_profiles', net_p['network_profile']['id']) for vlan in range(VLAN_MIN, VLAN_MAX + 1): self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, vlan) def test_create_network_profile_rollback_profile_binding(self): """Test rollback of profile binding if network profile create fails.""" db_session = db.get_session() client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) self.new_create_request('network_profiles', net_p_dict) bindings = (db_session.query(n1kv_models_v2.ProfileBinding).filter_by( profile_type="network")) self.assertEqual(3, bindings.count()) def test_create_network_profile_with_old_add_tenant_fail(self): data = self._prepare_net_profile_data('vlan') data['network_profile']['add_tenant'] = 'tenant1' net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(400, res.status_int) def test_create_network_profile_multi_tenants(self): data = self._prepare_net_profile_data('vlan') data['network_profile'][c_const.ADD_TENANTS] = ['tenant1', 'tenant2'] del data['network_profile']['tenant_id'] net_p_req = self.new_create_request('network_profiles', data) net_p_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) res = net_p_req.get_response(self.ext_api) self.assertEqual(201, res.status_int) net_p = self.deserialize(self.fmt, res) db_session = db.get_session() tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) tenant1 = n1kv_db_v2.get_profile_binding(db_session, 'tenant1', net_p['network_profile']['id']) tenant2 = n1kv_db_v2.get_profile_binding(db_session, 'tenant2', net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertIsNotNone(tenant1) self.assertIsNotNone(tenant2) return net_p def test_update_network_profile_multi_tenants(self): net_p = self.test_create_network_profile_multi_tenants() data = {'network_profile': {c_const.ADD_TENANTS: ['tenant1', 'tenant3']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) db_session = db.get_session() # current tenant_id should always present tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) tenant1 = n1kv_db_v2.get_profile_binding(db_session, 'tenant1', net_p['network_profile']['id']) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant4', net_p['network_profile']['id']) tenant3 = n1kv_db_v2.get_profile_binding(db_session, 'tenant3', net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertIsNotNone(tenant1) self.assertIsNotNone(tenant3) data = {'network_profile': {c_const.REMOVE_TENANTS: [self.tenant_id, 'tenant1']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) # current tenant_id should always present tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant1', net_p['network_profile']['id']) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant4', net_p['network_profile']['id']) tenant3 = n1kv_db_v2.get_profile_binding(db_session, 'tenant3', net_p['network_profile']['id']) self.assertIsNotNone(tenant3) # Add new tenant4 to network profile and make sure existing tenants # are not deleted. data = {'network_profile': {c_const.ADD_TENANTS: ['tenant4']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) tenant4 = n1kv_db_v2.get_profile_binding(db_session, 'tenant4', net_p['network_profile']['id']) self.assertIsNotNone(tenant4) def test_get_network_profile_restricted(self): c_conf.CONF.set_override('restrict_network_profiles', True, 'CISCO_N1K') ctx1 = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) sess1 = db.get_session() net_p = self._make_test_profile(name='netp1') n1kv_db_v2.create_profile_binding(sess1, ctx1.tenant_id, net_p['id'], c_const.NETWORK) #network profile binding with creator tenant should always exist profile = n1kv_db_v2.get_network_profile(sess1, net_p['id'], ctx1.tenant_id) self.assertIsNotNone(profile) ctx2 = context.Context(user_id='non_admin', tenant_id='tenant2', is_admin=False) sess2 = db.get_session() self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_network_profile, sess2, net_p['id'], ctx2.tenant_id) def test_get_network_profile_unrestricted(self): c_conf.CONF.set_override('restrict_network_profiles', False, 'CISCO_N1K') ctx1 = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) sess1 = db.get_session() net_p = self._make_test_profile(name='netp1') n1kv_db_v2.create_profile_binding(sess1, ctx1.tenant_id, net_p['id'], c_const.NETWORK) # network profile binding with creator tenant should always exist profile = n1kv_db_v2.get_network_profile(sess1, net_p['id'], ctx1.tenant_id) self.assertIsNotNone(profile) ctx2 = context.Context(user_id='non_admin', tenant_id='tenant2', is_admin=False) sess2 = db.get_session() profile = n1kv_db_v2.get_network_profile(sess2, net_p['id'], ctx2.tenant_id) #network profile will be returned even though the profile is #not bound to tenant of sess2 self.assertIsNotNone(profile) class TestN1kvBasicGet(test_plugin.TestBasicGet, N1kvPluginTestCase): pass class TestN1kvHTTPResponse(test_plugin.TestV2HTTPResponse, N1kvPluginTestCase): pass class TestN1kvPorts(test_plugin.TestPortsV2, N1kvPluginTestCase, test_bindings.PortBindingsTestCase): VIF_TYPE = portbindings.VIF_TYPE_OVS HAS_PORT_FILTER = False _unsupported = ('test_delete_network_if_port_exists', 'test_requested_subnet_id_v4_and_v6') def setUp(self): if self._testMethodName in self._unsupported: self.skipTest("Unsupported test case") super(TestN1kvPorts, self).setUp() def test_create_port_with_default_n1kv_policy_profile_id(self): """Test port create without passing policy profile id.""" with self.port() as port: db_session = db.get_session() pp = n1kv_db_v2.get_policy_profile( db_session, port['port'][n1kv.PROFILE_ID]) self.assertEqual(pp['name'], 'service_profile') def test_create_port_with_n1kv_policy_profile_id(self): """Test port create with policy profile id.""" profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id']}} port_req = self.new_create_request('ports', data) port = self.deserialize(self.fmt, port_req.get_response(self.api)) self.assertEqual(port['port'][n1kv.PROFILE_ID], profile_obj.id) self._delete('ports', port['port']['id']) def test_update_port_with_n1kv_policy_profile_id(self): """Test port update failure while updating policy profile id.""" with self.port() as port: data = {'port': {n1kv.PROFILE_ID: 'some-profile-uuid'}} port_req = self.new_update_request('ports', data, port['port']['id']) res = port_req.get_response(self.api) # Port update should fail to update policy profile id. self.assertEqual(res.status_int, 400) def test_create_first_port_invalid_parameters_fail(self): """Test parameters for first port create sent to the VSM.""" profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id'], }} port_req = self.new_create_request('ports', data) res = port_req.get_response(self.api) self.assertEqual(res.status_int, 500) client_patch.stop() def test_create_next_port_invalid_parameters_fail(self): """Test parameters for subsequent port create sent to the VSM.""" with self.port() as port: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'port': {n1kv.PROFILE_ID: port['port']['n1kv:profile_id'], 'tenant_id': port['port']['tenant_id'], 'network_id': port['port']['network_id']}} port_req = self.new_create_request('ports', data) res = port_req.get_response(self.api) self.assertEqual(res.status_int, 500) client_patch.stop() def test_create_first_port_rollback_vmnetwork(self): """Test whether VMNetwork is cleaned up if port create fails on VSM.""" db_session = db.get_session() profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client. TestClientInvalidResponse) client_patch.start() data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id'], }} self.new_create_request('ports', data) self.assertRaises(c_exc.VMNetworkNotFound, n1kv_db_v2.get_vm_network, db_session, profile_obj.id, network['network']['id']) # Explicit stop of failure response mock from controller required # for network object clean up to succeed. client_patch.stop() def test_create_next_port_rollback_vmnetwork_count(self): """Test whether VMNetwork count if port create fails on VSM.""" db_session = db.get_session() with self.port() as port: pt = port['port'] old_vmn = n1kv_db_v2.get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id']) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client. TestClientInvalidResponse) client_patch.start() data = {'port': {n1kv.PROFILE_ID: pt['n1kv:profile_id'], 'tenant_id': pt['tenant_id'], 'network_id': pt['network_id']}} self.new_create_request('ports', data) new_vmn = n1kv_db_v2.get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id']) self.assertEqual(old_vmn.port_count, new_vmn.port_count) # Explicit stop of failure response mock from controller required # for network object clean up to succeed. client_patch.stop() def test_delete_last_port_vmnetwork_cleanup(self): """Test whether VMNetwork is cleaned up from db on last port delete.""" db_session = db.get_session() with self.port() as port: pt = port['port'] self.assertIsNotNone(n1kv_db_v2. get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id'])) req = self.new_delete_request('ports', port['port']['id']) req.get_response(self.api) # Verify VMNetwork is cleaned up from the database on port delete. self.assertRaises(c_exc.VMNetworkNotFound, n1kv_db_v2.get_vm_network, db_session, pt['n1kv:profile_id'], pt['network_id']) class TestN1kvPolicyProfiles(N1kvPluginTestCase): def setUp(self): """ Setup function for policy profile tests. We need to use the policy profile extension manager for these test cases, so call the super class setup, but pass in the policy profile extension manager. """ super(TestN1kvPolicyProfiles, self).setUp( ext_mgr=PolicyProfileTestExtensionManager()) def test_populate_policy_profile(self): client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient) client_patch.start() instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() instance._populate_policy_profiles() db_session = db.get_session() profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001') self.assertEqual('pp-1', profile['name']) client_patch.stop() def test_populate_policy_profile_delete(self): # Patch the Client class with the TestClient class with mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient): # Patch the _get_total_profiles() method to return a custom value with mock.patch(fake_client.__name__ + '.TestClient._get_total_profiles') as obj_inst: # Return 3 policy profiles obj_inst.return_value = 3 plugin = manager.NeutronManager.get_plugin() plugin._populate_policy_profiles() db_session = db.get_session() profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001') # Verify that DB contains only 3 policy profiles self.assertEqual('pp-1', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000002') self.assertEqual('pp-2', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000003') self.assertEqual('pp-3', profile['name']) self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000004') # Return 2 policy profiles obj_inst.return_value = 2 plugin._populate_policy_profiles() # Verify that the third policy profile is deleted self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000003') def _init_get_policy_profiles(self): # Get the profiles mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient).start() instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() instance._populate_policy_profiles() db_session = db.get_session() return [ n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001'), n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000002') ] def _test_get_policy_profiles(self, expected_profiles, admin): resource = 'policy_profiles' if admin: ctx = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) else: ctx = context.Context(user_id='non_admin', tenant_id='tenant1', is_admin=False) res = self._list(resource, neutron_context=ctx) self.assertEqual(len(expected_profiles), len(res[resource])) profiles = sorted(res[resource]) for i in range(len(profiles)): self.assertEqual(expected_profiles[i].id, profiles[i]['id']) self.assertEqual(expected_profiles[i].name, profiles[i]['name']) def test_get_profiles_unrestricted(self): """ Test unrestricted policy profile retrieval. Test getting policy profiles using the normal unrestricted behavior. We set the flag and attempt to retrieve the port profiles. It should work for both admin and non-admin. """ # Get the profiles profiles = self._init_get_policy_profiles() # Set the restriction flag c_conf.CONF.set_override('restrict_policy_profiles', False, 'CISCO_N1K') # Request the list using non-admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=False) # Request the list using admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=True) def test_get_profiles_restricted(self): """ Test restricted policy profile retrieval. Test getting policy profiles using the restricted behavior. We set the flag and attempt to retrieve the port profiles. It should work for admin and fail for non-admin. """ # Get the profiles profiles = self._init_get_policy_profiles() # Set the restriction flag c_conf.CONF.set_override('restrict_policy_profiles', True, 'CISCO_N1K') # Request the list using non-admin and verify it returns no data self._test_get_policy_profiles(expected_profiles=[], admin=False) # Request the list using admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=True) def test_get_policy_profiles_by_name(self): with mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient): instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() profile = instance._get_policy_profile_by_name('pp-1') self.assertEqual('pp-1', profile['name']) self.assertEqual('00000000-0000-0000-0000-000000000001', profile['id']) self.assertRaises(c_exc.PolicyProfileNameNotFound, instance._get_policy_profile_by_name, "name") class TestN1kvNetworks(test_plugin.TestNetworksV2, N1kvPluginTestCase): def test_plugin(self): self._make_network('json', 'some_net', True, tenant_id=self.tenant_id, set_context=True) req = self.new_list_request('networks', params="fields=tenant_id") req.environ['neutron.context'] = context.Context('', self.tenant_id) res = req.get_response(self.api) self.assertEqual(res.status_int, 200) body = self.deserialize('json', res) self.assertIn('tenant_id', body['networks'][0]) def _prepare_net_data(self, net_profile_id): return {'network': {'name': 'net1', n1kv.PROFILE_ID: net_profile_id, 'tenant_id': self.tenant_id}} def test_create_network_with_default_n1kv_network_profile_id(self): """Test network create without passing network profile id.""" with self.network() as network: db_session = db.get_session() np = n1kv_db_v2.get_network_profile( db_session, network['network'][n1kv.PROFILE_ID]) self.assertEqual(np['name'], 'default_network_profile') def test_create_network_with_n1kv_network_profile_id(self): """Test network create with network profile id.""" profile_obj = self._make_test_profile(name='test_profile') data = self._prepare_net_data(profile_obj.id) network_req = self.new_create_request('networks', data) network = self.deserialize(self.fmt, network_req.get_response(self.api)) self.assertEqual(network['network'][n1kv.PROFILE_ID], profile_obj.id) def test_update_network_with_n1kv_network_profile_id(self): """Test network update failure while updating network profile id.""" with self.network() as network: data = {'network': {n1kv.PROFILE_ID: 'some-profile-uuid'}} network_req = self.new_update_request('networks', data, network['network']['id']) res = network_req.get_response(self.api) # Network update should fail to update network profile id. self.assertEqual(res.status_int, 400) def test_create_network_rollback_deallocate_vlan_segment(self): """Test vlan segment deallocation on network create failure.""" profile_obj = self._make_test_profile(name='test_profile', segment_range='20-23') data = self._prepare_net_data(profile_obj.id) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() self.new_create_request('networks', data) db_session = db.get_session() self.assertFalse(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, 20).allocated) def test_create_network_rollback_deallocate_overlay_segment(self): """Test overlay segment deallocation on network create failure.""" profile_obj = self._make_test_profile('test_np', c_const.NETWORK_TYPE_OVERLAY, '10000-10001') data = self._prepare_net_data(profile_obj.id) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() self.new_create_request('networks', data) db_session = db.get_session() self.assertFalse(n1kv_db_v2.get_vxlan_allocation(db_session, 10000).allocated) def test_delete_network(self): """Regular test case of network deletion. Should return successful.""" res = self._create_network(self.fmt, name='net', admin_state_up=True) network = self.deserialize(self.fmt, res) req = self.new_delete_request('networks', network['network']['id']) res = req.get_response(self.api) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) def test_delete_network_with_subnet(self): """Network deletion fails when a subnet is present on the network.""" with self.subnet() as subnet: net_id = subnet['subnet']['network_id'] req = self.new_delete_request('networks', net_id) res = req.get_response(self.api) self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code) def test_update_network_set_not_shared_multi_tenants2_returns_409(self): """ Verifies that updating a network which cannot be shared, returns a conflict error. """ with self.network(shared=True) as network: res = self._create_port(self.fmt, network['network']['id'], webob.exc.HTTPCreated.code, tenant_id='somebody_else', set_context=True) data = {'network': {'shared': False}} req = self.new_update_request('networks', data, network['network']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPConflict.code) port = self.deserialize(self.fmt, res) self._delete('ports', port['port']['id']) def test_delete_network_if_port_exists(self): """Verify that a network with a port attached cannot be removed.""" res = self._create_network(self.fmt, name='net1', admin_state_up=True) network = self.deserialize(self.fmt, res) net_id = network['network']['id'] res = self._create_port(self.fmt, net_id, webob.exc.HTTPCreated.code) req = self.new_delete_request('networks', net_id) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPConflict.code) class TestN1kvSubnets(test_plugin.TestSubnetsV2, N1kvPluginTestCase): _unsupported = ( 'test_delete_network', 'test_create_subnets_bulk_emulated', 'test_create_subnets_bulk_emulated_plugin_failure') def setUp(self): if self._testMethodName in self._unsupported: self.skipTest("Unsupported test") super(TestN1kvSubnets, self).setUp() def test_port_prevents_network_deletion(self): self.skipTest("plugin does not return standard conflict code") def test_create_subnet_with_invalid_parameters(self): """Test subnet creation with invalid parameters sent to the VSM""" with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'subnet': {'network_id': network['network']['id'], 'cidr': "10.0.0.0/24"}} subnet_req = self.new_create_request('subnets', data) subnet_resp = subnet_req.get_response(self.api) # Subnet creation should fail due to invalid network name self.assertEqual(subnet_resp.status_int, 400) def test_update_subnet_adding_additional_host_routes_and_dns(self): host_routes = [{'destination': '172.16.0.0/24', 'nexthop': '10.0.2.2'}] with self.network() as network: data = {'subnet': {'network_id': network['network']['id'], 'cidr': '10.0.2.0/24', 'ip_version': 4, 'dns_nameservers': ['192.168.0.1'], 'host_routes': host_routes, 'tenant_id': network['network']['tenant_id']}} req = self.new_create_request('subnets', data) subnet = self.deserialize(self.fmt, req.get_response(self.api)) host_routes = [{'destination': '172.16.0.0/24', 'nexthop': '10.0.2.2'}, {'destination': '192.168.0.0/24', 'nexthop': '10.0.2.3'}] dns_nameservers = ['192.168.0.1', '192.168.0.2'] data = {'subnet': {'host_routes': host_routes, 'dns_nameservers': dns_nameservers}} req = self.new_update_request('subnets', data, subnet['subnet']['id']) subnet = self.deserialize(self.fmt, req.get_response(self.api)) self.assertEqual(sorted(subnet['subnet']['host_routes']), sorted(host_routes)) self.assertEqual(sorted(subnet['subnet']['dns_nameservers']), sorted(dns_nameservers)) # In N1K we need to delete the subnet before the network req = self.new_delete_request('subnets', subnet['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_subnet_with_allocation_range(self): with self.network() as network: net_id = network['network']['id'] data = {'subnet': {'network_id': net_id, 'cidr': '10.0.0.0/24', 'ip_version': 4, 'gateway_ip': '10.0.0.1', 'tenant_id': network['network']['tenant_id'], 'allocation_pools': [{'start': '10.0.0.100', 'end': '10.0.0.120'}]}} req = self.new_create_request('subnets', data) subnet = self.deserialize(self.fmt, req.get_response(self.api)) # Check fixed IP not in allocation range kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'], 'ip_address': '10.0.0.10'}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) port = self.deserialize(self.fmt, res) # delete the port self._delete('ports', port['port']['id']) # Check when fixed IP is gateway kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'], 'ip_address': '10.0.0.1'}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) port = self.deserialize(self.fmt, res) # delete the port self._delete('ports', port['port']['id']) req = self.new_delete_request('subnets', subnet['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_requested_subnet_id_v4_and_v6(self): with self.network() as network: net_id = network['network']['id'] res = self._create_subnet(self.fmt, tenant_id='tenant1', net_id=net_id, cidr='10.0.0.0/24', ip_version=4, gateway_ip=attributes.ATTR_NOT_SPECIFIED) subnet1 = self.deserialize(self.fmt, res) res = self._create_subnet(self.fmt, tenant_id='tenant1', net_id=net_id, cidr='2607:f0d0:1002:51::/124', ip_version=6, gateway_ip=attributes.ATTR_NOT_SPECIFIED) subnet2 = self.deserialize(self.fmt, res) kwargs = {"fixed_ips": [{'subnet_id': subnet1['subnet']['id']}, {'subnet_id': subnet2['subnet']['id']}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) port3 = self.deserialize(self.fmt, res) ips = port3['port']['fixed_ips'] self.assertEqual(len(ips), 2) self.assertIn({'ip_address': '10.0.0.2', 'subnet_id': subnet1['subnet']['id']}, ips) self.assertIn({'ip_address': '2607:f0d0:1002:51::2', 'subnet_id': subnet2['subnet']['id']}, ips) res = self._create_port(self.fmt, net_id=net_id) port4 = self.deserialize(self.fmt, res) # Check that a v4 and a v6 address are allocated ips = port4['port']['fixed_ips'] self.assertEqual(len(ips), 2) self.assertIn({'ip_address': '10.0.0.3', 'subnet_id': subnet1['subnet']['id']}, ips) self.assertIn({'ip_address': '2607:f0d0:1002:51::3', 'subnet_id': subnet2['subnet']['id']}, ips) self._delete('ports', port3['port']['id']) self._delete('ports', port4['port']['id']) req = self.new_delete_request('subnets', subnet1['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) req = self.new_delete_request('subnets', subnet2['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_schedule_network_with_subnet_create(self): """Test invocation of explicit scheduling for networks.""" with mock.patch.object(n1kv_neutron_plugin.N1kvNeutronPluginV2, 'schedule_network') as mock_method: # Test with network auto-scheduling disabled c_conf.CONF.set_override('network_auto_schedule', False) # Subnet creation should trigger scheduling for networks with self.subnet(): pass self.assertEqual(1, mock_method.call_count) class TestN1kvL3Test(test_l3.L3NatExtensionTestCase): pass class TestN1kvL3SchedulersTest(test_l3_agent_scheduler.L3SchedulerTestCase): pass
{ "content_hash": "9dc55fdc0a9a9c2cc1455c46728c29ae", "timestamp": "", "source": "github", "line_count": 1277, "max_line_length": 79, "avg_line_length": 50.32263116679718, "alnum_prop": 0.5410662599981326, "repo_name": "kongseokhwan/kulcloud-iitp-neutron", "id": "b388e083fc9f935ce5d4391ba39f7840195d8571", "size": "64874", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "neutron/tests/unit/plugins/cisco/n1kv/test_n1kv_plugin.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Mako", "bytes": "980" }, { "name": "Python", "bytes": "7271508" }, { "name": "Shell", "bytes": "12819" } ], "symlink_target": "" }
from heatclient.common import http from heatclient import exc from heatclient.openstack.common import jsonutils from keystoneclient.v2_0 import client as ksclient def script_keystone_client(token=None): if token: ksclient.Client(auth_url='http://no.where', insecure=False, tenant_id='tenant_id', token=token).AndReturn(FakeKeystone(token)) else: ksclient.Client(auth_url='http://no.where', insecure=False, password='password', tenant_name='tenant_name', username='username').AndReturn(FakeKeystone( 'abcd1234')) def script_heat_list(url=None): if url is None: url = '/stacks?' resp_dict = {"stacks": [ { "id": "1", "stack_name": "teststack", "stack_status": 'CREATE_COMPLETE', "creation_time": "2012-10-25T01:58:47Z" }, { "id": "2", "stack_name": "teststack2", "stack_status": 'IN_PROGRESS', "creation_time": "2012-10-25T01:58:47Z" }] } resp = FakeHTTPResponse(200, 'success, you', {'content-type': 'application/json'}, jsonutils.dumps(resp_dict)) http.HTTPClient.json_request('GET', url).AndReturn((resp, resp_dict)) def script_heat_normal_error(): resp_dict = { "explanation": "The resource could not be found.", "code": 404, "error": { "message": "The Stack (bad) could not be found.", "type": "StackNotFound", "traceback": "", }, "title": "Not Found" } resp = FakeHTTPResponse(400, 'The resource could not be found', {'content-type': 'application/json'}, jsonutils.dumps(resp_dict)) http.HTTPClient.json_request('GET', '/stacks/bad').AndRaise( exc.from_response(resp)) def script_heat_error(resp_string): resp = FakeHTTPResponse(400, 'The resource could not be found', {'content-type': 'application/json'}, resp_string) http.HTTPClient.json_request('GET', '/stacks/bad').AndRaise( exc.from_response(resp)) def fake_headers(): return {'X-Auth-Token': 'abcd1234', 'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'python-heatclient'} class FakeServiceCatalog(): def url_for(self, endpoint_type, service_type): return 'http://192.168.1.5:8004/v1/f14b41234' class FakeKeystone(): service_catalog = FakeServiceCatalog() def __init__(self, auth_token): self.auth_token = auth_token class FakeRaw(): version = 110 class FakeHTTPResponse(): version = 1.1 def __init__(self, status_code, reason, headers, content): self.headers = headers self.content = content self.status_code = status_code self.reason = reason self.raw = FakeRaw() def getheader(self, name, default=None): return self.headers.get(name, default) def getheaders(self): return self.headers.items() def read(self, amt=None): b = self.content self.content = None return b def iter_content(self, chunksize): return self.content def json(self): return jsonutils.loads(self.content)
{ "content_hash": "ea4bcd33cdfa984904bda9d8576acbbd", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 73, "avg_line_length": 29.548387096774192, "alnum_prop": 0.5316593886462883, "repo_name": "jasondunsmore/python-heatclient", "id": "5e8c4416ffb84be6cff77e73bcd07204a060ba9e", "size": "4210", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "heatclient/tests/fakes.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "338186" }, { "name": "Shell", "bytes": "3351" } ], "symlink_target": "" }
import unittest import os os.environ['MIAMI_ENV'] = 'test' import miami from miami.models import Task, TimeSlot, User, Team, Burning from datetime import datetime from mockito import when, unstub def create_entity(entity): miami.db.session.add(entity) miami.db.session.commit() class JobTest(unittest.TestCase): def setUp(self): miami.init_db() team = Team('Log') team.members.append(User('Mike')) create_entity(team) when(miami.utils).now().thenReturn(datetime(2012, 11, 11, 23, 0, 0)) def tearDown(self): unstub() def test_task_zeroing(self): task = Task('title2', 'detail2', estimate=10, price=10, status='PROGRESS', start_time=datetime(2012, 11, 11, 10, 0, 0), team=Team.query.get(1)) task.owner = User.query.get(1) create_entity(task) miami.zeroing() task = Task.query.get(1) self.assertEquals('READY', task.status) self.assertIsNone(task.partner) self.assertEquals(28800.0, task.consuming) self.assertEquals(1, task.time_slots.count()) def test_task_burning(self): task = Task('title2', 'detail2', estimate=10, price=10, status='PROGRESS', start_time=datetime(2012, 11, 11, 10, 0, 0), team=Team.query.get(1)) task.owner = User.query.get(1) create_entity(task) create_entity(Task('title1', 'detail1', estimate=10, price=5, status='DONE', start_time=datetime(2012, 11, 11, 12, 0, 0), team=Team.query.get(1))) create_entity(Task('title3', 'detail3', estimate=0, price=5, status='READY', start_time=datetime(2012, 11, 10, 12, 0, 0), team=Team.query.get(1))) miami.zeroing() burning = Burning.query.get(1) self.assertEquals(datetime(2012, 11, 11, 0, 0, 0),burning.day) self.assertEquals(5,burning.burning) self.assertEquals(15,burning.remaining) self.assertEquals(Team.query.get(1),burning.team)
{ "content_hash": "c3dd49c315f414aa8ec3d46ca5f087bc", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 154, "avg_line_length": 35.96296296296296, "alnum_prop": 0.6436663233779608, "repo_name": "archiechen/miami", "id": "50945e4dd450054ab13d9c5966f6e730a7f04e13", "size": "1942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/job_tests.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "482660" }, { "name": "Python", "bytes": "77790" } ], "symlink_target": "" }
import sys, os, subprocess ADDR2LINE = "addr2line" NULL_DEREF_READ = 0 NULL_DEREF_WRITE = 1 MISALIGN_READ = 2 MISALIGN_WRITE = 3 WRITE_OOB = 4 READ_OOB = 5 READ_UNINIT = 6 UNBOUND_MALLOC = 7 msg2code = [("Possible NULL ptr dereference (read)", NULL_DEREF_READ), ("Possible NULL ptr dereference (write)", NULL_DEREF_WRITE), ("Misaligned read discovered", MISALIGN_READ), ("Misaligned write discovered", MISALIGN_WRITE), ("Write out of bounds", WRITE_OOB), ("Read out of bounds", READ_OOB), ("Read of uninitialized address", READ_UNINIT), ("Unbounded malloc", UNBOUND_MALLOC)] code2warn = { NULL_DEREF_READ : "Null pointer dereference (read)", NULL_DEREF_WRITE : "Null pointer dereference (write)", MISALIGN_READ : "Misaligned read", MISALIGN_WRITE : "Misaligned write", WRITE_OOB : "Write out-of-bounds", READ_OOB : "Read out-of-bounds", READ_UNINIT : "Read of uninitialized address", UNBOUND_MALLOC : "Allocate the entire address space"} __cache = {} def addr2line(exe, addr): if (exe, addr) in __cache: return __cache[(exe, addr)] cmdline = "%s -f -e %s 0x%.8x" % (ADDR2LINE, exe, addr) pipe = subprocess.Popen(cmdline.split(), stdout = subprocess.PIPE) output = pipe.communicate()[0] assert ":" in output output = output.split("\n") func = output[0] source, line = output[1].split(":") __cache[(exe, addr)] = func, source, int(line) return func, source, int(line) # IGNORE = [MISALIGN_WRITE, MISALIGN_READ, NULL_DEREF_WRITE, NULL_DEREF_READ, READ_UNINIT] IGNORE = [] def parsewarn(msg): if msg.startswith("***"): for m, c in msg2code: if m in msg: if not c in IGNORE: a1 = int(msg.split(" ### ")[1].strip(), 16) a2 = int(msg.split(" ### ")[2].strip(), 16) return c, a1, a2 else: return None assert False, "Invalid warning '%s'" % msg else: return None def printwarn(warn, addr, func, source, line, addr2, func2, source2, line2): s = "" if warn is not None: s = code2warn[warn] source = source.replace("/home/martignlo/DATA/Ricerca/TypeInference/", "") source2 = source2.replace("/home/martignlo/DATA/Ricerca/TypeInference/", "") source = "%s@%s:%d" % (func, source, line) source2 = "%s@%s:%d" % (func2, source2, line2) print "%-40s: %.8x : %-40s : %.8x : %s" % (s, addr, source, addr2, source2) if __name__ == "__main__": assert len(sys.argv) == 3 exe = sys.argv[1] log = sys.argv[2] assert os.path.isfile(exe) assert os.path.isfile(log) or log == "/dev/stdin" log = open(log) first = True for warn in log.xreadlines(): warn = warn.strip() warn_ = parsewarn(warn) if warn_: wanr_type, warn_addr1, warn_addr2 = warn_ func1, source1, line1 = addr2line(exe, warn_addr1) func2, source2, line2 = addr2line(exe, warn_addr2) printwarn(wanr_type, warn_addr2, func2, source2, line2, warn_addr1, func1, source1, line1)
{ "content_hash": "a15527b53df93db8b12ec860ec81d638", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 102, "avg_line_length": 35.79775280898876, "alnum_prop": 0.5834902699309479, "repo_name": "bitblaze-fuzzball/d-s-se-directed-tests", "id": "edfa5638d49b91818608422ec75a9eedc6ec43e6", "size": "3209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "warning2source.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "257" }, { "name": "Batchfile", "bytes": "13545" }, { "name": "C", "bytes": "534200" }, { "name": "C++", "bytes": "549713" }, { "name": "Makefile", "bytes": "20692" }, { "name": "OCaml", "bytes": "20346" }, { "name": "Perl", "bytes": "13918" }, { "name": "Python", "bytes": "5430" }, { "name": "Shell", "bytes": "12483" } ], "symlink_target": "" }
from django.conf.urls import url from . import views urlpatterns = [ url(r'^signup/$', views.SignupUserView.as_view(), name='signup'), url(r'^login/$', views.LoginUserView.as_view(), name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), ]
{ "content_hash": "484e3eae33a371a0ba7625e2d3e12061", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 69, "avg_line_length": 32.8, "alnum_prop": 0.5975609756097561, "repo_name": "tuanquanghpvn/bideox", "id": "d8ecb22760d0b30e4ba49bd07bce7b249d208f6b", "size": "328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/users/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "503317" }, { "name": "HTML", "bytes": "1808267" }, { "name": "JavaScript", "bytes": "2866114" }, { "name": "PHP", "bytes": "1684" }, { "name": "Python", "bytes": "35633" } ], "symlink_target": "" }
from setuptools import setup setup(name='mousedb', version='1.1.1', description="MouseDB is a data management and analysis system for experimental animals", long_description=open('README.rst').read(), author='Dave Bridges', author_email='dave.bridges@gmail.com', license='BSD 2-Clause License', packages=['mousedb'], zip_safe=False, install_requires=[ 'Django', # 'Sphinx', # ^^^ Not sure if this is needed on readthedocs.org # 'something else?', ], )
{ "content_hash": "254a0349839ceda686cc6662027ab6ff", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 94, "avg_line_length": 31.27777777777778, "alnum_prop": 0.5896980461811723, "repo_name": "davebridges/mousedb", "id": "7fd355471df2c293fec5534748aaf8518ddc2e0b", "size": "563", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3257" }, { "name": "CSS", "bytes": "95388" }, { "name": "HTML", "bytes": "1616714" }, { "name": "JavaScript", "bytes": "930328" }, { "name": "Makefile", "bytes": "5707" }, { "name": "PHP", "bytes": "81487" }, { "name": "Python", "bytes": "327531" }, { "name": "TeX", "bytes": "327631" } ], "symlink_target": "" }
""" This is a TiddlyWeb plugin which extends the TiddlyWeb filter syntax to add 'oom' (One Of Many) which matches if the named attribute is any of those named in the provided list. It is similar to tiddlywebplugins.mselect but only matches the named attribute against many values, not many possible attributes. This will return all tiddlers with tag blog or published (or both) and then sort by modified: oom=tag:blog,published;sort=-modified Install by adding 'tiddlywebplugins.oom' to 'system_plugins' in tiddlywebconfig.py. """ from itertools import ifilter from tiddlyweb.filters import FILTER_PARSERS from tiddlyweb.store import get_entity OOM_SEPARATOR = ',' test_oom = None def init(config): """ Install the filter. """ global test_oom def select_if_one(attribute, value, entities, environ=None): if environ == None: environ = {} store = environ.get('tiddlyweb.store', None) if environ: try: separator = environ['tiddlyweb.config']['oom.separator'] except (TypeError, KeyError): separator = OOM_SEPARATOR else: separator = config.get('oom.separator', OOM_SEPARATOR) values = value.split(separator) def get_value_in_values(entity): entity = get_entity(entity, store) try: return getattr(entity, attribute) in values except AttributeError: try: return entity.fields[attribute] in values except (AttributeError, KeyError): return False return ifilter(get_value_in_values, entities) def oom_parse(command): attribute, args = command.split(':', 1) def selector(entities, indexable=False, environ=None): return select_if_one(attribute, args, entities, environ=environ) return selector FILTER_PARSERS['oom'] = oom_parse test_oom = select_if_one
{ "content_hash": "c33fd42df969e91ff9907832e88177b7", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 76, "avg_line_length": 27.397260273972602, "alnum_prop": 0.6375, "repo_name": "tiddlyweb/tiddlywebplugins.oom", "id": "81c998847a743010f3bab4b8a254c747060f3a02", "size": "2000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tiddlywebplugins/oom.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "4360" } ], "symlink_target": "" }
""" Test scaffold utilities. """ import unittest from oe_utils.chem.scaffold import Scaffold from openeye.oechem import * class TestScaffold(unittest.TestCase): """ Test Scaffold. """ def setUp(self): """ Set up tests. """ smiles = 'C[C@@]1(C(=O)NC(=O)N(C1=O)C)C2=CCCCC2 (S)-Hexobarbital' self.mol = OEMol() OESmilesToMol(self.mol, smiles) self.engine = Scaffold() def test_murcko_scaffold(self): """ Test Murcko scaffold. """ smiles = self.engine.get_scaffold_smiles(self.mol) scaffold = OEMol() OESmilesToMol(scaffold, 'C1(CNCNC1)C2=CCCCC2') assert smiles == OECreateIsoSmiString(scaffold)
{ "content_hash": "e91621d16649bd1842890eb35ddfeb6b", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 73, "avg_line_length": 24.266666666666666, "alnum_prop": 0.592032967032967, "repo_name": "skearnes/color-features", "id": "3c36866f8debd41844f9daaae3175ca6908a84a1", "size": "728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oe_utils/chem/tests/test_scaffold.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "114006" }, { "name": "Shell", "bytes": "3822" } ], "symlink_target": "" }
"""Italian dictionary""" it = { "LANGUAGE": "Italiano", # Client notifications "config-cleared-notification": "Impostazioni iniziali ripristinate. I cambiamenti saranno memorizzati quando salverai una configurazione valida.", "relative-config-notification": "Caricato i file di configurazione relativi: {}", "connection-attempt-notification": "Tentativo di connessione a {}:{}", # Port, IP "reconnection-attempt-notification": "Connessione col server persa, tentativo di riconnesione in corso", "disconnection-notification": "Disconnesso dal server", "connection-failed-notification": "Connessione col server fallita", "connected-successful-notification": "Connessione al server effettuata con successo", "retrying-notification": "%s, Nuovo tentativo in %d secondi...", # Seconds "reachout-successful-notification": "Collegamento stabilito con {} ({})", "rewind-notification": "Riavvolgo a causa della differenza temporale con {}", # User "fastforward-notification": "Avanzamento rapido a causa della differenza temporale con {}", # User "slowdown-notification": "Rallento a causa della differenza temporale con {}", # User "revert-notification": "Ripristino la velocità di riproduzione normale", "pause-notification": "{} ha messo in pausa", # User "unpause-notification": "{} ha ripreso la riproduzione", # User "seek-notification": "{} è passato da {} a {}", # User, from time, to time "current-offset-notification": "Offset corrente: {} secondi", # Offset "media-directory-list-updated-notification": "Le cartelle multimediali di Syncplay sono state aggiornate.", "room-join-notification": "{} è entranto nella stanza: '{}'", # User "left-notification": "{} ha lasciato la stanza", # User "left-paused-notification": "{} ha lasciato la stanza, {} ha messo in pausa", # User who left, User who paused "playing-notification": "{} sta riproducendo '{}' ({})", # User, file, duration "playing-notification/room-addendum": " nella stanza: '{}'", # Room "not-all-ready": "Non pronti: {}", # Usernames "all-users-ready": "Tutti i partecipanti sono pronti ({} utenti)", # Number of ready users "ready-to-unpause-notification": "Ora sei pronto - premi ancora una volta per riprendere la riproduzione", "set-as-ready-notification": "Ora sei pronto", "set-as-not-ready-notification": "Non sei pronto", "autoplaying-notification": "Riproduzione automatica in {}...", # Number of seconds until playback will start "identifying-as-controller-notification": "Ti sei identificato come gestore della stanza con password '{}'...", "failed-to-identify-as-controller-notification": "{} ha fallito l'identificazione come gestore della stanza.", "authenticated-as-controller-notification": "{} autenticato come gestore della stanza", "created-controlled-room-notification": "Stanza gestita '{}' creata con password '{}'. Per favore salva queste informazioni per una consultazione futura!", # RoomName, operatorPassword "file-different-notification": "Il file che stai riproducendo sembra essere diverso da quello di {}", # User "file-differences-notification": "Il tuo file mostra le seguenti differenze: {}", # Differences "room-file-differences": "Differenze: {}", # File differences (filename, size, and/or duration) "file-difference-filename": "nome", "file-difference-filesize": "dimensione", "file-difference-duration": "durata", "alone-in-the-room": "Non ci sono altri utenti nella stanza", "different-filesize-notification": " (la dimensione del tuo file è diversa da quella degli altri partecipanti!)", "userlist-playing-notification": "{} sta riproducendo:", # Username "file-played-by-notification": "File: {} è in riproduzione da:", # File "no-file-played-notification": "{} non sta riproducendo alcun file", # Username "notplaying-notification": "Partecipanti che non stanno riproducendo alcun file:", "userlist-room-notification": "Nella stanza '{}':", # Room "userlist-file-notification": "File", "controller-userlist-userflag": "Gestore", "ready-userlist-userflag": "Pronto", "update-check-failed-notification": "Controllo automatico degli aggiornamenti di Syncplay {} fallito. Vuoi visitare https://syncplay.pl/ per verificare manualmente la presenza di aggiornamenti?", # Syncplay version "syncplay-uptodate-notification": "Syncplay è aggiornato", "syncplay-updateavailable-notification": "Una nuova versione di Syncplay è disponibile. Vuoi visitare la pagina delle release?", "mplayer-file-required-notification": "Utilizzare Syncplay con mplayer di selezionare il file all'avvio", "mplayer-file-required-notification/example": "Esempio di utilizzo: syncplay [opzioni] [url|percorso/]nomefile", "mplayer2-required": "Syncplay non è compatibile con MPlayer 1.x, per favore utilizza mplayer2 or mpv", "unrecognized-command-notification": "Comando non riconosciuto", "commandlist-notification": "Comandi disponibili:", "commandlist-notification/room": "\tr [nome] - cambia stanza", "commandlist-notification/list": "\tl - mostra la lista di utenti", "commandlist-notification/undo": "\tu - annulla l'ultima ricerca", "commandlist-notification/pause": "\tp - attiva o disattiva la pausa", "commandlist-notification/seek": "\t[s][+-]tempo - salta all'istante di tempo dato, se + o - non è specificato si considera il tempo assoluto in secondi o min:sec", "commandlist-notification/help": "\th - mostra questo help", "commandlist-notification/toggle": "\tt - attiva o disattiva la funzionalità \"pronto\"", "commandlist-notification/create": "\tc [nome] - crea una stanza gestita usando il nome della stanza attuale", "commandlist-notification/auth": "\ta [password] - autentica come gestore della stanza, utilizzando la password del gestore", "commandlist-notification/chat": "\tch [message] - invia un messaggio nella chat della stanza", "syncplay-version-notification": "Versione di Syncplay: {}", # syncplay.version "more-info-notification": "Maggiori informazioni a: {}", # projectURL "gui-data-cleared-notification": "Syncplay ha ripristinato i dati dell'interfaccia relativi ai percorsi e allo stato delle finestre.", "language-changed-msgbox-label": "La lingua sarà cambiata quando avvierai Syncplay.", "promptforupdate-label": "Ti piacerebbe che, di tanto in tanto, Syncplay controllasse automaticamente la presenza di aggiornamenti?", "media-player-latency-warning": "Attenzione: il media player ha impiegato {} secondi per rispondere. Se stai avendo problemi di sincronizzazione, chiudi delle applicazioni per liberare le risorse di sistema e, se ciò non dovesse avere alcun effetto, prova un altro media player.", # Seconds to respond "mpv-unresponsive-error": "mpv non ha risposto per {} secondi, quindi sembra non funzionare correttamente. Per favore, riavvia Syncplay.", # Seconds to respond # Client prompts "enter-to-exit-prompt": "Premi Invio per uscire\n", # Client errors "missing-arguments-error": "Alcuni argomenti obbligatori non sono stati trovati. Fai riferimento a --help", "server-timeout-error": "Connessione col server scaduta", "mpc-slave-error": "Non è possibile avviare MPC in modalità slave!", "mpc-version-insufficient-error": "La tua versione di MPC è troppo vecchia, per favore usa `mpc-hc` >= `{}`", "mpc-be-version-insufficient-error": "La tua versione di MPC è troppo vecchia, per favore usa `mpc-be` >= `{}`", "mpv-version-error": "Syncplay non è compatibile con questa versione di mpv. Per favore usa un'altra versione di mpv (es. Git HEAD).", "player-file-open-error": "Il player non è riuscito ad aprire il file", "player-path-error": "Il path del player non è configurato correttamente. I player supportati sono: mpv, mpv.net, VLC, MPC-HC, MPC-BE e mplayer2", "hostname-empty-error": "Il campo hostname non può essere vuoto", "empty-error": "Il campo {} non può esssere vuoto", # Configuration "media-player-error": "Errore media player: \"{}\"", # Error line "unable-import-gui-error": "Non è possibile importare le librerie di interfaccia grafica. Hai bisogno di PySide per poter utilizzare l'interfaccia grafica.", "unable-import-twisted-error": "Non è possibile importare Twisted. Si prega di installare Twisted v16.4.0 o superiore.", "arguments-missing-error": "Alcuni argomenti obbligatori non sono stati trovati. Fai riferimento a --help", "unable-to-start-client-error": "Impossibile avviare il client", "player-path-config-error": "Il percorso del player non è configurato correttamente. I player supportati sono: mpv, mpv.net, VLC, MPC-HC, MPC-BE e mplayer2.", "no-file-path-config-error": "Deve essere selezionato un file prima di avviare il player", "no-hostname-config-error": "Il campo hostname non può essere vuoto", "invalid-port-config-error": "La porta deve essere valida", "empty-value-config-error": "Il campo {} non può essere vuoto", # Config option "not-json-error": "Non è una stringa con codifica JSON\n", "hello-arguments-error": "Not enough Hello arguments\n", # DO NOT TRANSLATE "version-mismatch-error": "La versione del client è diversa da quella del server\n", "vlc-failed-connection": "Impossibile collegarsi a VLC. Se non hai installato syncplay.lua e stai usando l'ultima versione di VLC, fai riferimento a https://syncplay.pl/LUA/ per istruzioni.", "vlc-failed-noscript": "VLC ha segnalato che lo script di interfaccia syncplay.lua non è stato installato. Per favore, fai riferimento a https://syncplay.pl/LUA/ per istruzioni.", "vlc-failed-versioncheck": "Questa versione di VLC non è supportata da Syncplay.", "feature-sharedPlaylists": "playlist condivise", # used for not-supported-by-server-error "feature-chat": "chat", # used for not-supported-by-server-error "feature-readiness": "pronto", # used for not-supported-by-server-error "feature-managedRooms": "stanze gestite", # used for not-supported-by-server-error "not-supported-by-server-error": "La feature {} non è supportata da questo server..", # feature "shared-playlists-not-supported-by-server-error": "Le playlist condivise potrebbero non essere supportata dal server. È necessario un server con Syncplay {}+ per assicurarsi che funzionino correttamente, tuttavia il server sta utilizzando Syncplay {}.", # minVersion, serverVersion "shared-playlists-disabled-by-server-error": "Le playlist condivise sono state disabilitate nella configurazione del server. Per utilizzarle, dovrai collegarti a un altro server.", "invalid-seek-value": "Valore di ricerca non valido", "invalid-offset-value": "Valore di offset non valido", "switch-file-not-found-error": "Impossibile selezionare il file '{0}'. Syncplay osserva solo le cartelle multimediali specificate.", # File not found "folder-search-timeout-error": "La ricerca nelle cartelle multimediali è stata interrotta perché l'analisi di '{}' sta impiegando troppo tempo. Ciò accade se si aggiunge nella lista di ricerca una cartella con troppe sottocartelle. Per riabilitare la selezione automatica dei file seleziona File->Imposta cartelle multimediali nella barra dei menù e rimuovi questa cartella, o sostituiscila con una sottocartella appropriata. Se la cartella è idonea, è possibile riabilitarla selezionando File->Imposta cartelle multimediali e premendo 'OK'.", # Folder "folder-search-first-file-timeout-error": "La ricerca dei media in '{}' è stata interrotta perché l'accesso alla cartella sta impiegando troppo tempo. Ciò accade se questa si trova in un disco di rete oppure se hai impostato il blocco della rotazione del disco rigido dopo un certo periodo di inattività. Per riabilitare la selezione automatica dei file seleziona File->Imposta cartelle multimediali, quindi rimuovi la cartella oppure risolvi il problema (es. cambiando le impostazioni di risparmio energetico).", # Folder "added-file-not-in-media-directory-error": "Hai selezionato un file in '{}', che non è impostata come cartella multimediale. Puoi aggiungerla come cartella multimediale selezionando File->Imposta cartelle multimediali nella barra dei menù.", # Folder "no-media-directories-error": "Nessuna cartella multimediale è stata configurata. Per permettere il corretto funzionamento delle playlist condivise e la selezione automatica dei file, naviga in File->Imposta cartelle multimediali e specifica dove Syncplay deve ricercare i file multimediali.", "cannot-find-directory-error": "Impossibile trovare la cartella multimediale '{}'. Per aggiornare la lista delle cartelle multimediali seleziona File->Imposta cartelle multimediali dalla barra dei menù e specifica dove Syncplay deve ricercare i file multimediali.", "failed-to-load-server-list-error": "Impossibile caricare la lista dei server pubblici. Per favore, visita https://www.syncplay.pl/ con il tuo browser.", # Client arguments "argument-description": 'Programma per sincronizzare la riproduzione di media player multipli attraverso la rete.', "argument-epilog": 'Se non è specificata alcuna opzione saranno utilizzati i valori _config', "nogui-argument": 'non mostrare l\'interfaccia grafica', "host-argument": 'indirizzo del server', "name-argument": 'username desiderato', "debug-argument": 'modalità debug', "force-gui-prompt-argument": 'mostra la finestra di configurazione', "no-store-argument": 'non salvare i valori in .syncplay', "room-argument": 'stanza di default', "password-argument": 'password del server', "player-path-argument": 'percorso dell\'eseguibile del tuo player', "file-argument": 'file da riprodurre', "args-argument": 'opzioni del player, se hai bisogno di utilizzare opzioni che iniziano con - anteponi un singolo \'--\'', "clear-gui-data-argument": 'ripristina il percorso e i dati impostati tramite interfaccia grafica e salvati come QSettings', "language-argument": 'lingua per i messaggi di Syncplay (de/en/ru/it/es)', "version-argument": 'mostra la tua versione', "version-message": "Stai usando la versione di Syncplay {} ({})", "load-playlist-from-file-argument": "loads playlist from text file (one entry per line)", # TODO: Translate # Client labels "config-window-title": "Configurazione di Syncplay", "connection-group-title": "Impostazioni di connessione", "host-label": "Indirizzo del server: ", "name-label": "Username (opzionale):", "password-label": "Password del server (se necessaria):", "room-label": "Stanza di default: ", "media-setting-title": "Impostazioni del media player", "executable-path-label": "Percorso del media player:", "media-path-label": "Percorso del video (opzionale):", "player-arguments-label": "Opzioni del player (se necessarie):", "browse-label": "Sfoglia", "update-server-list-label": "Aggiorna lista", "more-title": "Mostra altre impostazioni", "never-rewind-value": "Mai", "seconds-suffix": " sec", "privacy-sendraw-option": "Invio semplice", "privacy-sendhashed-option": "Invio cifrato", "privacy-dontsend-option": "Non inviare", "filename-privacy-label": "Nome del file:", "filesize-privacy-label": "Dimensione del file:", "checkforupdatesautomatically-label": "Controlla automaticamente gli aggiornamenti di Syncplay", "slowondesync-label": "Rallenta in caso di sfasamento minimo (non supportato su MPC-HC/BE)", "rewindondesync-label": "Riavvolgi in caso di grande sfasamento (consigliato)", "fastforwardondesync-label": "Avanzamento rapido in caso di ritardo (consigliato)", "dontslowdownwithme-label": "Non rallentare o riavvolgere gli altri utenti (sperimentale)", "pausing-title": "Pausa", "pauseonleave-label": "Metti in pausa quando gli altri utenti lasciano la stanza (es. disconnessione)", "readiness-title": "Stato iniziale di 'pronto'", "readyatstart-label": "Imposta sempre il mio stato come \"pronto\" a guardare", "forceguiprompt-label": "Non mostrare la finestra di configurazione di Syncplay a ogni avvio", # (Inverted) "showosd-label": "Abilita i messaggi OSD", "showosdwarnings-label": "Mostra gli avvisi (es. file differenti, utenti non pronti)", "showsameroomosd-label": "Mostra gli eventi della tua stanza", "shownoncontrollerosd-label": "Mostra gli eventi dei non gestori nelle stanze gestite", "showdifferentroomosd-label": "Mostra gli eventi di altre stanze", "showslowdownosd-label": "Mostra le notifiche di rallentamento / riavvolgimento", "language-label": "Lingua:", "automatic-language": "Predefinita ({})", # Default language "showdurationnotification-label": "Avvisa in caso di mancata corrispondenza della durata del file", "basics-label": "Generali", "readiness-label": "Play/Pausa", "misc-label": "Varie", "core-behaviour-title": "Comportamento principale della stanza", "syncplay-internals-title": "Funzionamento di Syncplay", "syncplay-mediasearchdirectories-title": "Cartelle contenenti i file multimediali", "syncplay-mediasearchdirectories-label": "Cartelle contenenti i file multimediali (un solo percorso per riga)", "sync-label": "Sincronia", # don't have better options as the label won't fit in the panel. "sync-otherslagging-title": "Se gli altri partecipanti non sono sincronizzati...", "sync-youlaggging-title": "Se tu sei non sei sincronizzato...", "messages-label": "Messaggi", "messages-osd-title": "Impostazioni On-Screen Display", "messages-other-title": "Altre impostazioni dello schermo", "chat-label": "Chat", "privacy-label": "Privacy", # Currently unused, but will be brought back if more space is needed in Misc tab "privacy-title": "Impostazioni privacy", "unpause-title": "Premendo play, imposta il tuo stato su \"pronto\" e:", "unpause-ifalreadyready-option": "Riprendi la riproduzione se eri già pronto", "unpause-ifothersready-option": "Riprendi la riproduzione se eri già pronto o se gli altri partecipanti sono pronti (default)", "unpause-ifminusersready-option": "Riprendi la riproduzione se eri già pronto o se un numero minimo di partecipanti è pronto", "unpause-always": "Riprendi sempre la riproduzione", "syncplay-trusteddomains-title": "Domini fidati (per streaming e i contenuti in rete)", "chat-title": "Inserimento messaggi di chat", "chatinputenabled-label": "Abilita la chat su mpv", "chatdirectinput-label": "Abilita la chat istantanea (evita di dover premere Invio per chattare)", "chatinputfont-label": "Font dell'input della chat", "chatfont-label": "Imposta font", "chatcolour-label": "Imposta colore", "chatinputposition-label": "Posizione dell'area di inserimento testo in mpv", "chat-top-option": "In alto", "chat-middle-option": "Al centro", "chat-bottom-option": "In basso", "chatoutputheader-label": "Output messaggi di chat", "chatoutputfont-label": "Font dell'output della chat", "chatoutputenabled-label": "Abilita l'output della chat nel media player (al momento solo mpv è supportato)", "chatoutputposition-label": "Modalità di output", "chat-chatroom-option": "Stile chatroom", "chat-scrolling-option": "A scorrimento", "mpv-key-tab-hint": "[TAB] per attivare le scorciatoie da tastiera e disattivare la chat.", "mpv-key-hint": "[Invio] per inviare un messaggio. [Esc] per uscire dalla modalità chat.", "alphakey-mode-warning-first-line": "Puoi utilizzare temporaneamente i vecchi comandi di mpv con i tasti a-z.", "alphakey-mode-warning-second-line": "Premi [TAB] per ritornare alla modalità chat di Syncplay.", "help-label": "Aiuto", "reset-label": "Elimina configurazione", "run-label": "Avvia Syncplay", "storeandrun-label": "Salva la configurazione e avvia Syncplay", "contact-label": "Sentiti libero di inviare un'e-mail a <a href=\"mailto:dev@syncplay.pl\"><nobr>dev@syncplay.pl</nobr></a>, chattare tramite il <a href=\"https://webchat.freenode.net/?channels=#syncplay\"><nobr>canale IRC #Syncplay</nobr></a> su irc.freenode.net, <a href=\"https://github.com/Uriziel/syncplay/issues\"><nobr>segnalare un problema</nobr></a> su GitHub, <a href=\"https://www.facebook.com/SyncplaySoftware\"><nobr>lasciare un like sulla nostra pagina Facebook</nobr></a>, <a href=\"https://twitter.com/Syncplay/\"><nobr>seguirci su Twitter</nobr></a>, o visitare <a href=\"https://syncplay.pl/\"><nobr>https://syncplay.pl/</nobr></a>. Non usare Syncplay per inviare dati sensibili.", "joinroom-label": "Entra nella stanza", "joinroom-menu-label": "Entra nella stanza {}", "seektime-menu-label": "Vai a...", "undoseek-menu-label": "Annulla vai a...", "play-menu-label": "Play", "pause-menu-label": "Pausa", "playbackbuttons-menu-label": "Mostra i controlli della riproduzione", "autoplay-menu-label": "Mostra il tasto di riproduzione automatica", "autoplay-guipushbuttonlabel": "Riproduci quando tutti sono pronti", "autoplay-minimum-label": "Minimo utenti pronti:", "sendmessage-label": "Invia", "ready-guipushbuttonlabel": "Sono pronto a guardare!", "roomuser-heading-label": "Stanza / Utente", "size-heading-label": "Dimensione", "duration-heading-label": "Durata", "filename-heading-label": "Nome del file", "notifications-heading-label": "Notifiche", "userlist-heading-label": "Lista degli utenti nella stanza", "browseformedia-label": "Seleziona i file multimediali", "file-menu-label": "&File", # & precedes shortcut key "openmedia-menu-label": "&Apri file multimediali", "openstreamurl-menu-label": "Apri indirizzo di &rete", "setmediadirectories-menu-label": "Imposta &cartelle multimediali", "loadplaylistfromfile-menu-label": "&Load playlist from file", # TODO: Translate "saveplaylisttofile-menu-label": "&Save playlist to file", # TODO: Translate "exit-menu-label": "&Esci", "advanced-menu-label": "&Avanzate", "window-menu-label": "&Finestra", "setoffset-menu-label": "Imposta &offset", "createcontrolledroom-menu-label": "&Crea stanza gestita", "identifyascontroller-menu-label": "&Identificati come operatore della stanza", "settrusteddomains-menu-label": "Imposta &domini fidati", "addtrusteddomain-menu-label": "Aggiungi {} come dominio fidato", # Domain "edit-menu-label": "&Modifica", "cut-menu-label": "&Taglia", "copy-menu-label": "&Copia", "paste-menu-label": "&Incolla", "selectall-menu-label": "&Seleziona tutto", "playback-menu-label": "&Riproduzione", "help-menu-label": "&Aiuto", "userguide-menu-label": "Apri guida &utente", "update-menu-label": "Controlla la presenza di &aggiornamenti", "startTLS-initiated": "Tentativo di connessione sicura in corso", "startTLS-secure-connection-ok": "Connessione sicura stabilita ({})", "startTLS-server-certificate-invalid": 'Connessione sicura non riuscita. Il certificato di sicurezza di questo server non è valido. La comunicazione potrebbe essere intercettata da una terza parte. Per ulteriori dettagli e informazioni sulla risoluzione del problema, clicca <a href="https://syncplay.pl/trouble">qui</a>.', "startTLS-not-supported-client": "Questo client non supporta TLS", "startTLS-not-supported-server": "Questo server non supporta TLS", # TLS certificate dialog "tls-information-title": "Informazioni sul certificato", "tls-dialog-status-label": "<strong>Syncplay è connesso a {} tramite una connessione codificata.</strong>", "tls-dialog-desc-label": "La codifica con un certificato digitale mantiene private le informazioni quando vengono<br/>inviate dal/al server {}.", "tls-dialog-connection-label": "Informazioni codificate usando Transport Layer Security (TLS), versione {} usando gli<br/>algoritmi di cifratura: {}.", "tls-dialog-certificate-label": "Certificato rilasciato da {} valido fino al {}.", # About dialog "about-menu-label": "&Informazioni su Syncplay", "about-dialog-title": "Informazioni su Syncplay", "about-dialog-release": "Versione {} release {}", "about-dialog-license-text": "Rilasciato sotto Apache&nbsp;License,&nbsp;Version 2.0", "about-dialog-license-button": "Licenza", "about-dialog-dependencies": "Dipendenze", "setoffset-msgbox-label": "Imposta offset", "offsetinfo-msgbox-label": "Offset (vedi https://syncplay.pl/guide/ per istruzioni):", "promptforstreamurl-msgbox-label": "Apri URL", "promptforstreamurlinfo-msgbox-label": "Indirizzo di rete", "addfolder-label": "Aggiungi cartella", "adduris-msgbox-label": "Aggiungi gli indirizzi alla playlist (uno per riga)", "editplaylist-msgbox-label": "Imposta playlist (una per riga)", "trusteddomains-msgbox-label": "Domini a cui è lecito passare automaticamente (uno per riga)", "createcontrolledroom-msgbox-label": "Crea stanza gestita", "controlledroominfo-msgbox-label": "Inserisci il nome della stanza gestita\r\n(vedi https://syncplay.pl/guide/ per istruzioni):", "identifyascontroller-msgbox-label": "Identificati come operatore della stanza", "identifyinfo-msgbox-label": "Inserisci la password dell'operatore per questa stanza\r\n(vedi https://syncplay.pl/guide/ per istruzioni):", "public-server-msgbox-label": "Seleziona il server pubblico per questa sessione", "megabyte-suffix": " MB", # Tooltips "host-tooltip": "Hostname o indirizzo IP a cui collegarsi e, se necessario, includere la porta (es. syncplay.pl:8999). La sincronizzazione avviene solo con gli utenti collegati allo stesso server/porta.", "name-tooltip": "Il nome utente con cui sarai riconosciuto. Nessuna registrazione necessaria, cosi potrai sempre cambiarlo. Se lasciato vuoto, viene scelto un nome casuale.", "password-tooltip": "La password è necessaria solo in caso di connessione a server privati.", "room-tooltip": "La stanza in cui entrare dopo la connessione. Può assumere qualsiasi nome, ma ricorda che sarai sincronizzato solo con gli utenti nella stessa stanza.", "executable-path-tooltip": "Percorso del media player desiderato (scegliere tra mpv, VLC, MPC-HC/BE or mplayer2).", "media-path-tooltip": "Percorso del video o stream da aprire. Necessario per mplayer2.", "player-arguments-tooltip": "Argomenti da linea di comando aggiuntivi da passare al media player scelto.", "mediasearcdirectories-arguments-tooltip": "Cartelle dove Syncplay cercherà i file multimediali, es. quando usi la funzione click to switch. Syncplay cercherà anche nelle sottocartelle.", "more-tooltip": "Mostra le impostazioni usate meno frequentemente.", "filename-privacy-tooltip": "Modalità di invio al server del nome del file attualmente in riproduzione.", "filesize-privacy-tooltip": "Modalità di invio al server della dimensione del file attualmente in riproduzione.", "privacy-sendraw-tooltip": "Invia questa informazione in chiaro. Questa è l'impostazione predefinita per la maggior parte delle funzionalità.", "privacy-sendhashed-tooltip": "Invia una versione cifrata dell'informazione, rendendola meno visibile agli altri client.", "privacy-dontsend-tooltip": "Non inviare questa informazione al server. Questo garantisce massima privacy.", "checkforupdatesautomatically-tooltip": "Controlla regolarmente la presenza di nuove versioni di Syncplay.", "slowondesync-tooltip": "Riduce temporaneamente la velocità di riproduzione quando c'è bisogno di sincronizzarti con gli altri utenti. Non supportato su MPC-HC/BE.", "dontslowdownwithme-tooltip": "Gli altri utenti non vengono rallentati se non sei sincronizzato. Utile per i gestori della stanza.", "pauseonleave-tooltip": "Mette in pausa la riproduzione se vieni disconnesso o se qualcuno lascia la stanza.", "readyatstart-tooltip": "Imposta il tuo stato su \"pronto\" all'avvio (in caso contrario, sarai su \"non pronto\" finché non cambierai il tuo stato)", "forceguiprompt-tooltip": "La finestra di configurazione non viene mostrata quando apri Syncplay.", "nostore-tooltip": "Avvia Syncplay con la configurazione scelta, ma non salva le impostazioni.", "rewindondesync-tooltip": "Torna indietro quando necessario per ristabilire la sincronizzazione. Disabilitare quest'opzione può causare gravi problemi di sincronizzazione!", "fastforwardondesync-tooltip": "Avanza rapidamente quando non sei sincronizzato col gestore della stanza (usa una posizione fittizia se 'Non rallentare o riavvolgere gli altri utenti' è abilitato).", "showosd-tooltip": "Invia i messaggi di Syncplay al media player tramite OSD.", "showosdwarnings-tooltip": "Mostra gli avvisi in caso di riproduzione di un file differente, se sei l'unico utente nella stanza, se ci sono utenti non pronti, ecc.", "showsameroomosd-tooltip": "Mostra le notifiche OSD per gli eventi relativi alla stanza in cui si trova l'utente.", "shownoncontrollerosd-tooltip": "Mostra le notifiche OSD per gli eventi relativi ai non operatori presenti nelle stanze gestite.", "showdifferentroomosd-tooltip": "Mostra le notifiche OSD per gli eventi relativi alle stanze in cui l'utente non si trova.", "showslowdownosd-tooltip": "Mostra le notifiche di rallentamento / riavvolgimento in caso di differenza temporale.", "showdurationnotification-tooltip": "Utile quando manca un segmento di un file con più parti. Può causare dei falsi positivi.", "language-tooltip": "Lingua da utilizzare in Syncplay.", "unpause-always-tooltip": "Se riprendi la riproduzione, il tuo stato cambia in \"pronto\" e la riproduzione viene avviata, piuttosto che impostarti solo su pronto.", "unpause-ifalreadyready-tooltip": "Se riprendi la riproduzione quando non sei \"pronto\", verrai impostato su pronto - ripeti il comando ancora una volta per avviare la riproduzione.", "unpause-ifothersready-tooltip": "Se riprendi la riproduzione quando non sei \"pronto\" la riproduzione verrà avviata solo se gli altri sono pronti.", "unpause-ifminusersready-tooltip": "Se riprendi la riproduzione quando non sei \"pronto\", la riproduzione verrà avviata solo se un numero minimo di utenti è \"pronto\".", "trusteddomains-arguments-tooltip": "Domini verso cui è possibile collegarsi automaticamente quando le playlist condivise sono abilitate.", "chatinputenabled-tooltip": "Abilita l'input della chat in mpv (premi Invio per chattare, per inviare ed Esc per cancellare)", "chatdirectinput-tooltip": "Evita di dover premere Invio per aprire l'input della chat in mpv. Premi TAB in mpv per disabilitare temporaneamente questa funzione.", "font-label-tooltip": "Font usato nell'input della chat in mpv. Non influenza cosa vedono gli altri, vale solo per te.", "set-input-font-tooltip": "Font usato nell'input della chat in mpv. Non influenza cosa vedono gli altri, vale solo per te.", "set-input-colour-tooltip": "Colore del font usato nell'input della chat in mpv. Non influenza cosa vedono gli altri, vale solo per te.", "chatinputposition-tooltip": "Posizione dell'input della chat in mpv quando premi Invio.", "chatinputposition-top-tooltip": "Posiziona l'input della chat in cima alla finestra di mpv.", "chatinputposition-middle-tooltip": "Posizione l'input della chat al centro della finestra di mpv.", "chatinputposition-bottom-tooltip": "Posiziona l'input della chat in basso alla finestra di mpv.", "chatoutputenabled-tooltip": "Mostra i messaggi di chat nell'OSD (se supportato dal media player).", "font-output-label-tooltip": "Font dell'output della chat.", "set-output-font-tooltip": "Font usato per mostrare i messaggi di chat.", "chatoutputmode-tooltip": "Come sono mostrati i messaggi di chat.", "chatoutputmode-chatroom-tooltip": "Mostra i nuovi messaggi di chat al di sotto di quelli precedenti.", "chatoutputmode-scrolling-tooltip": "Scorri il testo della chat da destra a sinistra.", "help-tooltip": "Apri la guida utente su syncplay.pl.", "reset-tooltip": "Ripristina le impostazioni iniziali di Syncplay.", "update-server-list-tooltip": "Scarica la lista dei server pubblici da syncplay.pl.", "sslconnection-tooltip": "Connessione sicura al server. Clicca per informazioni sul certificato.", "joinroom-tooltip": "Lascia la stanza attuale e entra in quella specificata.", "seektime-msgbox-label": "Salta all'istante di tempo specificato (in secondi / min:sec). Usa +/- per una ricerca relativa.", "ready-tooltip": "Indica quando sei pronto a guardare.", "autoplay-tooltip": "Avvia la riproduzione automatica quando il numero minimo di utenti è pronto.", "switch-to-file-tooltip": "Doppio click per passare a {}", # Filename "sendmessage-tooltip": "Invia il messaggio alla stanza", # In-userlist notes (GUI) "differentsize-note": "Dimensione file diversa!", "differentsizeandduration-note": "Durata e dimensione file diversi!", "differentduration-note": "Durata diversa!", "nofile-note": "(Nessun file in riproduzione)", # Server messages to client "new-syncplay-available-motd-message": "Stai usando Syncplay {} ma una nuova versione è disponibile presso https://syncplay.pl", # ClientVersion # Server notifications "welcome-server-notification": "Benvenuto nel server Syncplay, ver. {0}", # version "client-connected-room-server-notification": "{0}({2}) connesso alla stanza '{1}'", # username, host, room "client-left-server-notification": "{0} ha lasciato il server", # name "no-salt-notification": "NOTA BENE: In futuro, per consentire il corretto funzionamento delle password generate da questo server (per le stanze gestite), aggiungi da linea di comando il seguente argomento prima di avviare il server Syncplay: --salt {}", # Salt # Server arguments "server-argument-description": 'Programma per sincronizzare la riproduzione di media player multipli attraverso la rete. Modulo server.', "server-argument-epilog": 'Se non è specificata alcuna opzione saranno utilizzati i valori _config', "server-port-argument": 'Porta TCP del server', "server-password-argument": 'password del server', "server-isolate-room-argument": 'Mantiene le stanze isolate', "server-salt-argument": "usare stringhe casuali per generare le password delle stanze gestite", "server-disable-ready-argument": "disabilita la funzionalità \"pronto\"", "server-motd-argument": "percorso del file da cui verrà letto il messaggio del giorno", "server-chat-argument": "abilita o disabilita la chat", "server-chat-maxchars-argument": "Numero massimo di caratteri in un messaggio di chat (default è {})", # Default number of characters "server-maxusernamelength-argument": "Numero massimo di caratteri in un nome utente (default è {})", "server-stats-db-file-argument": "Abilita la raccolta dei dati statistici nel file SQLite indicato", "server-startTLS-argument": "Abilita il protocollo TLS usando i certificati contenuti nel percorso indicato", "server-messed-up-motd-unescaped-placeholders": "Il messaggio del giorno ha dei caratteri non 'escaped'. Tutti i simboli $ devono essere doppi ($$).", "server-messed-up-motd-too-long": "Il messaggio del giorno è troppo lungo - numero massimo di caratteri è {}, {} trovati.", # Server errors "unknown-command-server-error": "Comando non riconosciuto {}", # message "not-json-server-error": "Non è una stringa in codifica JSON {}", # message "line-decode-server-error": "Non è una stringa utf-8", "not-known-server-error": "Devi essere autenticato dal server prima di poter inviare questo comando", "client-drop-server-error": "Il client è caduto: {} -- {}", # host, error "password-required-server-error": "È richiesta una password", "wrong-password-server-error": "La password inserita è errata", "hello-server-error": "Not enough Hello arguments", # DO NOT TRANSLATE # Playlists "playlist-selection-changed-notification": "{} ha cambiato il file selezionato nella playlist", # Username "playlist-contents-changed-notification": "{} ha aggiornato la playlist", # Username "cannot-find-file-for-playlist-switch-error": "Impossibile trovare il file {} nelle cartelle multimediali per permettere il cambio di file tramite la playlist!", # Filename "cannot-add-duplicate-error": "Impossibile aggiungere una seconda voce per '{}' alla playlist. Non è possibile avere file duplicati.", # Filename "cannot-add-unsafe-path-error": "Impossibile caricare automaticamente {} perché non è presente nei domini fidati. Puoi passare all'inserimento manuale facendo doppio click sull'indirizzo nella playlist, oppure aggiungerlo ai domini fidati tramite File->Avanzate->Imposta domini fidati. Cliccando col tasto destro del mouse su un indirizzo puoi impostare il suo dominio come fidato tramite il menù contestuale.", # Filename "sharedplaylistenabled-label": "Abilita le playlist condivise", "removefromplaylist-menu-label": "Rimuovi dalla playlist", "shuffleremainingplaylist-menu-label": "Mescola i file non ancora riprodotti", "shuffleentireplaylist-menu-label": "Mescola l'intera playlist", "undoplaylist-menu-label": "Annulla l'ultima modifica alla playlist", "addfilestoplaylist-menu-label": "Aggiungi un file alla fine della playlist", "addurlstoplaylist-menu-label": "Aggiungi un indirizzo alla fine della playlist", "editplaylist-menu-label": "Modifica la playlist", "open-containing-folder": "Apri la cartella contenente questo file", "addyourfiletoplaylist-menu-label": "Aggiungi il tuo file alla playlist", "addotherusersfiletoplaylist-menu-label": "Aggiungi il file di {} alla playlist", # Username "addyourstreamstoplaylist-menu-label": "Aggiungi il tuo indirizzo alla playlist", "addotherusersstreamstoplaylist-menu-label": "Aggiungi l'indirizzo di {} alla playlist", # Username # item owner indicator "openusersstream-menu-label": "Apri l'indirizzo di {}", # [username] "openusersfile-menu-label": "Apri il file di {}", # [username]'s "playlist-instruction-item-message": "Trascina qui i file per aggiungerli alla playlist condivisa.", "sharedplaylistenabled-tooltip": "Gli operatori della stanza possono aggiungere i file a una playlist sincronizzata per garantire che tutti i partecipanti stiano guardando la stessa cosa. Configura le cartelle multimediali alla voce 'Miscellanea'.", }
{ "content_hash": "f049b43161a5f66bf671a4d93efcdddf", "timestamp": "", "source": "github", "line_count": 504, "max_line_length": 703, "avg_line_length": 76.93849206349206, "alnum_prop": 0.7316192588390025, "repo_name": "NeverDecaf/syncplay", "id": "ee18fbda39abe0c0face17be6835f088f8aa9fa0", "size": "38888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "syncplay/messages_it.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Lua", "bytes": "51414" }, { "name": "Makefile", "bytes": "3490" }, { "name": "Python", "bytes": "744917" }, { "name": "Rich Text Format", "bytes": "17669" }, { "name": "Shell", "bytes": "6073" } ], "symlink_target": "" }
""" Blei's LDA-C format. """ from __future__ import with_statement from os import path import logging from gensim import interfaces, utils from gensim.corpora import IndexedCorpus from six.moves import xrange logger = logging.getLogger('gensim.corpora.bleicorpus') class BleiCorpus(IndexedCorpus): """ Corpus in Blei's LDA-C format. The corpus is represented as two files: one describing the documents, and another describing the mapping between words and their ids. Each document is one line:: N fieldId1:fieldValue1 fieldId2:fieldValue2 ... fieldIdN:fieldValueN The vocabulary is a file with words, one word per line; word at line K has an implicit ``id=K``. """ def __init__(self, fname, fname_vocab=None): """ Initialize the corpus from a file. `fname_vocab` is the file with vocabulary; if not specified, it defaults to `fname.vocab`. """ IndexedCorpus.__init__(self, fname) logger.info("loading corpus from %s" % fname) if fname_vocab is None: fname_base, _ = path.splitext(fname) fname_dir = path.dirname(fname) for fname_vocab in [ fname + '.vocab', fname + '/vocab.txt', fname_base + '.vocab', fname_dir + '/vocab.txt', ]: if path.exists(fname_vocab): break else: raise IOError('BleiCorpus: could not find vocabulary file') self.fname = fname with utils.smart_open(fname_vocab) as fin: words = [utils.to_unicode(word).rstrip() for word in fin] self.id2word = dict(enumerate(words)) self.length = 0 def __iter__(self): """ Iterate over the corpus, returning one sparse vector at a time. """ lineno = -1 with utils.smart_open(self.fname) as fin: for lineno, line in enumerate(fin): yield self.line2doc(line) self.length = lineno + 1 def line2doc(self, line): parts = utils.to_unicode(line).split() if int(parts[0]) != len(parts) - 1: raise ValueError("invalid format in %s: %s" % (self.fname, repr(line))) doc = [part.rsplit(':', 1) for part in parts[1:]] doc = [(int(p1), float(p2)) for p1, p2 in doc] return doc @staticmethod def save_corpus(fname, corpus, id2word=None, metadata=False): """ Save a corpus in the LDA-C format. There are actually two files saved: `fname` and `fname.vocab`, where `fname.vocab` is the vocabulary file. This function is automatically called by `BleiCorpus.serialize`; don't call it directly, call `serialize` instead. """ if id2word is None: logger.info("no word id mapping provided; initializing from corpus") id2word = utils.dict_from_corpus(corpus) num_terms = len(id2word) else: num_terms = 1 + max([-1] + id2word.keys()) logger.info("storing corpus in Blei's LDA-C format into %s" % fname) with utils.smart_open(fname, 'wb') as fout: offsets = [] for doc in corpus: doc = list(doc) offsets.append(fout.tell()) parts = ["%i:%s" % p for p in doc if abs(p[1]) > 1e-7] fout.write(utils.to_utf8("%i %s\n" % (len(doc), ' '.join(parts)))) # write out vocabulary, in a format compatible with Blei's topics.py script fname_vocab = fname + '.vocab' logger.info("saving vocabulary of %i words to %s" % (num_terms, fname_vocab)) with utils.smart_open(fname_vocab, 'wb') as fout: for featureid in xrange(num_terms): fout.write(utils.to_utf8("%s\n" % id2word.get(featureid, '---'))) return offsets def docbyoffset(self, offset): """ Return the document stored at file position `offset`. """ with utils.smart_open(self.fname) as f: f.seek(offset) return self.line2doc(f.readline()) # endclass BleiCorpus
{ "content_hash": "f1bfc5624ab8ba01f4d41f5b7d1066b2", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 85, "avg_line_length": 33.8, "alnum_prop": 0.5694674556213017, "repo_name": "ChenglongChen/topical_word_embeddings", "id": "4290951e7f25ac41d62320d1a7d8c422eedea4e8", "size": "4410", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "TWE-1/gensim/corpora/bleicorpus.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "930" }, { "name": "CSS", "bytes": "63981" }, { "name": "HTML", "bytes": "77898" }, { "name": "JavaScript", "bytes": "20520" }, { "name": "Makefile", "bytes": "9969" }, { "name": "Python", "bytes": "1914665" }, { "name": "Shell", "bytes": "4362" } ], "symlink_target": "" }
"""The LBFGS attack """ import numpy as np import tensorflow as tf from cleverhans.attacks.attack import Attack from cleverhans.compat import reduce_sum, softmax_cross_entropy_with_logits from cleverhans.model import CallableModelWrapper, Model, wrapper_warning from cleverhans import utils from cleverhans import utils_tf _logger = utils.create_logger("cleverhans.attacks.lbfgs") tf_dtype = tf.as_dtype("float32") class LBFGS(Attack): """ LBFGS is the first adversarial attack for convolutional neural networks, and is a target & iterative attack. Paper link: "https://arxiv.org/pdf/1312.6199.pdf" :param model: cleverhans.model.Model :param sess: tf.Session :param dtypestr: dtype of the data :param kwargs: passed through to super constructor """ def __init__(self, model, sess, dtypestr="float32", **kwargs): if not isinstance(model, Model): wrapper_warning() model = CallableModelWrapper(model, "probs") super(LBFGS, self).__init__(model, sess, dtypestr, **kwargs) self.feedable_kwargs = ("y_target",) self.structural_kwargs = [ "batch_size", "binary_search_steps", "max_iterations", "initial_const", "clip_min", "clip_max", ] def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: (required) A tensor with the inputs. :param kwargs: See `parse_params` """ assert ( self.sess is not None ), "Cannot use `generate` when no `sess` was provided" self.parse_params(**kwargs) if self.y_target is None: self.y_target, nb_classes = self.get_or_guess_labels(x, kwargs) self.targeted_attack = False else: _, nb_classes = self.get_or_guess_labels(x, kwargs) self.targeted_attack = True attack = LBFGS_impl( self.sess, x, self.model.get_logits(x), self.y_target, self.targeted_attack, self.binary_search_steps, self.max_iterations, self.initial_const, self.clip_min, self.clip_max, nb_classes, self.batch_size, ) def lbfgs_wrap(x_val, y_val): """ Wrapper creating TensorFlow interface for use with py_func """ return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype) wrap = tf.py_func(lbfgs_wrap, [x, self.y_target], self.tf_dtype) wrap.set_shape(x.get_shape()) return wrap def parse_params( self, y_target=None, batch_size=1, binary_search_steps=5, max_iterations=1000, initial_const=1e-2, clip_min=0, clip_max=1, ): """ :param y_target: (optional) A tensor with the one-hot target labels. :param batch_size: The number of inputs to include in a batch and process simultaneously. :param binary_search_steps: The number of times we perform binary search to find the optimal tradeoff- constant between norm of the purturbation and cross-entropy loss of classification. :param max_iterations: The maximum number of iterations. :param initial_const: The initial tradeoff-constant to use to tune the relative importance of size of the perturbation and cross-entropy loss of the classification. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ self.y_target = y_target self.batch_size = batch_size self.binary_search_steps = binary_search_steps self.max_iterations = max_iterations self.initial_const = initial_const self.clip_min = clip_min self.clip_max = clip_max class LBFGS_impl(object): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sess: a TF session. :param x: A tensor with the inputs. :param logits: A tensor with model's output logits. :param targeted_label: A tensor with the target labels. :param binary_search_steps: The number of times we perform binary search to find the optimal tradeoff- constant between norm of the purturbation and cross-entropy loss of classification. :param max_iterations: The maximum number of iterations. :param initial_const: The initial tradeoff-constant to use to tune the relative importance of size of the purturbation and cross-entropy loss of the classification. :param clip_min: Minimum input component value :param clip_max: Maximum input component value :param num_labels: The number of classes in the model's output. :param batch_size: Number of attacks to run simultaneously. """ def __init__( self, sess, x, logits, targeted_label, targeted_attack, binary_search_steps, max_iterations, initial_const, clip_min, clip_max, nb_classes, batch_size, ): self.sess = sess self.x = x self.logits = logits assert logits.op.type != "Softmax" self.targeted_label = targeted_label self.targeted_attack = targeted_attack self.binary_search_steps = binary_search_steps self.max_iterations = max_iterations self.initial_const = initial_const self.clip_min = clip_min self.clip_max = clip_max self.batch_size = batch_size self.repeat = self.binary_search_steps >= 10 self.shape = tuple([self.batch_size] + list(self.x.get_shape().as_list()[1:])) self.ori_img = tf.Variable(np.zeros(self.shape), dtype=tf_dtype, name="ori_img") self.const = tf.Variable( np.zeros(self.batch_size), dtype=tf_dtype, name="const" ) self.score = softmax_cross_entropy_with_logits( labels=self.targeted_label, logits=self.logits ) self.l2dist = reduce_sum(tf.square(self.x - self.ori_img)) # small self.const will result small adversarial perturbation # targeted attack aims at minimize loss against target label # untargeted attack aims at maximize loss against True label if self.targeted_attack: self.loss = reduce_sum(self.score * self.const) + self.l2dist else: self.loss = -reduce_sum(self.score * self.const) + self.l2dist (self.grad,) = tf.gradients(self.loss, self.x) def attack(self, x_val, targets): """ Perform the attack on the given instance for the given targets. """ def lbfgs_objective(adv_x, self, targets, oimgs, CONST): """ returns the function value and the gradient for fmin_l_bfgs_b """ loss = self.sess.run( self.loss, feed_dict={ self.x: adv_x.reshape(oimgs.shape), self.targeted_label: targets, self.ori_img: oimgs, self.const: CONST, }, ) grad = self.sess.run( self.grad, feed_dict={ self.x: adv_x.reshape(oimgs.shape), self.targeted_label: targets, self.ori_img: oimgs, self.const: CONST, }, ) return loss, grad.flatten().astype(float) def attack_success(out, target, targeted_attack): """ returns attack result """ if targeted_attack: return out == target else: return out != target # begin the main part for the attack from scipy.optimize import fmin_l_bfgs_b oimgs = np.clip(x_val, self.clip_min, self.clip_max) CONST = np.ones(self.batch_size) * self.initial_const # set the lower and upper bounds accordingly lower_bound = np.zeros(self.batch_size) upper_bound = np.ones(self.batch_size) * 1e10 # set the box constraints for the optimization function clip_min = self.clip_min * np.ones(oimgs.shape[:]) clip_max = self.clip_max * np.ones(oimgs.shape[:]) clip_bound = list(zip(clip_min.flatten(), clip_max.flatten())) # placeholders for the best l2 and instance attack found so far o_bestl2 = [1e10] * self.batch_size o_bestattack = np.copy(oimgs) for outer_step in range(self.binary_search_steps): _logger.debug( " Binary search step %s of %s", outer_step, self.binary_search_steps ) # The last iteration (if we run many steps) repeat the search once. if self.repeat and outer_step == self.binary_search_steps - 1: CONST = upper_bound # optimization function adv_x, _, __ = fmin_l_bfgs_b( lbfgs_objective, oimgs.flatten().astype(float), args=(self, targets, oimgs, CONST), bounds=clip_bound, maxiter=self.max_iterations, iprint=0, ) adv_x = adv_x.reshape(oimgs.shape) assert ( np.amax(adv_x) <= self.clip_max and np.amin(adv_x) >= self.clip_min ), "fmin_l_bfgs_b returns are invalid" # adjust the best result (i.e., the adversarial example with the # smallest perturbation in terms of L_2 norm) found so far preds = np.atleast_1d( utils_tf.model_argmax(self.sess, self.x, self.logits, adv_x) ) _logger.debug("predicted labels are %s", preds) l2s = np.zeros(self.batch_size) for i in range(self.batch_size): l2s[i] = np.sum(np.square(adv_x[i] - oimgs[i])) for e, (l2, pred, ii) in enumerate(zip(l2s, preds, adv_x)): if l2 < o_bestl2[e] and attack_success( pred, np.argmax(targets[e]), self.targeted_attack ): o_bestl2[e] = l2 o_bestattack[e] = ii # adjust the constant as needed for e in range(self.batch_size): if attack_success( preds[e], np.argmax(targets[e]), self.targeted_attack ): # success, divide const by two upper_bound[e] = min(upper_bound[e], CONST[e]) if upper_bound[e] < 1e9: CONST[e] = (lower_bound[e] + upper_bound[e]) / 2 else: # failure, either multiply by 10 if no solution found yet # or do binary search with the known upper bound lower_bound[e] = max(lower_bound[e], CONST[e]) if upper_bound[e] < 1e9: CONST[e] = (lower_bound[e] + upper_bound[e]) / 2 else: CONST[e] *= 10 _logger.debug( " Successfully generated adversarial examples " "on %s of %s instances.", sum(upper_bound < 1e9), self.batch_size, ) o_bestl2 = np.array(o_bestl2) mean = np.mean(np.sqrt(o_bestl2[o_bestl2 < 1e9])) _logger.debug(" Mean successful distortion: {:.4g}".format(mean)) # return the best solution found o_bestl2 = np.array(o_bestl2) return o_bestattack
{ "content_hash": "37cddcf37057d60393601b6907bccd9e", "timestamp": "", "source": "github", "line_count": 319, "max_line_length": 88, "avg_line_length": 38.28526645768025, "alnum_prop": 0.5550642757717187, "repo_name": "cleverhans-lab/cleverhans", "id": "3e7231915cd7b8b57292fd04fdce19328470770f", "size": "12213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cleverhans_v3.1.0/cleverhans/attacks/lbfgs.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "242" }, { "name": "HTML", "bytes": "64" }, { "name": "Makefile", "bytes": "836" }, { "name": "Python", "bytes": "1016809" }, { "name": "Shell", "bytes": "2831" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djangocms_tonicdev', '0003_auto_20160509_1538'), ] operations = [ migrations.AddField( model_name='tonicnotebookpluginmodel', name='node_version', field=models.CharField(blank=True, help_text='Provide a semver range that the node engine should satisfy, e.g. 0.12.x or > 4.0.0', max_length=32, null=True, verbose_name=b'Node version'), ), migrations.AlterField( model_name='tonicnotebookpluginmodel', name='readonly', field=models.BooleanField(default=False, help_text='Create a notebook that can not be edited or run', verbose_name=b'Readonly'), ), ]
{ "content_hash": "f0ebb92d101d4f5c21158cbfaa7743c1", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 199, "avg_line_length": 35.78260869565217, "alnum_prop": 0.6415552855407047, "repo_name": "TigerND/djangocms-tonicdev", "id": "69b432dfb8ad4de14a57f5e4ddf66414f4484d98", "size": "895", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "djangocms_tonicdev/migrations/0004_auto_20160509_1637.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "709" }, { "name": "JavaScript", "bytes": "588" }, { "name": "Python", "bytes": "9715" } ], "symlink_target": "" }
import shutil import sys import os import path binDir = path.path("C:/Users/haggi/coding/lux/windows/Projects/luxrender/x64") binDirA = path.path("C:/Users/haggi/coding/lux/windows/Projects/luxrays/x64") binDest = path.path("C:/Users/haggi/coding/OpenMaya/src/mayaToLux/devkit/luxsdk/bin") libDest = path.path("C:/Users/haggi/coding/OpenMaya/src/mayaToLux/devkit/luxsdk/lib") shutil.copy(binDir / "Debug/lux.dll", binDest / "Debug/lux.dll") shutil.copy(binDir / "Release/lux.dll", binDest / "Release/lux.dll") shutil.copy(binDir / "Release NoOpenCL/lux.dll", binDest / "Release NoOpenCL/lux.dll") for d in [binDir, binDirA]: for l in ["liblux.lib", "lux.lib", "libsgl.lib", "lux.pdb", "luxrays.lib"]: try: shutil.copy(d / "Debug/" + l, libDest / "Debug/" + l) shutil.copy(d / "Release/" + l, libDest / "Release/" + l) shutil.copy(d / "Release NoOpenCL/" + l, binDest / "Release NoOpenCL/" + l) except: pass
{ "content_hash": "8bfac4733f7f061d0eb217b1f1595bbf", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 87, "avg_line_length": 37.76923076923077, "alnum_prop": 0.6568228105906314, "repo_name": "haggi/OpenMaya", "id": "1c2083ec1de6d900357da8750a6a404a66a58499", "size": "982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mayaToLux/mtlu_devmodule/scripts/updateSDK.py", "mode": "33188", "license": "mit", "language": [ { "name": "AMPL", "bytes": "5333" }, { "name": "Batchfile", "bytes": "587" }, { "name": "C", "bytes": "246300" }, { "name": "C++", "bytes": "4178594" }, { "name": "Mathematica", "bytes": "12660820" }, { "name": "Objective-C", "bytes": "316" }, { "name": "Python", "bytes": "1583249" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from abc import ABCMeta from collections import MutableMapping import sys try: from collections import UserDict except ImportError: from UserDict import UserDict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict try: from thread import get_ident except ImportError: try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): 'Decorator to make a repr function return fillvalue for a recursive call' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) return wrapper return decorating_function class ChainMap(MutableMapping): ''' A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. ''' def __init__(self, *maps): '''Initialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. ''' self.maps = list(maps) or [{}] # always at least one map def __missing__(self, key): raise KeyError(key) def __getitem__(self, key): for mapping in self.maps: try: return mapping[key] # can't use 'key in mapping' with defaultdict except KeyError: pass return self.__missing__(key) # support subclasses that define __missing__ def get(self, key, default=None): return self[key] if key in self else default def __len__(self): return len(set().union(*self.maps)) # reuses stored hash values if possible def __iter__(self): return iter(set().union(*self.maps)) def __contains__(self, key): return any(key in m for m in self.maps) @recursive_repr() def __repr__(self): return '{0.__class__.__name__}({1})'.format( self, ', '.join(map(repr, self.maps))) @classmethod def fromkeys(cls, iterable, *args): 'Create a ChainMap with a single dict created from the iterable.' return cls(dict.fromkeys(iterable, *args)) def copy(self): 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' return self.__class__(self.maps[0].copy(), *self.maps[1:]) __copy__ = copy def new_child(self): # like Django's Context.push() 'New ChainMap with a new dict followed by all previous maps.' return self.__class__({}, *self.maps) @property def parents(self): # like Django's Context.pop() 'New ChainMap from maps[1:].' return self.__class__(*self.maps[1:]) def __setitem__(self, key, value): self.maps[0][key] = value def __delitem__(self, key): try: del self.maps[0][key] except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.') def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def clear(self): 'Clear maps[0], leaving maps[1:] intact.' self.maps[0].clear() class MappingProxyType(UserDict): def __init__(self, data): UserDict.__init__(self) self.data = data def get_cache_token(): return ABCMeta._abc_invalidation_counter class Support(object): def dummy(self): pass def cpython_only(self, func): if 'PyPy' in sys.version: return self.dummy return func
{ "content_hash": "824fe32b4e2e9d868f8f602da9a6162a", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 97, "avg_line_length": 31.023952095808383, "alnum_prop": 0.6014282956958116, "repo_name": "AtomLinter/linter-pylama", "id": "8fcdce40464de84002e81f17e47917ce1cc414ef", "size": "5228", "binary": false, "copies": "46", "ref": "refs/heads/master", "path": "bin/deps/singledispatch_helpers.py", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "22985" }, { "name": "Python", "bytes": "2871797" } ], "symlink_target": "" }
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import sys from abc import abstractmethod from contextlib import contextmanager from six.moves import range from twitter.common.collections import OrderedSet from pants.backend.jvm import argfile from pants.backend.jvm.subsystems.junit import JUnit from pants.backend.jvm.subsystems.jvm_platform import JvmPlatform from pants.backend.jvm.targets.junit_tests import JUnitTests from pants.backend.jvm.targets.jvm_target import JvmTarget from pants.backend.jvm.tasks.classpath_util import ClasspathUtil from pants.backend.jvm.tasks.coverage.base import Coverage from pants.backend.jvm.tasks.coverage.cobertura import Cobertura, CoberturaTaskSettings from pants.backend.jvm.tasks.jvm_task import JvmTask from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin from pants.backend.jvm.tasks.reports.junit_html_report import JUnitHtmlReport from pants.base.build_environment import get_buildroot from pants.base.exceptions import TargetDefinitionException, TaskError, TestFailedTaskError from pants.base.workunit import WorkUnitLabel from pants.build_graph.target import Target from pants.build_graph.target_scopes import Scopes from pants.java.distribution.distribution import DistributionLocator from pants.java.executor import SubprocessExecutor from pants.java.junit.junit_xml_parser import Test, TestRegistry, parse_failed_targets from pants.process.lock import OwnerPrintingInterProcessFileLock from pants.task.testrunner_task_mixin import TestRunnerTaskMixin from pants.util import desktop from pants.util.argutil import ensure_arg, remove_arg from pants.util.contextutil import environment_as from pants.util.dirutil import safe_mkdir, safe_rmtree from pants.util.memo import memoized_method from pants.util.meta import AbstractClass from pants.util.strutil import pluralize class _TestSpecification(AbstractClass): """Models the string format used to specify which tests to run.""" @classmethod def parse(cls, buildroot, test_spec): """Parses a test specification string into an object that can yield corresponding tests. Tests can be specified in one of four forms: * [classname] * [filename] * [classname]#[methodname] * [filename]#[methodname] The first two forms target one or more individual tests contained within a class or file whereas the final two forms specify an individual test method to execute. :param string buildroot: The path of the current build root directory. :param string test_spec: A test specification. :returns: A test specification object. :rtype: :class:`_TestSpecification` """ components = test_spec.split('#', 2) classname_or_sourcefile = components[0] methodname = components[1] if len(components) == 2 else None if os.path.exists(classname_or_sourcefile): sourcefile = os.path.relpath(classname_or_sourcefile, buildroot) return _SourcefileSpec(sourcefile=sourcefile, methodname=methodname) else: return _ClassnameSpec(classname=classname_or_sourcefile, methodname=methodname) @abstractmethod def iter_possible_tests(self, context): """Return an iterator over the possible tests this test specification indicates. NB: At least one test yielded by the returned iterator will correspond to an available test, but other yielded tests may not exist. :param context: The pants execution context. :type context: :class:`pants.goal.context.Context` :returns: An iterator over possible tests. :rtype: iter of :class:`pants.java.junit.junit_xml_parser.Test` """ class _SourcefileSpec(_TestSpecification): """Models a test specification in [sourcefile]#[methodname] format.""" def __init__(self, sourcefile, methodname): self._sourcefile = sourcefile self._methodname = methodname def iter_possible_tests(self, context): for classname in self._classnames_from_source_file(context): # Tack the methodname onto all classes in the source file, as we # can't know which method the user intended. yield Test(classname=classname, methodname=self._methodname) def _classnames_from_source_file(self, context): source_products = context.products.get_data('classes_by_source').get(self._sourcefile) if not source_products: # It's valid - if questionable - to have a source file with no classes when, for # example, the source file has all its code commented out. context.log.warn('Source file {0} generated no classes'.format(self._sourcefile)) else: for _, classes in source_products.rel_paths(): for cls in classes: yield ClasspathUtil.classname_for_rel_classfile(cls) class _ClassnameSpec(_TestSpecification): """Models a test specification in [classname]#[methodnme] format.""" def __init__(self, classname, methodname): self._classname = classname self._methodname = methodname def iter_possible_tests(self, context): yield Test(classname=self._classname, methodname=self._methodname) class JUnitRun(TestRunnerTaskMixin, JvmToolTaskMixin, JvmTask): """ :API: public """ @classmethod def register_options(cls, register): super(JUnitRun, cls).register_options(register) register('--batch-size', advanced=True, type=int, default=sys.maxint, help='Run at most this many tests in a single test process.') register('--test', type=list, help='Force running of just these tests. Tests can be specified using any of: ' '[classname], [classname]#[methodname], [filename] or [filename]#[methodname]') register('--per-test-timer', type=bool, help='Show progress and timer for each test.') register('--default-concurrency', advanced=True, choices=JUnitTests.VALID_CONCURRENCY_OPTS, default=JUnitTests.CONCURRENCY_SERIAL, help='Set the default concurrency mode for running tests not annotated with' ' @TestParallel or @TestSerial.') register('--parallel-threads', advanced=True, type=int, default=0, help='Number of threads to run tests in parallel. 0 for autoset.') register('--test-shard', advanced=True, help='Subset of tests to run, in the form M/N, 0 <= M < N. ' 'For example, 1/3 means run tests number 2, 5, 8, 11, ...') register('--output-mode', choices=['ALL', 'FAILURE_ONLY', 'NONE'], default='NONE', help='Specify what part of output should be passed to stdout. ' 'In case of FAILURE_ONLY and parallel tests execution ' 'output can be partial or even wrong. ' 'All tests output also redirected to files in .pants.d/test/junit.') register('--cwd', advanced=True, help='Set the working directory. If no argument is passed, use the build root. ' 'If cwd is set on a target, it will supersede this argument.') register('--strict-jvm-version', type=bool, advanced=True, help='If true, will strictly require running junits with the same version of java as ' 'the platform -target level. Otherwise, the platform -target level will be ' 'treated as the minimum jvm to run.') register('--failure-summary', type=bool, default=True, help='If true, includes a summary of which test-cases failed at the end of a failed ' 'junit run.') register('--allow-empty-sources', type=bool, advanced=True, help='Allows a junit_tests() target to be defined with no sources. Otherwise,' 'such a target will raise an error during the test run.') register('--use-experimental-runner', type=bool, advanced=True, help='Use experimental junit-runner logic for more options for parallelism.') register('--html-report', type=bool, help='If true, generate an html summary report of tests that were run.') register('--open', type=bool, help='Attempt to open the html summary report in a browser (implies --html-report)') # TODO: Yuck, but will improve once coverage steps are in their own tasks. for c in [Coverage, Cobertura]: c.register_options(register, cls.register_jvm_tool) @classmethod def subsystem_dependencies(cls): return super(JUnitRun, cls).subsystem_dependencies() + (DistributionLocator, JUnit) @classmethod def request_classes_by_source(cls, test_specs): """Returns true if the given test specs require the `classes_by_source` product to satisfy.""" buildroot = get_buildroot() for test_spec in test_specs: if isinstance(_TestSpecification.parse(buildroot, test_spec), _SourcefileSpec): return True return False @classmethod def prepare(cls, options, round_manager): super(JUnitRun, cls).prepare(options, round_manager) # Compilation and resource preparation must have completed. round_manager.require_data('runtime_classpath') # If the given test specs require the classes_by_source product, request it. if cls.request_classes_by_source(options.test or ()): round_manager.require_data('classes_by_source') def __init__(self, *args, **kwargs): super(JUnitRun, self).__init__(*args, **kwargs) options = self.get_options() self._tests_to_run = options.test self._batch_size = options.batch_size self._fail_fast = options.fail_fast self._working_dir = options.cwd or get_buildroot() self._strict_jvm_version = options.strict_jvm_version self._failure_summary = options.failure_summary self._open = options.open self._html_report = self._open or options.html_report @memoized_method def _args(self, output_dir): args = self.args[:] options = self.get_options() if options.output_mode == 'ALL': args.append('-output-mode=ALL') elif options.output_mode == 'FAILURE_ONLY': args.append('-output-mode=FAILURE_ONLY') else: args.append('-output-mode=NONE') if self._fail_fast: args.append('-fail-fast') args.append('-outdir') args.append(output_dir) if options.per_test_timer: args.append('-per-test-timer') if options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES_AND_METHODS: if not options.use_experimental_runner: self.context.log.warn('--default-concurrency=PARALLEL_CLASSES_AND_METHODS is ' 'experimental, use --use-experimental-runner.') args.append('-default-concurrency') args.append('PARALLEL_CLASSES_AND_METHODS') elif options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_METHODS: if not options.use_experimental_runner: self.context.log.warn('--default-concurrency=PARALLEL_METHODS is experimental, use ' '--use-experimental-runner.') if options.test_shard: # NB(zundel): The experimental junit runner doesn't support test sharding natively. The # legacy junit runner allows both methods and classes to run in parallel with this option. self.context.log.warn('--default-concurrency=PARALLEL_METHODS with test sharding will ' 'run classes in parallel too.') args.append('-default-concurrency') args.append('PARALLEL_METHODS') elif options.default_concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES: args.append('-default-concurrency') args.append('PARALLEL_CLASSES') elif options.default_concurrency == JUnitTests.CONCURRENCY_SERIAL: args.append('-default-concurrency') args.append('SERIAL') args.append('-parallel-threads') args.append(str(options.parallel_threads)) if options.test_shard: args.append('-test-shard') args.append(options.test_shard) if options.use_experimental_runner: self.context.log.info('Using experimental junit-runner logic.') args.append('-use-experimental-runner') return args def classpath(self, targets, classpath_product=None, **kwargs): return super(JUnitRun, self).classpath(targets, classpath_product=classpath_product, include_scopes=Scopes.JVM_TEST_SCOPES, **kwargs) def preferred_jvm_distribution_for_targets(self, targets): return JvmPlatform.preferred_jvm_distribution([target.platform for target in targets if isinstance(target, JvmTarget)], self._strict_jvm_version) def _spawn(self, distribution, executor=None, *args, **kwargs): """Returns a processhandler to a process executing java. :param Executor executor: the java subprocess executor to use. If not specified, construct using the distribution. :param Distribution distribution: The JDK or JRE installed. :rtype: ProcessHandler """ actual_executor = executor or SubprocessExecutor(distribution) return distribution.execute_java_async(*args, executor=actual_executor, **kwargs) def execute_java_for_targets(self, targets, *args, **kwargs): """Execute java for targets using the test mixin spawn and wait. Activates timeouts and other common functionality shared among tests. """ distribution = self.preferred_jvm_distribution_for_targets(targets) actual_executor = kwargs.get('executor') or SubprocessExecutor(distribution) return self._spawn_and_wait(*args, executor=actual_executor, distribution=distribution, **kwargs) def execute_java_for_coverage(self, targets, executor=None, *args, **kwargs): """Execute java for targets directly and don't use the test mixin. This execution won't be wrapped with timeouts and other testmixin code common across test targets. Used for coverage instrumentation. """ distribution = self.preferred_jvm_distribution_for_targets(targets) actual_executor = executor or SubprocessExecutor(distribution) return distribution.execute_java(*args, executor=actual_executor, **kwargs) def _collect_test_targets(self, targets): """Return a test registry mapping the tests found in the given targets. If `self._tests_to_run` is set, return a registry of explicitly specified tests instead. :returns: A registry of tests to run. :rtype: :class:`pants.java.junit.junit_xml_parser.Test.TestRegistry` """ test_registry = TestRegistry(tuple(self._calculate_tests_from_targets(targets))) if targets and self._tests_to_run: # If there are some junit_test targets in the graph, find ones that match the requested # test(s). possible_test_to_target = {} unknown_tests = [] for possible_test in self._get_possible_tests_to_run(): target = test_registry.get_owning_target(possible_test) if target is None: unknown_tests.append(possible_test) else: possible_test_to_target[possible_test] = target if len(unknown_tests) > 0: raise TaskError("No target found for test specifier(s):\n\n '{}'\n\nPlease change " "specifier or bring in the proper target(s)." .format("'\n '".join(t.render_test_spec() for t in unknown_tests))) return TestRegistry(possible_test_to_target) else: return test_registry def _run_tests(self, test_registry, output_dir, coverage=None): if coverage: extra_jvm_options = coverage.extra_jvm_options classpath_prepend = coverage.classpath_prepend classpath_append = coverage.classpath_append else: extra_jvm_options = [] classpath_prepend = () classpath_append = () tests_by_properties = test_registry.index( lambda tgt: tgt.cwd if tgt.cwd is not None else self._working_dir, lambda tgt: tgt.test_platform, lambda tgt: tgt.payload.extra_jvm_options, lambda tgt: tgt.payload.extra_env_vars, lambda tgt: tgt.concurrency, lambda tgt: tgt.threads) # the below will be None if not set, and we'll default back to runtime_classpath classpath_product = self.context.products.get_data('instrument_classpath') result = 0 for properties, tests in tests_by_properties.items(): (workdir, platform, target_jvm_options, target_env_vars, concurrency, threads) = properties for batch in self._partition(tests): # Batches of test classes will likely exist within the same targets: dedupe them. relevant_targets = {test_registry.get_owning_target(t) for t in batch} complete_classpath = OrderedSet() complete_classpath.update(classpath_prepend) complete_classpath.update(JUnit.global_instance().runner_classpath(self.context)) complete_classpath.update(self.classpath(relevant_targets, classpath_product=classpath_product)) complete_classpath.update(classpath_append) distribution = JvmPlatform.preferred_jvm_distribution([platform], self._strict_jvm_version) # Override cmdline args with values from junit_test() target that specify concurrency: args = self._args(output_dir) + [u'-xmlreport'] if concurrency is not None: args = remove_arg(args, '-default-parallel') if concurrency == JUnitTests.CONCURRENCY_SERIAL: args = ensure_arg(args, '-default-concurrency', param='SERIAL') elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES: args = ensure_arg(args, '-default-concurrency', param='PARALLEL_CLASSES') elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_METHODS: args = ensure_arg(args, '-default-concurrency', param='PARALLEL_METHODS') elif concurrency == JUnitTests.CONCURRENCY_PARALLEL_CLASSES_AND_METHODS: args = ensure_arg(args, '-default-concurrency', param='PARALLEL_CLASSES_AND_METHODS') if threads is not None: args = remove_arg(args, '-parallel-threads', has_param=True) args += ['-parallel-threads', str(threads)] batch_test_specs = [test.render_test_spec() for test in batch] with argfile.safe_args(batch_test_specs, self.get_options()) as batch_tests: self.context.log.debug('CWD = {}'.format(workdir)) self.context.log.debug('platform = {}'.format(platform)) with environment_as(**dict(target_env_vars)): result += abs(self._spawn_and_wait( executor=SubprocessExecutor(distribution), distribution=distribution, classpath=complete_classpath, main=JUnit.RUNNER_MAIN, jvm_options=self.jvm_options + extra_jvm_options + list(target_jvm_options), args=args + batch_tests, workunit_factory=self.context.new_workunit, workunit_name='run', workunit_labels=[WorkUnitLabel.TEST], cwd=workdir, synthetic_jar_dir=output_dir, create_synthetic_jar=self.synthetic_classpath, )) if result != 0 and self._fail_fast: break if result != 0: def error_handler(parse_error): # Just log and move on since the result is only used to characterize failures, and raising # an error here would just distract from the underlying test failures. self.context.log.error('Error parsing test result file {path}: {cause}' .format(path=parse_error.junit_xml_path, cause=parse_error.cause)) target_to_failed_test = parse_failed_targets(test_registry, output_dir, error_handler) failed_targets = sorted(target_to_failed_test, key=lambda t: t.address.spec) error_message_lines = [] if self._failure_summary: for target in failed_targets: error_message_lines.append('\n{indent}{address}'.format(indent=' ' * 4, address=target.address.spec)) for test in sorted(target_to_failed_test[target]): error_message_lines.append('{indent}{classname}#{methodname}' .format(indent=' ' * 8, classname=test.classname, methodname=test.methodname)) error_message_lines.append( '\njava {main} ... exited non-zero ({code}); {failed} failed {targets}.' .format(main=JUnit.RUNNER_MAIN, code=result, failed=len(failed_targets), targets=pluralize(len(failed_targets), 'target')) ) raise TestFailedTaskError('\n'.join(error_message_lines), failed_targets=list(failed_targets)) def _partition(self, tests): stride = min(self._batch_size, len(tests)) for i in range(0, len(tests), stride): yield tests[i:i + stride] def _get_possible_tests_to_run(self): buildroot = get_buildroot() for test_spec in self._tests_to_run: for test in _TestSpecification.parse(buildroot, test_spec).iter_possible_tests(self.context): yield test def _calculate_tests_from_targets(self, targets): """ :param list targets: list of targets to calculate test classes for. generates tuples (Test, Target). """ classpath_products = self.context.products.get_data('runtime_classpath') for target in targets: contents = ClasspathUtil.classpath_contents((target,), classpath_products, confs=self.confs) for f in contents: classname = ClasspathUtil.classname_for_rel_classfile(f) if classname: yield Test(classname=classname), target def _test_target_filter(self): def target_filter(target): return isinstance(target, JUnitTests) return target_filter def _validate_target(self, target): # TODO: move this check to an optional phase in goal_runner, so # that missing sources can be detected early. if not target.payload.sources.source_paths and not self.get_options().allow_empty_sources: msg = 'JUnitTests target must include a non-empty set of sources.' raise TargetDefinitionException(target, msg) def _execute(self, all_targets): # NB: We only run tests within junit_tests targets, but if coverage options are # specified, we want to instrument and report on all the original targets, not # just the test targets. test_registry = self._collect_test_targets(self._get_test_targets()) if test_registry.empty: return with self._isolation(all_targets) as (output_dir, do_report, coverage): try: self._run_tests(test_registry, output_dir, coverage) do_report(exc=None) except TaskError as e: do_report(exc=e) raise @contextmanager def _isolation(self, all_targets): run_dir = '_runs' output_dir = os.path.join(self.workdir, run_dir, Target.identify(all_targets)) safe_mkdir(output_dir, clean=True) coverage = None options = self.get_options() if options.coverage or options.is_flagged('coverage_open'): coverage_processor = options.coverage_processor if coverage_processor == 'cobertura': settings = CoberturaTaskSettings.from_task(self, workdir=output_dir) coverage = Cobertura(settings) else: raise TaskError('unknown coverage processor {0}'.format(coverage_processor)) self.context.release_lock() if coverage: coverage.instrument(targets=all_targets, compute_junit_classpath=lambda: self.classpath(all_targets), execute_java_for_targets=self.execute_java_for_coverage) def do_report(exc=None): if coverage: coverage.report(all_targets, self.execute_java_for_coverage, tests_failed_exception=exc) if self._html_report: html_file_path = JUnitHtmlReport().report(output_dir, os.path.join(output_dir, 'reports')) if self._open: desktop.ui_open(html_file_path) try: yield output_dir, do_report, coverage finally: # NB: Deposit of the "current" test output in the root workdir (.pants.d/test/junit) is a # defacto public API and so we implement that behavior here to maintain backwards # compatibility for non-pants report file consumers. # TODO(John Sirois): Deprecate this ~API and provide a stable directory solution for test # output: https://github.com/pantsbuild/pants/issues/3879 lock_file = '.file_lock' with OwnerPrintingInterProcessFileLock(os.path.join(self.workdir, lock_file)): # Kill everything except the isolated runs/ dir. for name in os.listdir(self.workdir): path = os.path.join(self.workdir, name) if name not in (run_dir, lock_file): if os.path.isdir(path): safe_rmtree(path) else: os.unlink(path) # Link all the isolated run/ dir contents back up to the stable workdir for name in os.listdir(output_dir): path = os.path.join(output_dir, name) os.symlink(path, os.path.join(self.workdir, name))
{ "content_hash": "9e40050df874dc835cc7710ed7b5a383", "timestamp": "", "source": "github", "line_count": 556, "max_line_length": 100, "avg_line_length": 45.87589928057554, "alnum_prop": 0.6700121535264829, "repo_name": "ericzundel/pants", "id": "cddb8d916edfeeeeacbe8f8b656dc028fed4cf0f", "size": "25654", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/python/pants/backend/jvm/tasks/junit_run.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "781" }, { "name": "CSS", "bytes": "9444" }, { "name": "Cucumber", "bytes": "919" }, { "name": "GAP", "bytes": "2459" }, { "name": "Go", "bytes": "1746" }, { "name": "HTML", "bytes": "79866" }, { "name": "Java", "bytes": "451946" }, { "name": "JavaScript", "bytes": "29992" }, { "name": "Protocol Buffer", "bytes": "3783" }, { "name": "Python", "bytes": "5295128" }, { "name": "Rust", "bytes": "64940" }, { "name": "Scala", "bytes": "80568" }, { "name": "Shell", "bytes": "59536" }, { "name": "Thrift", "bytes": "2046" } ], "symlink_target": "" }
import re from typing import Dict, Iterable, Iterator, Mapping from pants.option.config import Config from pants.option.option_tracker import OptionTracker from pants.option.parser import Parser from pants.option.scope import GLOBAL_SCOPE, ScopeInfo class InvalidScopeError(Exception): pass _empty_scope_component_re = re.compile(r"\.\.") def _validate_full_scope(scope: str) -> None: if _empty_scope_component_re.search(scope): raise InvalidScopeError(f"full scope '{scope}' has at least one empty component") def enclosing_scope(scope: str) -> str: """Utility function to return the scope immediately enclosing a given scope.""" _validate_full_scope(scope) return scope.rpartition(".")[0] def all_enclosing_scopes(scope: str, *, allow_global: bool = True) -> Iterator[str]: """Utility function to return all scopes up to the global scope enclosing a given scope.""" _validate_full_scope(scope) def scope_within_range(tentative_scope: str) -> bool: if not allow_global and tentative_scope == GLOBAL_SCOPE: return False return True while scope_within_range(scope): yield scope if scope == GLOBAL_SCOPE: return scope = enclosing_scope(scope) class ParserHierarchy: """A hierarchy of scoped Parser instances. A scope is a dotted string: E.g., compile.java. In this example the compile.java scope is enclosed in the compile scope, which is enclosed in the global scope (represented by an empty string.) """ def __init__( self, env: Mapping[str, str], config: Config, scope_infos: Iterable[ScopeInfo], option_tracker: OptionTracker, ) -> None: # Sorting ensures that ancestors precede descendants. scope_infos = sorted(set(list(scope_infos)), key=lambda si: si.scope) self._parser_by_scope: Dict[str, Parser] = {} for scope_info in scope_infos: scope = scope_info.scope parent_parser = ( None if scope == GLOBAL_SCOPE else self._parser_by_scope[enclosing_scope(scope)] ) self._parser_by_scope[scope] = Parser( env, config, scope_info, parent_parser, option_tracker=option_tracker ) def get_parser_by_scope(self, scope: str) -> Parser: try: return self._parser_by_scope[scope] except KeyError: raise Config.ConfigValidationError(f"No such options scope: {scope}") def walk(self, callback): """Invoke callback on each parser, in pre-order depth-first order.""" self._parser_by_scope[GLOBAL_SCOPE].walk(callback)
{ "content_hash": "269d64d8d19dbd48e09f73ac707fb5a8", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 97, "avg_line_length": 33.625, "alnum_prop": 0.6520446096654275, "repo_name": "tdyas/pants", "id": "892311eef714f44b6a6f361de919054b0e06a0e8", "size": "2822", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/python/pants/option/parser_hierarchy.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "655" }, { "name": "C++", "bytes": "2010" }, { "name": "CSS", "bytes": "9444" }, { "name": "Dockerfile", "bytes": "5596" }, { "name": "GAP", "bytes": "1283" }, { "name": "Gherkin", "bytes": "919" }, { "name": "Go", "bytes": "2765" }, { "name": "HTML", "bytes": "44381" }, { "name": "Java", "bytes": "518180" }, { "name": "JavaScript", "bytes": "22906" }, { "name": "Python", "bytes": "7955590" }, { "name": "Rust", "bytes": "1031208" }, { "name": "Scala", "bytes": "106520" }, { "name": "Shell", "bytes": "109904" }, { "name": "Starlark", "bytes": "502255" }, { "name": "Thrift", "bytes": "2953" } ], "symlink_target": "" }
# Software License Agreement (BSD License) # # # # Copyright 2014 University of Utah # # Scientific Computing and Imaging Institute # # 72 S Central Campus Drive, Room 3750 # # Salt Lake City, UT 84112 # # # # THE BSD LICENSE # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions # # are met: # # # # 1. Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # # notice, this list of conditions and the following disclaimer in the # # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # # contributors may be used to endorse or promote products derived # # from this software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################## import sys import numpy as np import time import os import itertools import collections #################################################### # This is tenuous at best, if the the directory structure of RAVEN changes, this # will need to be updated, make sure you add this to the beginning of the search # path, so that you try to grab the locally built one before relying on an # installed version myPath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0,myPath) try: import amsc except ImportError as e: makeFilePath = os.path.realpath(os.path.join(myPath,'..','..','amsc.mk')) sys.stderr.write(str(e)+"\n") sys.stderr.write('It appears you do not have the AMSC library. Try ' + 'running the following command:' + os.linesep + '\tmake -f ' + makeFilePath + os.linesep) sys.exit(1) ################################################################################ import scipy.optimize import scipy.stats import scipy ##Let's see what statsmodels weighted linear regression does #import statsmodels.api as sm def WeightedLinearModel(X,y,w): """ A wrapper for playing with the linear regression used per segment. The benefit of having this out here is that we do not have to adjust it in several places in the AMSC class, since it can build linear models for an arbitrary subset of dimensions, as well. @ In, X, a matrix of input samples @ In, y, a vector of output responses corresponding to the input samples @ In, w, a vector of weights corresponding to the input samples @ Out, a tuple consisting of the fits y-intercept and the the list of linear coefficients. """ ## Using scipy directly to do weighted linear regression on non-centered data Xw = np.ones((X.shape[0],X.shape[1]+1)) Xw[:,1:] = X Xw = Xw * np.sqrt(w)[:, None] yw = y * np.sqrt(w) results = scipy.linalg.lstsq(Xw, yw)[0] yIntercept = results[0] betaHat = results[1:] return (yIntercept,betaHat) class AMSC_Object(object): """ A wrapper class for the C++ approximate Morse-Smale complex Object that also communicates with the UI via Qt's signal interface """ def __init__(self, X, Y, w=None, names=None, graph='beta skeleton', gradient='steepest', knn=-1, beta=1.0, normalization=None, persistence='difference', edges=None, debug=False): """ Initialization method that takes at minimum a set of input points and corresponding output responses. @ In, X, an m-by-n array of values specifying m n-dimensional samples @ In, Y, a m vector of values specifying the output responses corresponding to the m samples specified by X @ In, w, an optional m vector of values specifying the weights associated to each of the m samples used. Default of None means all points will be equally weighted @ In, names, an optional list of strings that specify the names to associate to the n input dimensions and 1 output dimension. Default of None means input variables will be x0,x1...,x(n-1) and the output will be y @ In, graph, an optional string specifying the type of neighborhood graph to use. Default is 'beta skeleton,' but other valid types are: 'delaunay,' 'relaxed beta skeleton,' 'none', or 'approximate knn' @ In, gradient, an optional string specifying the type of gradient estimator to use. Currently the only available option is 'steepest' @ In, knn, an optional integer value specifying the maximum number of k-nearest neighbors used to begin a neighborhood search. In the case of graph='[relaxed] beta skeleton', we will begin with the specified approximate knn graph and prune edges that do not satisfy the empty region criteria. @ In, beta, an optional floating point value between 0 and 2. This value is only used when graph='[relaxed] beta skeleton' and specifies the radius for the empty region graph computation (1=Gabriel graph, 2=Relative neighbor graph) @ In, normalization, an optional string specifying whether the inputs/output should be scaled before computing. Currently, two modes are supported 'zscore' and 'feature'. 'zscore' will ensure the data has a mean of zero and a standard deviation of 1 by subtracting the mean and dividing by the variance. 'feature' scales the data into the unit hypercube. @ In, persistence, an optional string specifying how we will compute the persistence hierarchy. Currently, three modes are supported 'difference', 'probability' and 'count'. 'difference' will take the function value difference of the extrema and its closest function valued neighboring saddle, 'probability' will augment this value by multiplying the probability of the extremum and its saddle, and count will make the larger point counts more persistent. @ In, edges, an optional list of custom edges to use as a starting point for pruning, or in place of a computed graph. @ In, debug, an optional boolean flag for whether debugging output should be enabled. """ super(AMSC_Object,self).__init__() if X is not None and len(X) > 1: self.Reinitialize(X, Y, w, names, graph, gradient, knn, beta, normalization, persistence, edges, debug) else: # Set some reasonable defaults self.SetEmptySettings() def SetEmptySettings(self): """ Empties all internal storage containers """ self.partitions = {} self.persistence = 0. self.segmentFits = {} self.extremumFits = {} self.segmentFitnesses = {} self.extremumFitnesses = {} self.mergeSequence = {} self.selectedExtrema = [] self.selectedSegments = [] self.filters = {} self.minIdxs = [] self.maxIdxs = [] self.X = [] self.Y = [] self.w = [] self.normalization = None self.names = [] self.Xnorm = [] self.Ynorm = [] self.__amsc = None def Reinitialize(self, X, Y, w=None, names=None, graph='beta skeleton', gradient='steepest', knn=-1, beta=1.0, normalization=None, persistence='difference', edges=None, debug=False): """ Allows the caller to basically start over with a new dataset. @ In, X, an m-by-n array of values specifying m n-dimensional samples @ In, Y, a m vector of values specifying the output responses corresponding to the m samples specified by X @ In, w, an optional m vector of values specifying the weights associated to each of the m samples used. Default of None means all points will be equally weighted @ In, names, an optional list of strings that specify the names to associate to the n input dimensions and 1 output dimension. Default of None means input variables will be x0,x1...,x(n-1) and the output will be y @ In, graph, an optional string specifying the type of neighborhood graph to use. Default is 'beta skeleton,' but other valid types are: 'delaunay,' 'relaxed beta skeleton,' or 'approximate knn' @ In, gradient, an optional string specifying the type of gradient estimator to use. Currently the only available option is 'steepest' @ In, knn, an optional integer value specifying the maximum number of k-nearest neighbors used to begin a neighborhood search. In the case of graph='[relaxed] beta skeleton', we will begin with the specified approximate knn graph and prune edges that do not satisfy the empty region criteria. @ In, beta, an optional floating point value between 0 and 2. This value is only used when graph='[relaxed] beta skeleton' and specifies the radius for the empty region graph computation (1=Gabriel graph, 2=Relative neighbor graph) @ In, normalization, an optional string specifying whether the inputs/output should be scaled before computing. Currently, two modes are supported 'zscore' and 'feature'. 'zscore' will ensure the data has a mean of zero and a standard deviation of 1 by subtracting the mean and dividing by the variance. 'feature' scales the data into the unit hypercube. @ In, persistence, an optional string specifying how we will compute the persistence hierarchy. Currently, three modes are supported 'difference', 'probability' and 'count'. 'difference' will take the function value difference of the extrema and its closest function valued neighboring saddle, 'probability' will augment this value by multiplying the probability of the extremum and its saddle, and count will make the larger point counts more persistent. """ import sklearn.neighbors import sklearn.linear_model import sklearn.preprocessing self.partitions = {} self.persistence = 0. self.segmentFits = {} self.extremumFits = {} self.segmentFitnesses = {} self.extremumFitnesses = {} self.mergeSequence = {} self.selectedExtrema = [] self.selectedSegments = [] self.filters = {} self.minIdxs = [] self.maxIdxs = [] self.partitionColors = {} self.colorIdx = 0 self.X = X self.Y = Y if w is not None: self.w = np.array(w) else: self.w = np.ones(len(Y))*1.0/float(len(Y)) self.names = names self.normalization = normalization self.graph = graph self.gradient = gradient self.knn = knn self.beta = beta if self.X is None or self.Y is None: print('There is no data to process, what would the Maker have me do?') self.SetEmptySettings() return if self.names is None: self.names = [] for d in range(self.GetDimensionality()): self.names.append('x%d' % d) self.names.append('y') if normalization == 'feature': # This doesn't work with one-dimensional arrays on older versions of # sklearn min_max_scaler = sklearn.preprocessing.MinMaxScaler() self.Xnorm = min_max_scaler.fit_transform(np.atleast_2d(self.X)) self.Ynorm = min_max_scaler.fit_transform(np.atleast_2d(self.Y)) elif normalization == 'zscore': self.Xnorm = sklearn.preprocessing.scale(self.X, axis=0, with_mean=True, with_std=True, copy=True) self.Ynorm = sklearn.preprocessing.scale(self.Y, axis=0, with_mean=True, with_std=True, copy=True) else: self.Xnorm = np.array(self.X) self.Ynorm = np.array(self.Y) if knn <= 0: knn = len(self.Xnorm)-1 if debug: sys.stderr.write('Graph Preparation: ') start = time.clock() if knn <= 0: knn = len(self.Y)-1 if edges is None: knnAlgorithm = sklearn.neighbors.NearestNeighbors(n_neighbors=knn, algorithm='kd_tree') knnAlgorithm.fit(self.Xnorm) edges = knnAlgorithm.kneighbors(self.Xnorm, return_distance=False) if debug: end = time.clock() sys.stderr.write('%f s\n' % (end-start)) pairs = [] # prevent duplicates with this guy for e1 in range(0,edges.shape[0]): for col in range(0,edges.shape[1]): e2 = edges.item(e1,col) if e1 != e2: pairs.append((e1,e2)) else: pairs = edges # As seen here: # http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order seen = set() pairs = [ x for x in pairs if not (x in seen or x[::-1] in seen or seen.add(x))] edgesToPrune = [] for edge in pairs: edgesToPrune.append(edge[0]) edgesToPrune.append(edge[1]) if debug: end = time.clock() sys.stderr.write('%f s\n' % (end-start)) sys.stderr.write('Decomposition: ') start = time.clock() self.__amsc = amsc.AMSCFloat(amsc.vectorFloat(self.Xnorm.flatten()), amsc.vectorFloat(self.Y), amsc.vectorString(self.names), str(self.graph), str(self.gradient), int(self.knn), float(self.beta), str(persistence), amsc.vectorFloat(self.w), amsc.vectorInt(edgesToPrune), debug) if debug: end = time.clock() sys.stderr.write('%f s\n' % (end-start)) hierarchy = self.__amsc.PrintHierarchy().strip().split(' ') self.persistences = [] self.mergeSequence = {} for line in hierarchy: if line.startswith('Maxima') or line.startswith('Minima'): tokens = line.split(',') p = float(tokens[1]) dyingIndex = int(tokens[2]) parentIndex = int(tokens[3]) self.mergeSequence[dyingIndex] = (parentIndex,p) self.persistences.append(p) self.persistences = sorted(list(set(self.persistences))) partitions = self.Partitions(self.persistences[0]) cellIdxs = np.array(list(partitions.keys())) self.minIdxs = np.unique(cellIdxs[:,0]) self.maxIdxs = np.unique(cellIdxs[:,1]) def SetWeights(self, w=None): """ Sets the weights associated to the m input samples @ In, w, optional m vector specifying the new weights to use for the data points. Default is None and resets the weights to be uniform. """ if w is not None: self.w = np.array(w) elif len(self.Y) > 0: self.w = np.ones(len(self.Y))*1.0/float(len(self.Y)) if self.FitsSynced(): self.BuildModels() def GetMergeSequence(self): """ Returns a data structure holding the ordered merge sequence of extrema simplification @ Out, a dictionary of tuples where the key is the dying extrema and the tuple is the parent index and the persistence associated to the dying index, in that order. """ return self.mergeSequence def Partitions(self,persistence=None): """ Returns the partitioned data based on a specified persistence level. @ In, persistence, a floating point value specifying the size of the smallest feature we want to track. Default = None means consider all features. @ Out, a dictionary lists where each key is a min-max tuple specifying the index of the minimum and maximum, respectively. Each entry will hold a list of indices specifying points that are associated to this min-max pair. """ if self.__amsc is None: return None if persistence is None: persistence = self.persistence if persistence not in self.partitions: partitions = self.__amsc.GetPartitions(persistence) tupleKeyedPartitions = {} minMaxKeys = partitions.keys() for strMinMax in minMaxKeys: indices = partitions[strMinMax] minMax = tuple(map(int,strMinMax.split(','))) tupleKeyedPartitions[minMax] = indices self.partitions[persistence] = tupleKeyedPartitions return self.partitions[persistence] def StableManifolds(self,persistence=None): """ Returns the partitioned data based on a specified persistence level. @ In, persistence, a floating point value specifying the size of the smallest feature we want to track. Default = None means consider all features. @ Out, a dictionary lists where each key is a integer specifying the index of the maximum. Each entry will hold a list of indices specifying points that are associated to this maximum. """ if persistence is None: persistence = self.persistence return self.__amsc.GetStableManifolds(persistence) def UnstableManifolds(self,persistence=None): """ Returns the partitioned data based on a specified persistence level. @ In, persistence, a floating point value specifying the size of the smallest feature we want to track. Default = None means consider all features. @ Out, a dictionary lists where each key is a integer specifying the index of the minimum. Each entry will hold a list of indices specifying points that are associated to this minimum. """ if persistence is None: persistence = self.persistence return self.__amsc.GetUnstableManifolds(persistence) def SegmentFitCoefficients(self): """ Returns a dictionary keyed off the min-max index pairs defining Morse-Smale segments where the values are the linear coefficients of the input dimensions sorted in the same order as the input data. @ Out, a dictionary with tuples as keys specifying a pair of integers denoting minimum and maximum indices. The values associated to the dictionary keys are the linear coefficients fit for each min-max pair. """ if self.segmentFits is None or len(self.segmentFits) == 0: self.BuildModels(self.persistence) coefficients = {} for key,fit in self.segmentFits.items(): coefficients[key] = fit[1:] # coefficients[key] = fit[:] return coefficients def SegmentFitnesses(self): """ Returns a dictionary keyed off the min-max index pairs defining Morse-Smale segments where the values are the R^2 metrics of the linear fits for each Morse-Smale segment. @ Out, a dictionary with tuples as keys specifying a pair of integers denoting minimum and maximum indices. The values associated to the dictionary keys are the R^2 values for each linear fit of the Morse-Smale segments defined by the min-max pair of integers. """ if self.segmentFits is None or len(self.segmentFits) == 0: self.BuildModels(self.persistence) rSquared = {} for key,fitness in self.segmentFitnesses.items(): rSquared[key] = fitness return rSquared def SegmentPearsonCoefficients(self): """ Returns a dictionary keyed off the min-max index pairs defining Morse-Smale segments where the values are the Pearson correlation coefficients of the input dimensions sorted in the same order as the input data. @ Out, a dictionary with tuples as keys specifying a pair of integers denoting minimum and maximum indices. The values associated to the dictionary keys are the Pearson correlation coefficients associated to each subset of the data. """ if self.segmentFits is None or len(self.segmentFits) == 0: self.BuildModels(self.persistence) pearson = {} for key,fit in self.pearson.items(): pearson[key] = fit[:] return pearson def SegmentSpearmanCoefficients(self): """ Returns a dictionary keyed off the min-max index pairs defining Morse-Smale segments where the values are the Spearman rank correlation coefficients of the input dimensions sorted in the same order as the input data. @ Out, a dictionary with tuples as keys specifying a pair of integers denoting minimum and maximum indices. The values associated to the dictionary keys are the Spearman rank correlation coefficients associated to each subset of the data. """ if self.segmentFits is None or len(self.segmentFits) == 0: self.BuildModels(self.persistence) spearman = {} for key,fit in self.spearman.items(): spearman[key] = fit[:] return spearman def GetMask(self,indices=None): """ Applies all data filters to the input data and returns a list of filtered indices that specifies the rows of data that satisfy all conditions. @ In, indices, an optional integer list of indices to start from, if not supplied, then the mask will be applied to all indices of the data. @ Out, a 1-dimensional array of integer indices that is a subset of the input data row indices specifying rows that satisfy every set filter criterion. """ if indices is None: indices = list(range(0,self.GetSampleSize())) mask = np.ones(len(indices), dtype=bool) for header,bounds in self.filters.items(): if header in self.names: idx = self.names.index(header) if idx >= 0 and idx < len(self.names)-1: vals = self.X[indices,idx] elif idx == len(self.names)-1: vals = self.Y[indices] elif header == 'Predicted from Linear Fit': vals = self.PredictY(indices, fit='linear', applyFilters=False) elif header == 'Predicted from Maximum Fit': vals = self.PredictY(indices, fit='maximum', applyFilters=False) elif header == 'Predicted from Minimum Fit': vals = self.PredictY(indices, fit='minimum', applyFilters=False) elif header == 'Residual from Linear Fit': vals = self.Residuals(indices, fit='linear', applyFilters=False) elif header == 'Residual from Maximum Fit': vals = self.Residuals(indices, fit='maximum', applyFilters=False) elif header == 'Residual from Minimum Fit': vals = self.Residuals(indices, fit='minimum', applyFilters=False) elif header == 'Probability': vals = self.w[indices] mask = np.logical_and(mask, bounds[0] <= vals) mask = np.logical_and(mask, vals < bounds[1]) indices = np.array(indices)[mask] indices = np.array(sorted(list(set(indices)))) return indices def ComputePerDimensionFitErrors(self,key): """ Heuristically builds lower-dimensional linear patches for a Morse-Smale segment specified by a tuple of integers, key. The heuristic is to sort the set of linear coefficients by magnitude and progressively refit the data using more and more dimensions and computing R^2 values for each lower dimensional fit until we arrive at the full dimensional linear fit @ In, key, a tuple of two integers specifying the minimum and maximum indices used to key the partition upon which we are retrieving info. @ Out, a tuple of three equal sized lists that specify the index order of the dimensions added where the indices match the input data's order, the R^2 values for each progressively finer fit, and the F-statistic for each progressively finer fit. Thus, an index order of [2,3,1,0] would imply the first fit uses only dimension 2, and the next fit uses dimension 2 and 3, and the next fit uses 2, 3, and 1, and the final fit uses dimensions 2, 1, 3, and 0. """ partitions = self.Partitions(self.persistence) if key not in self.segmentFits or key not in partitions: return None beta_hat = self.segmentFits[key][1:] yIntercept = self.segmentFits[key][0] # beta_hat = self.segmentFits[key][:] # yIntercept = 0 items = partitions[key] X = self.Xnorm[np.array(items),:] y = self.Y[np.array(items)] w = self.w[np.array(items)] yHat = X.dot(beta_hat) + yIntercept RSS2 = np.sum(w*(y-yHat)**2)/np.sum(w) RSS1 = 0 rSquared = [] ## From here: http://en.wikipedia.org/wiki/F-test fStatistic = [] ## the computed F statistic indexOrder = list(reversed(np.argsort(np.absolute(beta_hat)))) for i,nextDim in enumerate(indexOrder): B = np.zeros(self.GetDimensionality()) for activeDim in indexOrder[0: (i+1)]: B[activeDim] = beta_hat[activeDim] X = self.X[np.array(items),:] X = X[:,indexOrder[0:(i+1)]] ## In the first case, X will be one-dimensional, so we have to enforce a ## reshape in order to get it to play nice. X = np.reshape(X,(len(items),i+1)) y = self.Y[np.array(items)] w = self.w[np.array(items)] (temp_yIntercept,temp_beta_hat) = WeightedLinearModel(X,y,w) yHat = X.dot(temp_beta_hat) + temp_yIntercept # Get a weighted mean yMean = np.average(y,weights=w) RSS2 = np.sum(w*(y-yHat)**2)/np.sum(w) if RSS1 == 0: fStatistic.append(0) else: fStatistic.append( (RSS1-RSS2)/(len(indexOrder)-i) \ / (RSS2/(len(y)-len(indexOrder))) ) SStot = np.sum(w*(y-yMean)**2)/np.sum(w) rSquared.append(1-(RSS2/SStot)) RSS1 = RSS2 return (indexOrder,rSquared,fStatistic) def Persistence(self, p=None): """ Sets or returns the persistence simplfication level to be used for representing this Morse-Smale complex @ In, p, a floating point value that will set the persistence value, if this value is set to None, then this function will return the current persistence leve. @ Out, if no p value is supplied then this function will return the current persistence setting. If a p value is supplied, it will be returned as it will be the new persistence setting of this object. """ if p is None: return self.persistence self.persistence = p self.segmentFits = {} self.extremumFits = {} self.segmentFitnesses = {} self.extremumFitnesses = {} return self.persistence def BuildModels(self,persistence=None): """ Forces the construction of linear fits per Morse-Smale segment and Gaussian fits per stable/unstable manifold for the user-specified persistence level. @ In, persistence, a floating point value specifying the simplification level to use, if this value is None, then we will build models based on the internally set persistence level for this Morse-Smale object. """ self.segmentFits = {} self.extremumFits = {} self.segmentFitnesses = {} self.extremumFitnesses = {} self.BuildLinearModels(persistence) self.ComputeStatisticalSensitivity() def BuildLinearModels(self, persistence=None): """ Forces the construction of linear fits per Morse-Smale segment. @ In, persistence, a floating point value specifying the simplification level to use, if this value is None, then we will build models based on the internally set persistence level for this Morse-Smale object. """ partitions = self.Partitions(persistence) for key,items in partitions.items(): X = self.Xnorm[np.array(items),:] y = np.array(self.Y[np.array(items)]) w = self.w[np.array(items)] (temp_yIntercept,temp_beta_hat) = WeightedLinearModel(X,y,w) self.segmentFits[key] = np.hstack((temp_yIntercept,temp_beta_hat)) yHat = X.dot(self.segmentFits[key][1:]) + self.segmentFits[key][0] self.segmentFitnesses[key] = sum(np.sqrt((yHat-y)**2)) def GetNames(self): """ Returns the names of the input and output dimensions in the order they appear in the input data. @ Out, a list of strings specifying the input + output variable names. """ return self.names def GetNormedX(self,rows=None,cols=None,applyFilters=False): """ Returns the normalized input data requested by the user @ In, rows, a list of non-negative integers specifying the row indices to return @ In, cols, a list of non-negative integers specifying the column indices to return @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a matrix of floating point values specifying the normalized data values used in internal computations filtered by the three input parameters. """ if rows is None: rows = list(range(0,self.GetSampleSize())) if cols is None: cols = list(range(0,self.GetDimensionality())) if applyFilters: rows = self.GetMask(rows) retValue = self.Xnorm[rows,:] return retValue[:,cols] def GetX(self,rows=None,cols=None,applyFilters=False): """ Returns the input data requested by the user @ In, rows, a list of non-negative integers specifying the row indices to return @ In, cols, a list of non-negative integers specifying the column indices to return @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a matrix of floating point values specifying the input data values filtered by the three input parameters. """ if rows is None: rows = list(range(0,self.GetSampleSize())) if cols is None: cols = list(range(0,self.GetDimensionality())) rows = sorted(list(set(rows))) if applyFilters: rows = self.GetMask(rows) retValue = self.X[rows,:] if len(rows) == 0: return [] return retValue[:,cols] def GetY(self, indices=None, applyFilters=False): """ Returns the output data requested by the user @ In, indices, a list of non-negative integers specifying the row indices to return @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a list of floating point values specifying the output data values filtered by the two input parameters. """ if indices is None: indices = list(range(0,self.GetSampleSize())) else: indices = sorted(list(set(indices))) if applyFilters: indices = self.GetMask(indices) if len(indices) == 0: return [] return self.Y[indices] def GetLabel(self, indices=None, applyFilters=False): """ Returns the label pair indices requested by the user @ In, indices, a list of non-negative integers specifying the row indices to return @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a list of integer 2-tuples specifying the minimum and maximum index of the specified rows. """ if indices is None: indices = list(range(0,self.GetSampleSize())) elif isinstance(indices,collections.Iterable): indices = sorted(list(set(indices))) else: indices = [indices] if applyFilters: indices = self.GetMask(indices) if len(indices) == 0: return [] partitions = self.__amsc.GetPartitions(self.persistence) labels = self.X.shape[0]*[None] for strMinMax in partitions.keys(): partIndices = partitions[strMinMax] label = tuple(map(int,strMinMax.split(','))) for idx in np.intersect1d(partIndices,indices): labels[idx] = label labels = np.array(labels) if len(indices) == 1: return labels[indices][0] return labels[indices] def GetWeights(self, indices=None, applyFilters=False): """ Returns the weights requested by the user @ In, indices, a list of non-negative integers specifying the row indices to return @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a list of floating point values specifying the weights associated to the input data rows filtered by the two input parameters. """ if indices is None: indices = list(range(0,self.GetSampleSize())) else: indices = sorted(list(set(indices))) if applyFilters: indices = self.GetMask(indices) if len(indices) == 0: return [] return self.w[indices] def Predict(self, x, key): """ Returns the predicted response of x given a model index @ In, x, a list of input values matching the dimensionality of the input space @ In, key, a 2-tuple specifying a min-max id pair used for determining which model is being used for prediction @ Out, a predicted response value for the given input point """ partitions = self.Partitions(self.persistence) beta_hat = self.segmentFits[key][1:] y_intercept = self.segmentFits[key][0] if len(x.shape) == 1: return x.dot(beta_hat) + y_intercept else: predictions = [] for xi in x: predictions.append(xi.dot(beta_hat) + y_intercept) return predictions def PredictY(self,indices=None, fit='linear',applyFilters=False): """ Returns the predicted output values requested by the user @ In, indices, a list of non-negative integers specifying the row indices to predict @ In, fit, an optional string specifying which fit should be used to predict each location, 'linear' = Morse-Smale segment, 'maxima' = descending/stable manifold, 'minima' = ascending/unstable manifold. Only 'linear' is available in this version. @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a list of floating point values specifying the predicted output values filtered by the three input parameters. """ partitions = self.Partitions(self.persistence) predictedY = np.zeros(self.GetSampleSize()) if fit == 'linear': for key,items in partitions.items(): beta_hat = self.segmentFits[key][1:] y_intercept = self.segmentFits[key][0] for idx in items: predictedY[idx] = self.Xnorm[idx,:].dot(beta_hat) + y_intercept ## Possible extension to fit data per stable or unstable manifold would ## go here if indices is None: indices = list(range(0,self.GetSampleSize())) if applyFilters: indices = self.GetMask(indices) indices = np.array(sorted(list(set(indices)))) return predictedY[indices] def Residuals(self,indices=None,fit='linear',signed=False,applyFilters=False): """ Returns the residual between the output data and the predicted output values requested by the user @ In, indices, a list of non-negative integers specifying the row indices for which to compute residuals @ In, fit, an optional string specifying which fit should be used to predict each location, 'linear' = Morse-Smale segment, 'maxima' = descending/stable manifold, 'minima' = ascending/unstable manifold @ In, applyFilters, a boolean specifying whether data filters should be used to prune the results @ Out, a list of floating point values specifying the signed difference between the predicted output values and the original output data filtered by the three input parameters. """ if indices is None: indices = list(range(0,self.GetSampleSize())) else: indices = sorted(list(set(indices))) if applyFilters: indices = self.GetMask(indices) indices = np.array(sorted(list(set(indices)))) yRange = max(self.Y) - min(self.Y) actualY = self.GetY(indices) predictedY = self.PredictY(indices,fit) if signed: residuals = (actualY-predictedY)/yRange else: residuals = np.absolute(actualY-predictedY)/yRange return residuals def GetColors(self): """ Returns a dictionary of colors where the keys specify Morse-Smale segment min-max integer index pairs, unstable/ascending manifold minima integer indices, and stable/descending manifold maxima integer indices. The values are hex strings specifying unique colors for each different type of segment. @ Out, a dictionary specifying unique colors for each Morse-Smale segment, stable/descending manifold, and unstable/ascending manifold. """ partitions = self.Partitions(self.persistence) partColors = {} for key in partitions.keys(): minKey,maxKey = key if key not in self.partitionColors: self.partitionColors[key] = next(self.colorList) if minKey not in self.partitionColors: self.partitionColors[minKey] = next(self.colorList) if maxKey not in self.partitionColors: self.partitionColors[maxKey] = next(self.colorList) # Only get the colors we need for this level of the partition partColors[key] = self.partitionColors[key] partColors[minKey] = self.partitionColors[minKey] partColors[maxKey] = self.partitionColors[maxKey] return partColors def GetSelectedExtrema(self): """ Returns the extrema highlighted as being selected in an attached UI @ Out, a list of non-negative integer indices specifying the extrema selected. """ return self.selectedExtrema def GetSelectedSegments(self): """ Returns the Morse-Smale segments highlighted as being selected in an attached UI @ Out, a list of non-negative integer index pairs specifying the min-max pairs associated to the selected Morse-Smale segments. """ return self.selectedSegments def GetCurrentLabels(self): """ Returns a list of tuples that specifies the min-max index labels associated to each input sample @ Out, a list of tuples that are each a pair of non-negative integers specifying the min-flow and max-flow indices associated to each input sample at the current level of persistence """ partitions = self.Partitions(self.persistence) return partitions.keys() def GetSampleSize(self,key = None): """ Returns the number of samples in the input data @ In, key, an optional 2-tuple specifying a min-max id pair used for determining which partition size should be returned. If not specified then the size of the entire data set will be returned. @ Out, an integer specifying the number of samples. """ if key is None: return len(self.Y) else: return len(self.partitions[self.persistence][key]) def GetDimensionality(self): """ Returns the dimensionality of the input space of the input data @ Out, an integer specifying the dimensionality of the input samples. """ return self.X.shape[1] def GetClassification(self,idx): """ Given an index, this function will report whether that sample is a local minimum, a local maximum, or a regular point. @ In, idx, a non-negative integer less than the sample size of the input data. @ Out, a string specifying the classification type of the input sample: will be 'maximum,' 'minimum,' or 'regular.' """ if idx in self.minIdxs: return 'minimum' elif idx in self.maxIdxs: return 'maximum' return 'regular' def ComputeStatisticalSensitivity(self): """ Computes the per segment Pearson correlation coefficients and the Spearman rank correlation coefficients and stores them internally. """ partitions = self.Partitions() self.pearson = {} self.spearman = {} for key,items in partitions.items(): X = self.Xnorm[np.array(items),:] y = self.Y[np.array(items)] self.pearson[key] = [] self.spearman[key] = [] for col in range(0,X.shape[1]): sigmaXcol = np.std(X[:,col]) self.pearson[key].append(scipy.stats.pearsonr(X[:,col], y)[0]) self.spearman[key].append(scipy.stats.spearmanr(X[:,col], y)[0]) def PrintHierarchy(self): """ Writes the complete Morse-Smale merge hierarchy to a string object. @ Out, a string object storing the entire merge hierarchy of all minima and maxima. """ return self.__amsc.PrintHierarchy() def GetNeighbors(self,idx): """ Returns a list of neighbors for the specified index @ In, an integer specifying the query point @ Out, a integer list of neighbors indices """ return self.__amsc.Neighbors(idx) try: import PySide.QtCore as qtc __QtAvailable = True except ImportError as e: try: import PySide2.QtCore as qtc __QtAvailable = True except ImportError as e: __QtAvailable = False if __QtAvailable: TolColors = ['#88CCEE', '#DDCC77', '#AA4499', '#117733', '#332288', '#999933', '#44AA99', '#882255', '#CC6677'] class QAMSC_Object(AMSC_Object,qtc.QObject): ## Paul Tol's colorblind safe colors colorList = itertools.cycle(TolColors) sigPersistenceChanged = qtc.Signal() sigSelectionChanged = qtc.Signal() sigFilterChanged = qtc.Signal() sigDataChanged = qtc.Signal() sigModelsChanged = qtc.Signal() sigWeightsChanged = qtc.Signal() def Reinitialize(self, X, Y, w=None, names=None, graph='beta skeleton', gradient='steepest', knn=-1, beta=1.0, normalization=None, persistence='difference', edges=None, debug=False): """ Allows the caller to basically start over with a new dataset. @ In, X, an m-by-n array of values specifying m n-dimensional samples @ In, Y, a m vector of values specifying the output responses corresponding to the m samples specified by X @ In, w, an optional m vector of values specifying the weights associated to each of the m samples used. Default of None means all points will be equally weighted @ In, names, an optional list of strings that specify the names to associate to the n input dimensions and 1 output dimension. Default of None means input variables will be x0,x1...,x(n-1) and the output will be y @ In, graph, an optional string specifying the type of neighborhood graph to use. Default is 'beta skeleton,' but other valid types are: 'delaunay,' 'relaxed beta skeleton,' or 'approximate knn' @ In, gradient, an optional string specifying the type of gradient estimator to use. Currently the only available option is 'steepest' @ In, knn, an optional integer value specifying the maximum number of k-nearest neighbors used to begin a neighborhood search. In the case of graph='[relaxed] beta skeleton', we will begin with the specified approximate knn graph and prune edges that do not satisfy the empty region criteria. @ In, beta, an optional floating point value between 0 and 2. This value is only used when graph='[relaxed] beta skeleton' and specifies the radius for the empty region graph computation (1=Gabriel graph, 2=Relative neighbor graph) @ In, normalization, an optional string specifying whether the inputs/output should be scaled before computing. Currently, two modes are supported 'zscore' and 'feature'. 'zscore' will ensure the data has a mean of zero and a standard deviation of 1 by subtracting the mean and dividing by the variance. 'feature' scales the data into the unit hypercube. @ In, persistence, an optional string specifying how we will compute the persistence hierarchy. Currently, three modes are supported 'difference', 'probability' and 'count'. 'difference' will take the function value difference of the extrema and its closest function valued neighboring saddle, 'probability' will augment this value by multiplying the probability of the extremum and its saddle, and count will make the larger point counts more persistent. """ super(QAMSC_Object,self).Reinitialize(X, Y, w, names, graph, gradient, knn, beta, normalization, persistence, edges, debug) self.sigDataChanged.emit() def Persistence(self, p=None): """ Sets or returns the persistence simplfication level to be used for representing this Morse-Smale complex @ In, p, a floating point value that will set the persistence value, if this value is set to None, then this function will return the current persistence leve. @ Out, if no p value is supplied then this function will return the current persistence setting. If a p value is supplied, it will be returned as it will be the new persistence setting of this object. """ if p is None: return self.persistence pers = super(QAMSC_Object,self).Persistence(p) self.sigPersistenceChanged.emit() return pers def SetWeights(self, w=None): """ Sets the weights associated to the m input samples @ In, w, optional m vector specifying the new weights to use for the data points. Default is None and resets the weights to be uniform. """ super(QAMSC_Object,self).SetWeights(w) self.sigWeightsChanged.emit() def BuildModels(self,persistence=None): """ Forces the construction of linear fits per Morse-Smale segment and Gaussian fits per stable/unstable manifold for the user-specified persistence level. @ In, persistence, a floating point value specifying the simplification level to use, if this value is None, then we will build models based on the internally set persistence level for this Morse-Smale object. """ super(QAMSC_Object,self).BuildModels(persistence) self.sigModelsChanged.emit() def SetSelection(self, selectionList, cross_inclusion=False): """ Sets the currently selected items of this instance @ In, selectionList, a mixed list of 2-tuples and integers representing min-max index pairs and extremum indices, respectively @ In, cross_inclusion, a boolean that will ensure if you select all of the segments attached to an extermum get selected and vice versa """ partitions = self.Partitions(self.persistence) self.selectedSegments = [] self.selectedExtrema = [] for idx in selectionList: ## Here are a few alternatives to do the same thing, I think I like the ## not an int test the best because it is less likely to change than the ## representation of the pair #if isinstance(label, tuple): #if hasattr(label, '__len__'): if isinstance(idx,int): self.selectedExtrema.append(idx) #If you select an extremum, also select all of its attached segments if cross_inclusion: for minMax in partitions.keys(): if idx in minMax: self.selectedSegments.append(minMax) else: self.selectedSegments.append(idx) #If you select an segment, also select all of its attached extrema if cross_inclusion: self.selectedExtrema.extend(list(idx)) self.selectedSegments = list(set(self.selectedSegments)) self.selectedExtrema = list(set(self.selectedExtrema)) self.sigSelectionChanged.emit() def ClearFilter(self): """ Erases all currently set filters on any dimension. """ self.filters = {} self.sigSelectionChanged.emit() def SetFilter(self,name,bounds): """ Sets the bounds of the selected dimension as a filter @ In, name, a string denoting the variable to which this filter will be applied. @ In, bounds, a list of two values specifying a lower and upper bound on the dimension specified by name. """ if bounds is None: self.filters.pop(name,None) else: self.filters[name] = bounds self.sigSelectionChanged.emit() def GetFilter(self,name): """ Returns the currently set filter for a particular dimension specified. @ In, name, a string denoting the variable for which one wants to retrieve filtered information. @ Out, a list consisting of two values that specify the filter boundaries of the queried dimension. """ if name in self.filters.keys(): return self.filters[name] else: return None def Select(self, idx): """ Add a segment or extremum to the list of currently selected items @ In, idx, either an non-negative integer or a 2-tuple of non-negative integers specifying the index of an extremum or a min-max index pair. """ if isinstance(idx,int): if idx not in self.selectedExtrema: self.selectedExtrema.append(idx) else: if idx not in self.sectedSegments: self.selectedSegments.append(idx) self.sigSelectionChanged.emit() def Deselect(self, idx): """ Remove a segment or extremum from the list of currently selected items @ In, idx, either an non-negative integer or a 2-tuple of non-negative integers specifying the index of an extremum or a min-max index pair. """ if isinstance(idx,int): if idx in self.selectedExtrema: self.selectedExtrema.remove(idx) else: if idx in self.sectedSegments: self.selectedSegments.remove(idx) self.sigSelectionChanged.emit() def ClearSelection(self): """ Empties the list of selected items. """ self.selectedSegments = [] self.selectedExtrema = [] self.sigSelectionChanged.emit() def GetSelectedIndices(self,segmentsOnly=True): """ Returns a mixed list of extremum indices and min-max index pairs specifying all of the segments selected. @ In, segmentsOnly, a boolean variable that will filter the results to only return min-max index pairs. @ Out, a list of non-negative integers and 2-tuples consisting of non-negative integers. """ partitions = self.Partitions(self.persistence) indices = [] for extPair,indexSet in partitions.items(): if extPair in self.selectedSegments \ or extPair[0] in self.selectedExtrema \ or extPair[1] in self.selectedExtrema: indices.extend(indexSet) indices = self.GetMask(indices) return list(indices) def FitsSynced(self): """ Returns whether the segment and extremum fits are built for the currently selected level of persistence. @ Out, a boolean that reports True if everything is synced and False, otherwise. """ fitKeys = self.segmentFits.keys() rSquaredKeys = self.segmentFitnesses.keys() if sorted(fitKeys) != sorted(rSquaredKeys) \ or sorted(fitKeys) != sorted(self.GetCurrentLabels()) \ or self.segmentFits is None or len(self.segmentFits) == 0: return False return True # sys.stderr.write(str(e) +'\n') # sys.exit(1)
{ "content_hash": "348ab9913cab51b6964b64c94a01f32c", "timestamp": "", "source": "github", "line_count": 1253, "max_line_length": 184, "avg_line_length": 42.740622505985634, "alnum_prop": 0.6438548007618479, "repo_name": "joshua-cogliati-inl/raven", "id": "a76b60cffbf932f0fbe64e9c3dd3dd5073b7d2b6", "size": "53633", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "src/AMSC/AMSC_Object.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1556080" }, { "name": "Batchfile", "bytes": "1095" }, { "name": "C", "bytes": "148504" }, { "name": "C++", "bytes": "48279546" }, { "name": "CMake", "bytes": "9998" }, { "name": "Jupyter Notebook", "bytes": "84202" }, { "name": "MATLAB", "bytes": "202335" }, { "name": "Makefile", "bytes": "2399" }, { "name": "Perl", "bytes": "1297" }, { "name": "Python", "bytes": "6952659" }, { "name": "R", "bytes": "67" }, { "name": "SWIG", "bytes": "8574" }, { "name": "Shell", "bytes": "124279" }, { "name": "TeX", "bytes": "479725" } ], "symlink_target": "" }
from django.conf.urls import include from django.conf.urls import patterns from django.conf.urls import url from django.shortcuts import HttpResponse from django.conf import settings from tastypie.api import Api from api.resources import UserResource from api.resources import UserProfileResource from api.resources import WhiteListItemResource from api.resources import BlackListItemResource from api.resources import EyeHistoryResource from api.resources import EyeHistoryMessageResource from api.resources import ChatMessageResource from api.resources import MuteListResource from api.resources import LoginResource from api.resources import RatingsResource from api.resources import PageResource from eyebrowse.views import about from eyebrowse.views import faq from eyebrowse.views import tutorial from eyebrowse.views import mft, mft_results_treatment, mft_results_control from eyebrowse.views import api_docs from eyebrowse.views import consent_accept from eyebrowse.views import consent from eyebrowse.views import getting_started v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(UserProfileResource()) v1_api.register(WhiteListItemResource()) v1_api.register(BlackListItemResource()) v1_api.register(EyeHistoryResource()) v1_api.register(EyeHistoryMessageResource()) v1_api.register(ChatMessageResource()) v1_api.register(MuteListResource()) v1_api.register(LoginResource()) v1_api.register(RatingsResource()) v1_api.register(PageResource()) # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'', include('django.contrib.auth.urls')), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), url(r'^robots\.txt$', lambda r: HttpResponse( "User-agent: *\nDisallow: /", mimetype="text/plain")), url(r'^users/(?P<username>.+?)/visualizations$', 'stats.views.profile_viz'), url(r'^users/(?P<username>.+)$', 'stats.views.profile_data'), url(r'^following/(?P<username>.+)$', 'stats.views.following_data'), url(r'^followers/(?P<username>.+)$', 'stats.views.followers_data'), url(r"^notifications/", include("notifications.urls")), url(r'^notifications', 'notifications.views.notifications'), url(r'^accounts/', include('accounts.urls')), url(r'^live_stream/', include('live_stream.urls')), url(r'^visualizations/word_cloud/$', 'live_stream.views.word_cloud_viz'), url(r'^visualizations/hour_of_day/$', 'live_stream.views.hod_viz'), url(r'^visualizations/day_of_week/$', 'live_stream.views.dow_viz'), url(r'^stats/', include('stats.urls')), url(r'^api/', include('api.urls')), url(r'^api/', include(v1_api.urls)), url(r'^about', about), url(r'^tutorial', tutorial), url(r'^faq', faq), url(r'^mft/(?P<token>.+)$', mft), url(r'^mft_results/827', mft_results_treatment), url(r'^mft_results/543', mft_results_control), url(r'^api_docs', api_docs), url(r'^consent_accept$', consent_accept), url(r'^consent$', consent), url(r'^getting_started$', getting_started), url(r'^ext/', include("extension.urls")), url(r'^tags/', include("tags.urls")) ) urlpatterns += patterns('eyebrowse.views', url(r'^google3a0cf4e7f8daa91b.html$', 'google_verify'), url(r'^feedback$', 'feedback'), url(r'^add_tag$', 'add_tag'), url(r'^delete_tag$', 'delete_tag'), url(r'^color_tag$', 'color_tag'), url(r'^downloads$', 'downloads'), url(r'^$', 'home'), url(r'^tracking/', include('tracking.urls')), )
{ "content_hash": "727ada34b300fa400af08fa749da4a7d", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 96, "avg_line_length": 42.44642857142857, "alnum_prop": 0.5557425326041229, "repo_name": "haystack/eyebrowse-server", "id": "b1f25b657f11a555fc9ddddb617f30ccc00065cb", "size": "4754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eyebrowse/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13941" }, { "name": "HTML", "bytes": "149107" }, { "name": "Java", "bytes": "4327" }, { "name": "JavaScript", "bytes": "82373" }, { "name": "Makefile", "bytes": "1104" }, { "name": "PostScript", "bytes": "1643" }, { "name": "Python", "bytes": "1092543" }, { "name": "Shell", "bytes": "758" } ], "symlink_target": "" }
from ..token import Token from .node import Node from .identifier import Identifier class IdentifierList(list, Node): """ Parse a list of identifiers. """ def __init__(self): """ Create a list of identifiers. """ super(IdentifierList, self).__init__() @classmethod def parse(cls, tokenizer, identifiers, declaration=False): """ Parse a list of identifiers. """ identifier_list = IdentifierList() while True: # parse the identifier identifier_list.append(Identifier.parse( tokenizer, identifiers, declaration=declaration)) # check if there are more identifiers if tokenizer.get_token() == Token.COMMA: tokenizer.skip_token() # no more identifiers else: break return identifier_list def __str__(self): """ Human-readable string representation. """ return ", ".join(map(lambda d: str(d), self))
{ "content_hash": "181fb656ca2d5641fcd13086e3f5f12b", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 62, "avg_line_length": 23.29787234042553, "alnum_prop": 0.5360730593607306, "repo_name": "CtrlC-Root/cse3341", "id": "1154fda878cb5fdcf6cf772355ce270da16f7ff5", "size": "1095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/cse3341/pt/identifier_list.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "61457" }, { "name": "Scheme", "bytes": "3162" } ], "symlink_target": "" }