commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
faa683d04e307b0a2bf4cbedb463686a65c61645
disable buggy test stup
dmaticzka/EDeN,smautner/EDeN,fabriziocosta/EDeN,fabriziocosta/EDeN,smautner/EDeN,dmaticzka/EDeN
test/test_bin_model.py
test/test_bin_model.py
import re # from filecmp import cmp from scripttest import TestFileEnvironment testdir = "test/" bindir = "bin/" datadir = "test/data/" testenv = testdir + 'testenv_bin_model/' env = TestFileEnvironment(testenv) # relative to test file environment: testenv bindir_rel = "../../" + bindir datadir_rel = "../../" + datadir def test_call_without_parameters(): "Call bin/model without any additional parameters." call_script = bindir_rel + 'model' run = env.run(*call_script.split(), expect_error=True ) assert re.search("too few arguments", run.stderr), 'expecting "too few arguments" in stderr' # def test_fit(): # "Call bin/model in fit mode." # call_script = bindir_rel + 'model -p xx -n xx' # run = env.run(*call_script.split()) # assert False, str(run.files_created)
import re # from filecmp import cmp from scripttest import TestFileEnvironment testdir = "test/" bindir = "bin/" datadir = "test/data/" testenv = testdir + 'testenv_bin_model/' env = TestFileEnvironment(testenv) # relative to test file environment: testenv bindir_rel = "../../" + bindir datadir_rel = "../../" + datadir def test_call_without_parameters(): "Call bin/model without any additional parameters." call_script = bindir_rel + 'model' run = env.run(*call_script.split(), expect_error=True ) assert re.search("too few arguments", run.stderr), 'expecting "too few arguments" in stderr' def test_fit(): "Call bin/model in fit mode." call_script = bindir_rel + 'model -p xx -n xx' run = env.run(*call_script.split()) assert False, str(run.files_created)
mit
Python
981300a70bce72bfa76958eefc1dd494a94e7b77
Fix coding separation issue
MuhammadAlkarouri/hug,timothycrosley/hug,timothycrosley/hug,MuhammadAlkarouri/hug,timothycrosley/hug,MuhammadAlkarouri/hug
hug/input_format.py
hug/input_format.py
"""hug/input_formats.py Defines the built-in Hug input_formatting handlers Copyright (C) 2016 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import json as json_converter import re from hug.format import content_type, underscore RE_CHARSET = re.compile("charset=(?P<charset>[^;]+)") def separate_encoding(content_type, default=None): """Separates out the encoding from the content_type and returns both in a tuple (content_type, encoding)""" encoding = default if content_type and ";" in content_type: content_type, rest = content_type.split(";", 1) charset = RE_CHARSET.search(rest) if charset: encoding = charset.groupdict().get('charset', encoding).strip() return (content_type, encoding) @content_type('text/plain') def text(body, encoding='utf-8'): """Takes plain text data""" return body.read().decode(encoding) @content_type('application/json') def json(body, encoding='utf-8'): """Takes JSON formatted data, converting it into native Python objects""" return json_converter.loads(text(body, encoding=encoding)) def _underscore_dict(dictionary): new_dictionary = {} for key, value in dictionary.items(): if isinstance(value, dict): value = _underscore_dict(value) if isinstance(key, str): key = underscore(key) new_dictionary[key] = value return new_dictionary def json_underscore(body): """Converts JSON formatted date to native Python objects. The keys in any JSON dict are transformed from camelcase to underscore separated words. """ return _underscore_dict(json(body))
"""hug/input_formats.py Defines the built-in Hug input_formatting handlers Copyright (C) 2016 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import json as json_converter import re from hug.format import content_type, underscore RE_CHARSET = re.compile("charset=(?P<charset>[^;]+)") def separate_encoding(content_type, default=None): """Separates out the encoding from the content_type and returns both in a tuple (content_type, encoding)""" encoding = default if content_type and ";" in content_type: content_type, rest = content_type.split(";", 1) charset = RE_CHARSET.search(rest).groupdict() encoding = charset.get('charset', encoding).strip() return (content_type, encoding) @content_type('text/plain') def text(body, encoding='utf-8'): """Takes plain text data""" return body.read().decode(encoding) @content_type('application/json') def json(body, encoding='utf-8'): """Takes JSON formatted data, converting it into native Python objects""" return json_converter.loads(text(body, encoding=encoding)) def _underscore_dict(dictionary): new_dictionary = {} for key, value in dictionary.items(): if isinstance(value, dict): value = _underscore_dict(value) if isinstance(key, str): key = underscore(key) new_dictionary[key] = value return new_dictionary def json_underscore(body): """Converts JSON formatted date to native Python objects. The keys in any JSON dict are transformed from camelcase to underscore separated words. """ return _underscore_dict(json(body))
mit
Python
0eebc40a74b35fccbe79abdca4afb4aa1cc25d25
Simplify test skipping using `importorskip()`
d-grossman/pelops,Lab41/pelops,dave-lab41/pelops,dave-lab41/pelops,Lab41/pelops,d-grossman/pelops
testci/test_chipper.py
testci/test_chipper.py
import pytest import datetime as dt # OpenCV is *VERY* hard to install in CircleCI, so if we don't have it, skip these tests cv2 = pytest.importorskip("cv2") # Skip all tests if not found from pelops.datasets.chipper import FrameProducer @pytest.fixture def frame_time_fp(tmpdir): # Define a FrameProducer with just enough information to run __get_frame_time() ifp = FrameProducer( file_list = [], ) ifp.vid_metadata = {"fps": 30} return ifp @pytest.fixture def frame_time_fp_data(tmpdir): # Data to test __get_frame_time() DATA = ( # (filename, frame number), (answer) (("/foo/bar/baz_20000101T000000-00000-006000.mp4", 0), dt.datetime(2000, 1, 1)), (("/foo/bar/baz_20000101T000000-00600-012000.mp4", 0), dt.datetime(2000, 1, 1, 0, 10)), (("/foo/bar/baz_20000101T000000-00000-006000.mp4", 1), dt.datetime(2000, 1, 1, 0, 0, 0, 33333)), (("/foo/bar/baz_20000101T000000-00600-012000.mp4", 10), dt.datetime(2000, 1, 1, 0, 10, 0, 333333)), ) return DATA def test_get_frame_time(frame_time_fp, frame_time_fp_data): for input, answer in frame_time_fp_data: output = frame_time_fp._FrameProducer__get_frame_time(input[0], input[1]) assert output == answer
import pytest import datetime as dt # OpenCV is *VERY* hard to install in CircleCI, so if we don't have it, skip these tests try: cv2 = pytest.importorskip("cv2") from pelops.datasets.chipper import FrameProducer except ImportError: pass @pytest.fixture def frame_time_fp(tmpdir): # Define a FrameProducer with just enough information to run __get_frame_time() ifp = FrameProducer( file_list = [], ) ifp.vid_metadata = {"fps": 30} return ifp @pytest.fixture def frame_time_fp_data(tmpdir): # Data to test __get_frame_time() DATA = ( # (filename, frame number), (answer) (("/foo/bar/baz_20000101T000000-00000-006000.mp4", 0), dt.datetime(2000, 1, 1)), (("/foo/bar/baz_20000101T000000-00600-012000.mp4", 0), dt.datetime(2000, 1, 1, 0, 10)), (("/foo/bar/baz_20000101T000000-00000-006000.mp4", 1), dt.datetime(2000, 1, 1, 0, 0, 0, 33333)), (("/foo/bar/baz_20000101T000000-00600-012000.mp4", 10), dt.datetime(2000, 1, 1, 0, 10, 0, 333333)), ) return DATA def test_get_frame_time(frame_time_fp, frame_time_fp_data): for input, answer in frame_time_fp_data: output = frame_time_fp._FrameProducer__get_frame_time(input[0], input[1]) assert output == answer
apache-2.0
Python
3c735d18bdcff28bbdd765b131649ba57fb612b0
Revert "Revert "Remove useless code""
ALSchwalm/hy,aisk/hy,paultag/hy,tianon/hy,hcarvalhoalves/hy,Foxboron/hy,Tritlo/hy,mtmiller/hy,michel-slm/hy,farhaven/hy,freezas/hy,zackmdavis/hy,tianon/hy,gilch/hy,aisk/hy,larme/hy,tuturto/hy,timmartin/hy,farhaven/hy,kirbyfan64/hy,farhaven/hy,algernon/hy,Foxboron/hy,hcarvalhoalves/hy,kirbyfan64/hy,adamfeuer/hy,jakirkham/hy,tianon/hy,larme/hy,larme/hy,kartikm/hy,aisk/hy
hy/models/string.py
hy/models/string.py
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ pass
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from hy.models import HyObject import sys if sys.version_info[0] >= 3: str_type = str else: str_type = unicode class HyString(HyObject, str_type): """ Generic Hy String object. Helpful to store string literals from Hy scripts. It's either a ``str`` or a ``unicode``, depending on the Python version. """ def __new__(cls, value): obj = str_type.__new__(cls, value) return obj
mit
Python
f594d211b0e95c17edc9eca693f05d307515e1a7
remove unused "event" parameter in I18nFieldMixin (#34)
raphaelm/django-i18nfield
i18nfield/fields.py
i18nfield/fields.py
import json import django from django.conf import settings from django.db import models from .forms import I18nFormField, I18nTextarea, I18nTextInput from .strings import LazyI18nString class I18nFieldMixin: form_class = I18nFormField widget = I18nTextInput def to_python(self, value): if isinstance(value, LazyI18nString): return value if value is None: return None return LazyI18nString(value) def get_prep_value(self, value): if isinstance(value, LazyI18nString): value = value.data if isinstance(value, dict): return json.dumps({k: v for k, v in value.items() if v}, sort_keys=True) if isinstance(value, LazyI18nString.LazyGettextProxy): return json.dumps({lng: value[lng] for lng, lngname in settings.LANGUAGES if value[lng]}, sort_keys=True) return value def get_prep_lookup(self, lookup_type, value): # NOQA raise TypeError('Lookups on i18n strings are currently not supported.') if django.VERSION < (2,): def from_db_value(self, value, expression, connection, context): return LazyI18nString(value) else: def from_db_value(self, value, expression, connection): return LazyI18nString(value) def value_to_string(self, obj): value = self.value_from_object(obj) return self.get_prep_value(value) def formfield(self, **kwargs): defaults = {'form_class': self.form_class, 'widget': self.widget} defaults.update(kwargs) return super().formfield(**defaults) class I18nCharField(I18nFieldMixin, models.TextField): """ A CharField which takes internationalized data. Internally, a TextField dabase field is used to store JSON. If you interact with this field, you will work with LazyI18nString instances. """ widget = I18nTextInput class I18nTextField(I18nFieldMixin, models.TextField): """ Like I18nCharField, but for TextFields. """ widget = I18nTextarea
import json import django from django.conf import settings from django.db import models from .forms import I18nFormField, I18nTextarea, I18nTextInput from .strings import LazyI18nString class I18nFieldMixin: form_class = I18nFormField widget = I18nTextInput def __init__(self, *args, **kwargs): self.event = kwargs.pop('event', None) super().__init__(*args, **kwargs) def to_python(self, value): if isinstance(value, LazyI18nString): return value if value is None: return None return LazyI18nString(value) def get_prep_value(self, value): if isinstance(value, LazyI18nString): value = value.data if isinstance(value, dict): return json.dumps({k: v for k, v in value.items() if v}, sort_keys=True) if isinstance(value, LazyI18nString.LazyGettextProxy): return json.dumps({lng: value[lng] for lng, lngname in settings.LANGUAGES if value[lng]}, sort_keys=True) return value def get_prep_lookup(self, lookup_type, value): # NOQA raise TypeError('Lookups on i18n strings are currently not supported.') if django.VERSION < (2,): def from_db_value(self, value, expression, connection, context): return LazyI18nString(value) else: def from_db_value(self, value, expression, connection): return LazyI18nString(value) def value_to_string(self, obj): value = self.value_from_object(obj) return self.get_prep_value(value) def formfield(self, **kwargs): defaults = {'form_class': self.form_class, 'widget': self.widget} defaults.update(kwargs) return super().formfield(**defaults) class I18nCharField(I18nFieldMixin, models.TextField): """ A CharField which takes internationalized data. Internally, a TextField dabase field is used to store JSON. If you interact with this field, you will work with LazyI18nString instances. """ widget = I18nTextInput class I18nTextField(I18nFieldMixin, models.TextField): """ Like I18nCharField, but for TextFields. """ widget = I18nTextarea
apache-2.0
Python
26c589ba0758c34516455803647d98e91c1bd47d
Print detected image class on top of the video stream.
google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian
src/examples/vision/image_classification_camera.py
src/examples/vision/image_classification_camera.py
#!/usr/bin/env python3 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Camera image classification demo code. Runs continuous image classification on camera frames and prints detected object classes. Example: image_classification_camera.py --num_frames 10 """ import argparse import contextlib from aiy.vision.inference import CameraInference from aiy.vision.models import image_classification from picamera import PiCamera def classes_info(classes): return ', '.join('%s (%.2f)' % pair for pair in classes) @contextlib.contextmanager def CameraPreview(camera, enabled): enabled and camera.start_preview() try: yield finally: enabled and camera.stop_preview() def main(): parser = argparse.ArgumentParser('Image classification camera inference example.') parser.add_argument('--num_frames', '-n', type=int, default=None, help='Sets the number of frames to run for, otherwise runs forever.') parser.add_argument('--num_objects', '-c', type=int, default=3, help='Sets the number of object interences to print.') parser.add_argument('--nopreview', dest='preview', action='store_false', default=True, help='Enable camera preview') args = parser.parse_args() with PiCamera(sensor_mode=4, framerate=30) as camera, \ CameraPreview(camera, enabled=args.preview), \ CameraInference(image_classification.model()) as inference: for result in inference.run(args.num_frames): classes = image_classification.get_classes(result, max_num_objects=args.num_objects) print(classes_info(classes)) if classes: camera.annotate_text = '%s (%.2f)' % classes[0] if __name__ == '__main__': main()
#!/usr/bin/env python3 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Camera image classification demo code. Runs continuous image detection on the VisionBonnet and prints the object and probability for top three objects. Example: image_classification_camera.py --num_frames 10 """ import argparse from aiy.vision.inference import CameraInference from aiy.vision.models import image_classification from picamera import PiCamera def classes_info(classes, count): return ', '.join('%s (%.2f)' % pair for pair in classes[0:count]) def main(): parser = argparse.ArgumentParser('Image classification camera inference example.') parser.add_argument('--num_frames', '-n', type=int, dest='num_frames', default=None, help='Sets the number of frames to run for, otherwise runs forever.') parser.add_argument('--num_objects', '-c', type=int, dest='num_objects', default=3, help='Sets the number of object interences to print.') args = parser.parse_args() # Forced sensor mode, 1640x1232, full FoV. See: # https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes with PiCamera(sensor_mode=4, framerate=30) as camera: camera.start_preview() with CameraInference(image_classification.model()) as inference: for result in inference.run(args.num_frames): classes = image_classification.get_classes(result) print(classes_info(classes, args.num_objects)) camera.stop_preview() if __name__ == '__main__': main()
apache-2.0
Python
ba7397cf5954ad5ab2d243b540c4d0629c9d42ca
Add test for MTanhProfile
PlasmaControl/DESC,PlasmaControl/DESC
tests/test_profiles.py
tests/test_profiles.py
import numpy as np import unittest import pytest from desc.io import InputReader from desc.equilibrium import Equilibrium from desc.profiles import PowerSeriesProfile class TestProfiles(unittest.TestCase): def test_same_result(self): input_path = "examples/DESC/SOLOVEV" ir = InputReader(input_path) eq1 = Equilibrium(ir.inputs[-1]) eq2 = eq1.copy() eq2.pressure = eq1.pressure.to_spline() eq2.iota = eq1.iota.to_spline() eq1.solve() eq2.solve() np.testing.assert_allclose( eq1.x, eq2.x, rtol=1e-05, atol=1e-08, ) def test_close_values(self): pp = PowerSeriesProfile(modes=np.array([0, 2, 4]), params=np.array([1, -2, 1])) sp = pp.to_spline() with pytest.warns(UserWarning): mp = pp.to_mtanh(order=4, ftol=1e-12, xtol=1e-12) x = np.linspace(0, 1, 100) np.testing.assert_allclose(pp(x), sp(x), rtol=1e-5, atol=1e-3) np.testing.assert_allclose(pp(x), mp(x), rtol=1e-3, atol=1e-2) pp1 = sp.to_powerseries(order=4) np.testing.assert_allclose(pp.params, pp1.params, rtol=1e-5, atol=1e-2) pp2 = mp.to_powerseries(order=4) np.testing.assert_allclose(pp.params, pp2.params, rtol=1e-5, atol=1e-2)
import numpy as np import unittest from desc.io import InputReader from desc.equilibrium import Equilibrium from desc.profiles import PowerSeriesProfile class TestProfiles(unittest.TestCase): def test_same_result(self): input_path = "examples/DESC/SOLOVEV" ir = InputReader(input_path) eq1 = Equilibrium(ir.inputs[-1]) eq2 = eq1.copy() eq2.pressure = eq1.pressure.to_spline() eq2.iota = eq1.iota.to_spline() eq1.solve() eq2.solve() np.testing.assert_allclose( eq1.x, eq2.x, rtol=1e-05, atol=1e-08, ) def test_close_values(self): pp = PowerSeriesProfile(modes=np.array([0, 2, 4]), params=np.array([1, -2, 1])) sp = pp.to_spline() x = np.linspace(0, 1, 100) np.testing.assert_allclose(pp.compute(x), sp.compute(x), rtol=1e-5, atol=1e-3) pp1 = sp.to_powerseries(order=4) np.testing.assert_allclose(pp.params, pp1.params, rtol=1e-5, atol=1e-2)
mit
Python
22967375441f2a40c255cd2933f9cefb69129f8b
Remove JBluesBlackBody from the nlte_properties collection.
kaushik94/tardis,kaushik94/tardis,kaushik94/tardis,kaushik94/tardis
tardis/plasma/properties/property_collections.py
tardis/plasma/properties/property_collections.py
from tardis.plasma.properties import * class PlasmaPropertyCollection(list): pass basic_inputs = PlasmaPropertyCollection([TRadiative, Abundance, Density, TimeExplosion, AtomicData, DilutionFactor, LinkTRadTElectron, HeliumTreatment]) basic_properties = PlasmaPropertyCollection([BetaRadiation, Levels, Lines, AtomicMass, PartitionFunction, GElectron, IonizationData, NumberDensity, LinesLowerLevelIndex, LinesUpperLevelIndex, TauSobolev, StimulatedEmissionFactor, SelectedAtoms, ElectronTemperature]) lte_ionization_properties = PlasmaPropertyCollection([PhiSahaLTE]) lte_excitation_properties = PlasmaPropertyCollection([LevelBoltzmannFactorLTE]) macro_atom_properties = PlasmaPropertyCollection([BetaSobolev, TransitionProbabilities]) nebular_ionization_properties = PlasmaPropertyCollection([PhiSahaNebular, ZetaData, BetaElectron, RadiationFieldCorrection]) dilute_lte_excitation_properties = PlasmaPropertyCollection([ LevelBoltzmannFactorDiluteLTE]) non_nlte_properties = PlasmaPropertyCollection([LevelBoltzmannFactorNoNLTE]) nlte_properties = PlasmaPropertyCollection([ LevelBoltzmannFactorNLTE, NLTEData, PreviousElectronDensities, PreviousBetaSobolev, BetaSobolev]) helium_nlte_properties = PlasmaPropertyCollection([HeliumNLTE, RadiationFieldCorrection, ZetaData, BetaElectron, LevelNumberDensityHeNLTE, IonNumberDensityHeNLTE]) helium_lte_properties = PlasmaPropertyCollection([LevelNumberDensity, IonNumberDensity]) helium_numerical_nlte_properties = PlasmaPropertyCollection([ HeliumNumericalNLTE])
from tardis.plasma.properties import * class PlasmaPropertyCollection(list): pass basic_inputs = PlasmaPropertyCollection([TRadiative, Abundance, Density, TimeExplosion, AtomicData, DilutionFactor, LinkTRadTElectron, HeliumTreatment]) basic_properties = PlasmaPropertyCollection([BetaRadiation, Levels, Lines, AtomicMass, PartitionFunction, GElectron, IonizationData, NumberDensity, LinesLowerLevelIndex, LinesUpperLevelIndex, TauSobolev, StimulatedEmissionFactor, SelectedAtoms, ElectronTemperature]) lte_ionization_properties = PlasmaPropertyCollection([PhiSahaLTE]) lte_excitation_properties = PlasmaPropertyCollection([LevelBoltzmannFactorLTE]) macro_atom_properties = PlasmaPropertyCollection([BetaSobolev, TransitionProbabilities]) nebular_ionization_properties = PlasmaPropertyCollection([PhiSahaNebular, ZetaData, BetaElectron, RadiationFieldCorrection]) dilute_lte_excitation_properties = PlasmaPropertyCollection([ LevelBoltzmannFactorDiluteLTE]) non_nlte_properties = PlasmaPropertyCollection([LevelBoltzmannFactorNoNLTE]) nlte_properties = PlasmaPropertyCollection([ LevelBoltzmannFactorNLTE, NLTEData, JBluesBlackBody, PreviousElectronDensities, PreviousBetaSobolev, BetaSobolev]) helium_nlte_properties = PlasmaPropertyCollection([HeliumNLTE, RadiationFieldCorrection, ZetaData, BetaElectron, LevelNumberDensityHeNLTE, IonNumberDensityHeNLTE]) helium_lte_properties = PlasmaPropertyCollection([LevelNumberDensity, IonNumberDensity]) helium_numerical_nlte_properties = PlasmaPropertyCollection([ HeliumNumericalNLTE])
bsd-3-clause
Python
8642314ce091dc1e98811ba7aa12f1e66a4b1fb2
add create_test_person factory
openstates/openstates.org,openstates/openstates.org,openstates/openstates.org,openstates/openstates.org
testutils/factories.py
testutils/factories.py
import random from openstates.data.models import Organization, Bill, LegislativeSession, Person, Post def create_test_bill( session, chamber, *, sponsors=0, actions=0, votes=0, versions=0, documents=0, sources=0, subjects=None, identifier=None, ): chamber = Organization.objects.get(classification=chamber) session = LegislativeSession.objects.get(identifier=session) b = Bill.objects.create( identifier=identifier or ("Bill " + str(random.randint(1000, 9000))), title="Random Bill", legislative_session=session, from_organization=chamber, subject=subjects or [], ) for n in range(sponsors): b.sponsorships.create(name="Someone") for n in range(actions): b.actions.create( description="Something", order=n, organization=chamber, date="2020-06-01" ) for n in range(votes): b.votes.create( identifier="A Vote Occurred", organization=chamber, legislative_session=session, ) for n in range(versions): b.versions.create(note="Version") for n in range(documents): b.documents.create(note="Document") for n in range(sources): b.sources.create(url="http://example.com") return b def create_test_vote(bill, *, yes_count=0, no_count=0, yes_votes=None, no_votes=None): vote = bill.votes.create( identifier="test vote", organization=bill.from_organization, legislative_session=bill.legislative_session, ) vote.counts.create(option="yes", value=yes_count) vote.counts.create(option="no", value=no_count) for name in yes_votes or []: vote.votes.create(option="yes", voter_name=name) for name in no_votes or []: vote.votes.create(option="no", voter_name=name) def create_test_person(name, *, org, district, party): p = Person.objects.create( name=name, primary_party=party, current_jurisdiction=org.jurisdiction, current_role={ "org_classification": org.classification, "district": district, "division_id": "ocd-division/123", "title": "Title", }, ) post = Post.objects.create(organization=org, label=district) p.memberships.create(post=post, organization=org) party, _ = Organization.objects.get_or_create(name=party, classification="party") p.memberships.create(organization=party) return p
import random from openstates.data.models import Organization, Bill, LegislativeSession def create_test_bill( session, chamber, *, sponsors=0, actions=0, votes=0, versions=0, documents=0, sources=0, subjects=None, identifier=None, ): chamber = Organization.objects.get(classification=chamber) session = LegislativeSession.objects.get(identifier=session) b = Bill.objects.create( identifier=identifier or ("Bill " + str(random.randint(1000, 9000))), title="Random Bill", legislative_session=session, from_organization=chamber, subject=subjects or [], ) for n in range(sponsors): b.sponsorships.create(name="Someone") for n in range(actions): b.actions.create( description="Something", order=n, organization=chamber, date="2020-06-01" ) for n in range(votes): b.votes.create( identifier="A Vote Occurred", organization=chamber, legislative_session=session, ) for n in range(versions): b.versions.create(note="Version") for n in range(documents): b.documents.create(note="Document") for n in range(sources): b.sources.create(url="http://example.com") return b def create_test_vote(bill, *, yes_count=0, no_count=0, yes_votes=None, no_votes=None): vote = bill.votes.create( identifier="test vote", organization=bill.from_organization, legislative_session=bill.legislative_session, ) vote.counts.create(option="yes", value=yes_count) vote.counts.create(option="no", value=no_count) for name in yes_votes or []: vote.votes.create(option="yes", voter_name=name) for name in no_votes or []: vote.votes.create(option="no", voter_name=name)
mit
Python
381990dc85b273129135e815e1701586062bc34a
fix filename for linux
mozman/ezdxf,mozman/ezdxf,mozman/ezdxf,mozman/ezdxf,mozman/ezdxf
integration_tests/test_write_without_handles.py
integration_tests/test_write_without_handles.py
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import os import pytest import ezdxf from ezdxf.lldxf.tagger import ascii_tags_loader from ezdxf.lldxf.loader import load_dxf_structure BASEDIR = os.path.dirname(__file__) DATADIR = 'data' @pytest.fixture(params=["POLI-ALL210_12.DXF"]) def filename(request): filename = os.path.join(BASEDIR, DATADIR, request.param) if not os.path.exists(filename): pytest.skip(f'File {filename} not found.') return filename def test_check_R12_has_handles(filename): dwg = ezdxf.readfile(filename) assert dwg.header['$HANDLING'] > 0 for entity in dwg.modelspace(): assert int(entity.dxf.handle, 16) > 0 def test_write_R12_without_handles(filename, tmpdir): dwg = ezdxf.readfile(filename) dwg.header['$HANDLING'] = 0 export_path = str(tmpdir.join("dxf_r12_without_handles.dxf")) dwg.saveas(export_path) # can't check with ezdxf.readfile(), because handles automatically enabled with open(export_path) as f: tagger = ascii_tags_loader(f) sections = load_dxf_structure(tagger) for entity in sections['ENTITIES']: with pytest.raises(ezdxf.DXFValueError): # has no handles entity.get_handle() for entity in sections['TABLES']: if entity[0] != (0, 'DIMSTYLE'): with pytest.raises(ezdxf.DXFValueError): # has no handles entity.get_handle() else: # special DIMSTYLE entity assert len( entity.find_all(105)) == 0, 'remove handle group code 105' assert len( entity.find_all(5)) == 1, 'do not remove group code 5'
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import os import pytest import ezdxf from ezdxf.lldxf.tagger import ascii_tags_loader from ezdxf.lldxf.loader import load_dxf_structure BASEDIR = os.path.dirname(__file__) DATADIR = 'data' @pytest.fixture(params=["POLI-ALL210_12.dxf"]) def filename(request): filename = os.path.join(BASEDIR, DATADIR, request.param) if not os.path.exists(filename): pytest.skip(f'File {filename} not found.') return filename def test_check_R12_has_handles(filename): dwg = ezdxf.readfile(filename) assert dwg.header['$HANDLING'] > 0 for entity in dwg.modelspace(): assert int(entity.dxf.handle, 16) > 0 def test_write_R12_without_handles(filename, tmpdir): dwg = ezdxf.readfile(filename) dwg.header['$HANDLING'] = 0 export_path = str(tmpdir.join("dxf_r12_without_handles.dxf")) dwg.saveas(export_path) # can't check with ezdxf.readfile(), because handles automatically enabled with open(export_path) as f: tagger = ascii_tags_loader(f) sections = load_dxf_structure(tagger) for entity in sections['ENTITIES']: with pytest.raises(ezdxf.DXFValueError): # has no handles entity.get_handle() for entity in sections['TABLES']: if entity[0] != (0, 'DIMSTYLE'): with pytest.raises(ezdxf.DXFValueError): # has no handles entity.get_handle() else: # special DIMSTYLE entity assert len( entity.find_all(105)) == 0, 'remove handle group code 105' assert len( entity.find_all(5)) == 1, 'do not remove group code 5'
mit
Python
7b3672288a6089b7ce3bc10590988e020bb944e9
Remove unused import
bnoi/scikit-tracker,bnoi/scikit-tracker,bnoi/scikit-tracker
sktracker/io/tests/test_objectsio.py
sktracker/io/tests/test_objectsio.py
import os import tempfile from sktracker import data from sktracker.io import StackIO from sktracker.io import ObjectsIO from sktracker.detection import peak_detector from sktracker.io import validate_metadata def test_objectsio(): fname = data.CZT_peaks() st = StackIO(fname, json_discovery=False) data_iterator = st.image_iterator(channel_index=0) parameters = {'w_s': 0.7, 'peak_radius': 0.2, 'threshold': 27, 'max_peaks': 4 } peaks = peak_detector(data_iterator(), st.metadata, parallel=True, verbose=False, show_progress=True, parameters=parameters) oio = ObjectsIO(st.metadata, store_path="test.h5", base_dir=tempfile.gettempdir()) oio["detected"] = peaks assert (oio.keys() == ['/detected', '/metadata']) and (oio["detected"].shape == (28, 6)) def test_from_h5_without_base_dir(): store_path = data.sample_h5() oio = ObjectsIO.from_h5(store_path) assert validate_metadata(oio.metadata) def test_from_h5(): store_path = data.sample_h5() oio = ObjectsIO.from_h5(store_path, base_dir=tempfile.gettempdir()) assert validate_metadata(oio.metadata)
import os import tempfile from nose import with_setup from sktracker import data from sktracker.io import StackIO from sktracker.io import ObjectsIO from sktracker.detection import peak_detector from sktracker.io import validate_metadata def test_objectsio(): fname = data.CZT_peaks() st = StackIO(fname, json_discovery=False) data_iterator = st.image_iterator(channel_index=0) parameters = {'w_s': 0.7, 'peak_radius': 0.2, 'threshold': 27, 'max_peaks': 4 } peaks = peak_detector(data_iterator(), st.metadata, parallel=True, verbose=False, show_progress=True, parameters=parameters) oio = ObjectsIO(st.metadata, store_path="test.h5", base_dir=tempfile.gettempdir()) oio["detected"] = peaks assert (oio.keys() == ['/detected', '/metadata']) and (oio["detected"].shape == (28, 6)) def test_from_h5_without_base_dir(): store_path = data.sample_h5() oio = ObjectsIO.from_h5(store_path) assert validate_metadata(oio.metadata) def test_from_h5(): store_path = data.sample_h5() oio = ObjectsIO.from_h5(store_path, base_dir=tempfile.gettempdir()) assert validate_metadata(oio.metadata)
bsd-3-clause
Python
2574552efdca9322a3579cc814cc0e268688ce6d
add permission checkers
awau/Amethyst
utils/check.py
utils/check.py
import discord from discord.ext.commands import Context, check def owner(): """Check if caller is a bot owner""" def checker(ctx: Context): return ctx.author.id in ctx.bot.owners return check(checker) def guild(): """Check if called in a guild""" def checker(ctx: Context): return not ctx.is_dm() return check(checker) def roles(*roles: int): """Check if caller has all given roles""" def checker(ctx: Context): return not ctx.is_dm() and all([x.id in roles for x in ctx.author.roles]) return check(checker) def named_roles(*roles: str): """Check if caller has all given roles, checking by name""" def checker(ctx: Context): return not ctx.is_dm() and all([x.name in roles for x in ctx.author.roles]) return check(checker) def nsfw(): """Check if called in a NSFW channel""" def checker(ctx: Context): return isinstance(ctx.channel, discord.TextChannel) and ctx.channel.is_nsfw() return check(checker) class permissions: @staticmethod def author(permissions: discord.Permissions): """Check if caller has required permissions""" def checker(ctx: Context): return ( isinstance(ctx.author, discord.Member) and ctx.author.permissions_in(ctx.channel) >= permissions ) return check(checker) @staticmethod def me(permissions: discord.Permissions): """Check if bot has required permissions""" def checker(ctx: Context): return ( isinstance(ctx.me, discord.Member) and ctx.me.permissions_in(ctx.channel) >= permissions ) return check(checker)
import discord from discord.ext.commands import check def owner(): def checker(ctx): return ctx.message.author.id in ctx.bot.owners return check(checker) def guild(): def checker(ctx): return not ctx.is_dm() return check(checker) def roles(*roles: int): def checker(ctx): return not ctx.is_dm() and len( [x for x in ctx.message.author.roles if x.id in roles] ) == len(roles) return check(checker) def named_roles(*roles: str): def checker(ctx): return not ctx.is_dm() and all( [x.name in roles for x in ctx.message.author.roles] ) return check(checker) def nsfw(): def checker(ctx): return ( isinstance(ctx.message.channel, discord.TextChannel) and ctx.message.channel.is_nsfw() ) return check(checker)
mit
Python
a2f9ba16d6fa80c674b198921f463397f3d98131
simplify sort_function_weight using cmp()
BackupTheBerlios/pondus
src/pondus/gui/guiutil.py
src/pondus/gui/guiutil.py
#! /usr/bin/env python # -*- coding: UTF-8 -*- """ This file is part of Pondus, a personal weight manager. Copyright (C) 2007-08 Eike Nicklas <eike@ephys.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import gtk from pondus import parameters def sort_function_weight(listmodel, iter1, iter2, data): """Sorts the weight column correctly, i.e. interprets the weight data as floats instead of strings.""" weight1 = float(listmodel.get_value(iter1, 2)) weight2 = float(listmodel.get_value(iter2, 2)) return cmp(weight1, weight2) def register_icons(): """Adds custom icons to the list of stock IDs.""" icon_info = {'pondus_plot': parameters.plot_button_path} iconfactory = gtk.IconFactory() stock_ids = gtk.stock_list_ids() for stock_id in icon_info: # only load image files when our stock_id is not present if stock_id not in stock_ids: icon_file = icon_info[stock_id] pixbuf = gtk.gdk.pixbuf_new_from_file(icon_file) iconset = gtk.IconSet(pixbuf) iconfactory.add(stock_id, iconset) iconfactory.add_default()
#! /usr/bin/env python # -*- coding: UTF-8 -*- """ This file is part of Pondus, a personal weight manager. Copyright (C) 2007-08 Eike Nicklas <eike@ephys.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import gtk from pondus import parameters def sort_function_weight(listmodel, iter1, iter2, data): """Sorts the weight column correctly, i.e. interprets the weight data as floats instead of strings.""" weight1 = float(listmodel.get_value(iter1, 2)) weight2 = float(listmodel.get_value(iter2, 2)) if weight1 < weight2: return -1 elif weight1 == weight2: return 0 else: return 1 def register_icons(): """Adds custom icons to the list of stock IDs.""" icon_info = {'pondus_plot': parameters.plot_button_path} iconfactory = gtk.IconFactory() stock_ids = gtk.stock_list_ids() for stock_id in icon_info: # only load image files when our stock_id is not present if stock_id not in stock_ids: icon_file = icon_info[stock_id] pixbuf = gtk.gdk.pixbuf_new_from_file(icon_file) iconset = gtk.IconSet(pixbuf) iconfactory.add(stock_id, iconset) iconfactory.add_default()
mit
Python
833cdb4b6fb2890039c110a1b60d16c44d4d61dd
increase version to 1.4.6
SCIP-Interfaces/PySCIPOpt,mattmilten/PySCIPOpt,SCIP-Interfaces/PySCIPOpt,mattmilten/PySCIPOpt
src/pyscipopt/__init__.py
src/pyscipopt/__init__.py
__version__ = '1.4.6' # export user-relevant objects: from pyscipopt.Multidict import multidict from pyscipopt.scip import Model from pyscipopt.scip import Branchrule from pyscipopt.scip import Conshdlr from pyscipopt.scip import Eventhdlr from pyscipopt.scip import Heur from pyscipopt.scip import Presol from pyscipopt.scip import Pricer from pyscipopt.scip import Prop from pyscipopt.scip import Sepa from pyscipopt.scip import LP from pyscipopt.scip import quicksum from pyscipopt.scip import exp from pyscipopt.scip import log from pyscipopt.scip import sqrt from pyscipopt.scip import PY_SCIP_RESULT as SCIP_RESULT from pyscipopt.scip import PY_SCIP_PARAMSETTING as SCIP_PARAMSETTING from pyscipopt.scip import PY_SCIP_PARAMEMPHASIS as SCIP_PARAMEMPHASIS from pyscipopt.scip import PY_SCIP_STATUS as SCIP_STATUS from pyscipopt.scip import PY_SCIP_STAGE as SCIP_STAGE from pyscipopt.scip import PY_SCIP_PROPTIMING as SCIP_PROPTIMING from pyscipopt.scip import PY_SCIP_PRESOLTIMING as SCIP_PRESOLTIMING from pyscipopt.scip import PY_SCIP_HEURTIMING as SCIP_HEURTIMING from pyscipopt.scip import PY_SCIP_EVENTTYPE as SCIP_EVENTTYPE
__version__ = '1.4.5' # export user-relevant objects: from pyscipopt.Multidict import multidict from pyscipopt.scip import Model from pyscipopt.scip import Branchrule from pyscipopt.scip import Conshdlr from pyscipopt.scip import Eventhdlr from pyscipopt.scip import Heur from pyscipopt.scip import Presol from pyscipopt.scip import Pricer from pyscipopt.scip import Prop from pyscipopt.scip import Sepa from pyscipopt.scip import LP from pyscipopt.scip import quicksum from pyscipopt.scip import exp from pyscipopt.scip import log from pyscipopt.scip import sqrt from pyscipopt.scip import PY_SCIP_RESULT as SCIP_RESULT from pyscipopt.scip import PY_SCIP_PARAMSETTING as SCIP_PARAMSETTING from pyscipopt.scip import PY_SCIP_PARAMEMPHASIS as SCIP_PARAMEMPHASIS from pyscipopt.scip import PY_SCIP_STATUS as SCIP_STATUS from pyscipopt.scip import PY_SCIP_STAGE as SCIP_STAGE from pyscipopt.scip import PY_SCIP_PROPTIMING as SCIP_PROPTIMING from pyscipopt.scip import PY_SCIP_PRESOLTIMING as SCIP_PRESOLTIMING from pyscipopt.scip import PY_SCIP_HEURTIMING as SCIP_HEURTIMING from pyscipopt.scip import PY_SCIP_EVENTTYPE as SCIP_EVENTTYPE
mit
Python
680a156dd2b1e34e45784482663af7b8ed47c2ab
Make our linter happy.
alephdata/ingestors
ingestors/__init__.py
ingestors/__init__.py
"""Provides a set of ingestors based on different file types.""" from .doc import DocumentIngestor # noqa from .html import HTMLIngestor # noqa from .image import ImageIngestor # noqa from .pdf import PDFIngestor # noqa from .tabular import TabularIngestor # noqa from .text import TextIngestor # noqa __version__ = '0.1.0' def ingest(fio, file_path): """Simple wrapper to run ingestors on a file. :param fio: An instance of the file to process. :type fio: py:class:`io.FileIO` :param file_path: The file path. :type file_path: str :return: Tuple, the ingestor object, its data and detached ingestors data. :rtype: tuple """ ingestor_class, mime_type = TextIngestor.match(fio) if not ingestor_class: return None, None, None ingestor = ingestor_class(fio, file_path, mime_type=mime_type) ingestor.run() detached_data = map(lambda c: c.result, getattr(ingestor, 'detached', [])) return ingestor, ingestor.result, detached_data
"""Provides a set of ingestors based on different file types.""" from .doc import DocumentIngestor # noqa from .html import HTMLIngestor # noqa from .image import ImageIngestor # noqa from .pdf import PDFIngestor # noqa from .tabular import TabularIngestor # noqa from .text import TextIngestor # noqa __version__ = '0.1.0' def ingest(fio, file_path): """Simple wrapper to run ingestors on a file. :param fio: An instance of the file to process. :type fio: py:class:`io.FileIO` :param file_path: The file path. :type file_path: str :return: A tuple, the ingestor object, its data and detached ingestors data. :rtype: tuple """ ingestor_class, mime_type = TextIngestor.match(fio) if not ingestor_class: return None, None, None ingestor = ingestor_class(fio, file_path, mime_type=mime_type) ingestor.run() detached_data = map(lambda c: c.result, getattr(ingestor, 'detached', [])) return ingestor, ingestor.result, detached_data
mit
Python
0425ea0c496bea2779c2b375404534e1fdd05d44
Update version to 2.10dev
StackStorm/mistral,StackStorm/mistral
version_st2.py
version_st2.py
# Copyright 2016 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = '2.10dev'
# Copyright 2016 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = '3.0dev'
apache-2.0
Python
002bd3b2208759db28d9be00e0ad80019e330971
Add admin users auth to core/person api
desenho-sw-g5/service_control,desenho-sw-g5/service_control
core/views/api_person_views.py
core/views/api_person_views.py
from rest_framework.views import APIView from rest_framework.views import Response from rest_framework.views import Request from rest_framework import status from rest_framework import authentication, permissions from django.shortcuts import get_object_or_404 from core.models import Person from core.serializers import PersonSerializer class PersonList(APIView): """ List people or create a new person GET /person -> list people POST /person -> create a new cart person * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request: Request) -> Response: people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data) def post(self, request: Request) -> Response: serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PersonDetail(APIView): """ Retrieve, update or delete a Person instance. GET /person/:id -> Get a person instance PUT /person/:id -> Updates a person instance DELETE /person/:id -> Deletes a person instance * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) serializer = PersonSerializer(person) return Response(serializer.data) def put(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) serializer = PersonSerializer(person, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) person.delete() return Response(status=status.HTTP_204_NO_CONTENT)
from rest_framework.views import APIView from rest_framework.views import Response from rest_framework.views import Request from rest_framework import status from django.shortcuts import get_object_or_404 from core.models import Person from core.serializers import PersonSerializer class PersonList(APIView): """ List people or create a new person GET /person -> list people POST /person -> create a new cart person """ def get(self, request: Request) -> Response: people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data) def post(self, request: Request) -> Response: serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PersonDetail(APIView): """ Retrieve, update or delete a Person instance. GET /person/:id -> Get a person instance PUT /person/:id -> Updates a person instance DELETE /person/:id -> Deletes a person instance """ def get(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) serializer = PersonSerializer(person) return Response(serializer.data) def put(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) serializer = PersonSerializer(person, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request: Request, pk: int) -> Response: person = get_object_or_404(Person, pk=pk) person.delete() return Response(status=status.HTTP_204_NO_CONTENT)
mit
Python
dc5581f8ee34d38cb570812cc203ee9975f083ff
Fix flake8 issues.
michaelaye/vispy,sbtlaarzc/vispy,jdreaver/vispy,inclement/vispy,sh4wn/vispy,RebeccaWPerry/vispy,jay3sh/vispy,QuLogic/vispy,jdreaver/vispy,kkuunnddaannkk/vispy,sh4wn/vispy,srinathv/vispy,sbtlaarzc/vispy,michaelaye/vispy,jdreaver/vispy,julienr/vispy,drufat/vispy,bollu/vispy,Eric89GXL/vispy,jay3sh/vispy,Eric89GXL/vispy,ghisvail/vispy,hronoses/vispy,dchilds7/Deysha-Star-Formation,Eric89GXL/vispy,hronoses/vispy,bollu/vispy,sh4wn/vispy,RebeccaWPerry/vispy,RebeccaWPerry/vispy,jay3sh/vispy,kkuunnddaannkk/vispy,QuLogic/vispy,hronoses/vispy,inclement/vispy,drufat/vispy,QuLogic/vispy,bollu/vispy,drufat/vispy,ghisvail/vispy,srinathv/vispy,julienr/vispy,kkuunnddaannkk/vispy,inclement/vispy,michaelaye/vispy,srinathv/vispy,ghisvail/vispy,sbtlaarzc/vispy,julienr/vispy,dchilds7/Deysha-Star-Formation,dchilds7/Deysha-Star-Formation
vispy/geometry/__init__.py
vispy/geometry/__init__.py
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ This module implements classes and methods for handling geometric data. """ from __future__ import division __all__ = ['MeshData', 'PolygonData', 'Rect', 'Triangulation', 'triangulate', 'create_arrow', 'create_cone', 'create_cube', 'create_cylinder', 'create_sphere', 'resize'] from .polygon import PolygonData # noqa from .meshdata import MeshData # noqa from .rect import Rect # noqa from .triangulation import Triangulation, triangulate # noqa from .torusknot import TorusKnot # noqa from .calculations import (_calculate_normals, _fast_cross_3d, # noqa resize) # noqa from .generation import (create_arrow, create_box, create_cone, # noqa create_cube, create_cylinder, create_plane, # noqa create_sphere) # noqa
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ This module implements classes and methods for handling geometric data. """ from __future__ import division __all__ = ['MeshData', 'PolygonData', 'Rect', 'Triangulation', 'triangulate', 'create_arrow', 'create_cone', 'create_cube', 'create_cylinder', 'create_sphere', 'resize'] from .polygon import PolygonData # noqa from .meshdata import MeshData # noqa from .rect import Rect # noqa from .triangulation import Triangulation, triangulate # noqa from .torusknot import TorusKnot # noqa from .calculations import (_calculate_normals, _fast_cross_3d, # noqa resize) # noqa from .generation import create_arrow, create_box, create_cone, create_cube, \ create_cylinder, create_plane, create_sphere # noqa
bsd-3-clause
Python
86d60cdfa4136a1d748120d5b764e64f70af7e5a
bump version
ramusus/django-vkontakte-wall
vkontakte_wall/__init__.py
vkontakte_wall/__init__.py
VERSION = (0, 5, 10) __version__ = '.'.join(map(str, VERSION))
VERSION = (0, 5, 9) __version__ = '.'.join(map(str, VERSION))
bsd-3-clause
Python
890a42bdf7f54b5907f7cc39832ea9f07fa18569
Update list of key changes with version in __init__.py
wf4ever/ro-manager,wf4ever/ro-manager,wf4ever/ro-manager,wf4ever/ro-manager
src/rocommand/__init__.py
src/rocommand/__init__.py
# __init__.py #__version__ = "0.2.1" # Initial version with installation package #__version__ = "0.2.2" # Updated README documentation for PyPI page #__version__ = "0.2.3" # Experimenting with distribution options #__version__ = "0.2.4" # Added MANIFEST.in so that data files are part of sdist #__version__ = "0.2.5" # Drop references to lpod-show from test suite #__version__ = "0.2.6" # Enhacements to handling of directories and external references #__version__ = "0.2.7" # Decouple MINIM constraints from target RO # ROSRS (v6) support, support evaluation of RODL/ROSRS objects # new annotation and linking options, # annotations with CURIE (QName) properties # add ro remove command, fix URI escaping problems #__version__ = "0.2.8" # Optimize annotation access in ROSRS_Session # Add web services for rendering traffic light displays #__version__ = "0.2.9" # Fix up experiment-workflow checklist __version__ = "0.2.10" # Fix problem evaluating RO with space in URI # RDFReport add escaping support; escape quotes in JSON strings # Fix problem with URI liveness test # New RO must have ore:Aggregation class # Allow reporting of missing <forall> entries # Add ro dump command # Ordering of checklist display # Various display formatting enhancements
# __init__.py #__version__ = "0.2.1" # Initial version with installation package #__version__ = "0.2.2" # Updated README documentation for PyPI page #__version__ = "0.2.3" # Experimenting with distribution options #__version__ = "0.2.4" # Added MANIFEST.in so that data files are part of sdist #__version__ = "0.2.5" # Drop references to lpod-show from test suite #__version__ = "0.2.6" # Enhacements to handling of directories and external references #__version__ = "0.2.7" # Decouple MINIM constraints from target RO # ROSRS (v6) support, support evaluation of RODL/ROSRS objects # new annotation and linking options, # annotations with CURIE (QName) properties # add ro remove command, fix URI escaping problems #__version__ = "0.2.8" # Optimize annotation access in ROSRS_Session # Add web services for renderinmg traffic light displays #__version__ = "0.2.9" # Fix up experiment-workflow checklist __version__ = "0.2.10" # ??
mit
Python
60870a3e471637d44da32f3aac74064e4ca60208
Use `set_defaults` of subparser to launch scripts
DerWeh/pyplot
pyplot.py
pyplot.py
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts', dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() args.run(args)
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts' ) module_subparser = {} for module_str in plotter.__all__: module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() from plotter.plotn import main main(args)
mit
Python
51aae21ce211abc9897b989c233f22507813ecf2
Add a pondmen column
benjello/openfisca-france-indirect-taxation,antoinearnoud/openfisca-france-indirect-taxation,thomasdouenne/openfisca-france-indirect-taxation,openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/model/input_variables.py
openfisca_france_indirect_taxation/model/input_variables.py
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # OpenFisca is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from openfisca_core.columns import DateCol, FloatCol, IntCol, reference_input_variable from ..entities import Individus, Menages reference_input_variable( column = DateCol, entity_class = Individus, is_permanent = True, label = "Date de naissance", name = 'birth', ) reference_input_variable( column = IntCol, entity_class = Individus, is_permanent = True, label = u"Identifiant du ménage", name = 'ident_men', ) reference_input_variable( column = IntCol, entity_class = Individus, is_permanent = True, label = u"Rôle dans le ménage", name = 'quimen', ) reference_input_variable( column = IntCol, entity_class = Menages, is_permanent = True, label = u"Pondération du ménage", name = 'pondmen', ) reference_input_variable( column = FloatCol, entity_class = Individus, label = "Salaire brut", name = 'salaire_brut', )
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # OpenFisca is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from openfisca_core.columns import DateCol, FloatCol, IntCol, reference_input_variable from ..entities import Individus reference_input_variable( column = DateCol, entity_class = Individus, is_permanent = True, label = "Date de naissance", name = 'birth', ) reference_input_variable( column = IntCol, entity_class = Individus, is_permanent = True, label = u"Identifiant du ménage", name = 'idmen', ) reference_input_variable( column = IntCol, entity_class = Individus, is_permanent = True, label = u"Rôle dans le ménage", name = 'quimen', ) reference_input_variable( column = FloatCol, entity_class = Individus, label = "Salaire brut", name = 'salaire_brut', )
agpl-3.0
Python
f7a6aa0434a13df6806bdedb885756d6179220db
fix course lesson 3 data prep test
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
tests/course/tests/lesson_3_data_prepare_test.py
tests/course/tests/lesson_3_data_prepare_test.py
# third party import pytest from testbook import testbook @pytest.fixture(scope="module") def tb(): with testbook("../courses/L3_DataPreparation.ipynb", execute=True) as tb: yield tb def test_data_acquisition(tb): assert tb.cell_output_text(8) == "(2280, 451)" def test_quality_check(tb): assert tb.cell_output_text(21) == "53" assert tb.cell_output_text(24) == "129" def test_data_and_pygrid(tb): assert ( "raw_data is of type: <class 'pandas.core.frame.DataFrame'>\nraw_data is of type: <class 'numpy.ndarray'>" in tb.cell_output_text(31) ) assert ( "test_data is of type: <class 'torch.Tensor'>\ntest_data is of type: <class 'numpy.ndarray'>" in tb.cell_output_text(32) ) assert ( "random_data is of dtype: float64\nrandom_data is now of type: int32" in tb.cell_output_text(36) ) def test_loading_data_to_pygrid(tb): sy = tb.ref("sy") assert sy.__version__ is not None domain_node = tb.ref("domain_node") # Check if the domain node was initialized assert domain_node is not None # Data was uploaded successfully assert tb.cell_output_text(43) is not None # Check if dataset is initialized assert domain_node.datasets is not None # Viewing the dataset assert tb.cell_output_text(46) is not None
# third party import pytest from testbook import testbook @pytest.fixture(scope="module") def tb(): with testbook("../courses/L3_DataPreparation.ipynb", execute=True) as tb: yield tb def test_data_acquisition(tb): assert tb.cell_output_text(8) == "(2280, 451)" def test_quality_check(tb): assert tb.cell_output_text(21) == "53" assert tb.cell_output_text(24) == "129" def test_data_and_pygrid(tb): assert ( tb.cell_output_text(31) == "raw_data is of type: <class 'pandas.core.frame.DataFrame'>\nraw_data is of type: <class 'numpy.ndarray'>" ) assert ( tb.cell_output_text(32) == "test_data is of type: <class 'torch.Tensor'>\ntest_data is of type: <class 'numpy.ndarray'>" ) assert ( tb.cell_output_text(36) == "random_data is of dtype: float64\nrandom_data is now of type: int32" ) def test_loading_data_to_pygrid(tb): sy = tb.ref("sy") assert sy.__version__ is not None domain_node = tb.ref("domain_node") # Check if the domain node was initialized assert domain_node is not None # Data was uploaded successfully assert tb.cell_output_text(43) is not None # Check if dataset is initialized assert domain_node.datasets is not None # Viewing the dataset assert tb.cell_output_text(46) is not None
apache-2.0
Python
fb5c92741243756516fa50073d34e94ba0b6981e
Generalize projection-matrix-removal script (#3430)
facebookresearch/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI
projects/anti_scaling/scripts/remove_projection_matrices.py
projects/anti_scaling/scripts/remove_projection_matrices.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import torch from parlai.utils import pickle from parlai.utils.io import PathManager from parlai.utils.torch import atomic_save def remove_projection_matrices(model_file: str): """ Remove all projection matrices used for distillation from the model and re-save it. """ print(f'Creating a backup copy of the original model at {model_file}._orig.') PathManager.copy(model_file, f'{model_file}._orig') print(f"Loading {model_file}.") with PathManager.open(model_file, 'rb') as f: states = torch.load(f, map_location=lambda cpu, _: cpu, pickle_module=pickle) print('Deleting projection matrices.') orig_num_keys = len(states['model']) states['model'] = { key: val for key, val in states['model'].items() if key.split('.')[0] not in ['encoder_proj_layer', 'embedding_proj_layers', 'hidden_proj_layers'] } new_num_keys = len(states['model']) print(f'{orig_num_keys-new_num_keys:d} model keys removed.') print(f"Saving to {model_file}.") atomic_save(states, model_file) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'model_file', type=str, help='Path to model to remove projection matrices from' ) args = parser.parse_args() remove_projection_matrices(args.model_file)
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import shutil import torch from parlai.utils import pickle from parlai.utils.io import PathManager from parlai.utils.torch import atomic_save def remove_projection_matrices(model_file: str): """ Remove all projection matrices used for distillation from the model and re-save it. """ print(f'Creating a backup copy of the original model at {model_file}.') shutil.copyfile(model_file, f'{model_file}._orig') print(f"Loading {model_file}.") with PathManager.open(model_file, 'rb') as f: states = torch.load(f, map_location=lambda cpu, _: cpu, pickle_module=pickle) print('Deleting projection matrices.') orig_num_keys = len(states['model']) states['model'] = { key: val for key, val in states['model'].items() if key.split('.')[0] not in ['encoder_proj_layer', 'embedding_proj_layers', 'hidden_proj_layers'] } new_num_keys = len(states['model']) print(f'{orig_num_keys-new_num_keys:d} model keys removed.') print(f"Saving to {model_file}.") atomic_save(states, model_file) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'model_file', type=str, help='Path to model to remove projection matrices from' ) args = parser.parse_args() remove_projection_matrices(args.model_file)
mit
Python
e81e2c30c756f224ce6a861b96c3c51d0ca60993
Add url validation util
strycore/megascops,strycore/megascops,strycore/megascops,strycore/megascops
video/utils.py
video/utils.py
import os import uuid import urllib from urlparse import urlparse import subprocess from django.conf import settings from video.models import Video def sanitize_url(url): """ Make sure an url is valid, prepending the scheme if needed. """ parsed = urlparse(url) if not parsed.scheme: url = "http://" + url parsed = urlparse(url) if not parsed.scheme: raise ValueError("Invalid url %s" % url) return url def download_thumbnail(thumbnail_url): destination_path = os.path.join(settings.MEDIA_ROOT, 'thumbnails') thumbnail_file = str(uuid.uuid4()) + ".jpg" urllib.urlretrieve(thumbnail_url, os.path.join(destination_path, thumbnail_file)) thumb_rel_path = os.path.join('thumbnails', thumbnail_file) return thumb_rel_path def encode_videos(video): path_format = "%s/video/%s.%s" orig_file = path_format % (settings.MEDIA_ROOT, video.filename, video.file_suffix) mp4_file = path_format % (settings.MEDIA_ROOT, video.filename, "mp4") webm_file = path_format % (settings.MEDIA_ROOT, video.filename, "webm") if orig_file != webm_file: launch_encoder(orig_file, webm_file) if orig_file != mp4_file: launch_encoder(orig_file, mp4_file) def launch_encoder(input_file, output_file, codec="", options=""): cmd = "avconv -i %(input)s %(codec)s %(options)s %(output)s" if os.path.exists(output_file): os.remove(output_file) params = {"input": input_file, "output": output_file, "codec": codec, "options": options} subprocess.Popen(cmd % params, shell=True).communicate() # pylint: disable=R0903 class VideoDownloader(object): def __init__(self, video_id): self.video_id = video_id self.video = Video.objects.get(pk=video_id) def _download_monitor(self, piece, block_size, total_size): bytes_downloaded = piece * block_size if total_size: progress = bytes_downloaded / (total_size * 1.0) else: progress = 0 #print "%d / %d " % (bytes_downloaded, total_size) if piece % 100 == 0: self.video.progress = progress * 100 self.video.save() def download(self, url, dest_path): urllib.urlretrieve(url, dest_path, self._download_monitor)
import os import uuid import urllib import subprocess from django.conf import settings from video.models import Video def download_thumbnail(thumbnail_url): destination_path = os.path.join(settings.MEDIA_ROOT, 'thumbnails') thumbnail_file = str(uuid.uuid4()) + ".jpg" urllib.urlretrieve(thumbnail_url, os.path.join(destination_path, thumbnail_file)) thumb_rel_path = os.path.join('thumbnails', thumbnail_file) return thumb_rel_path def encode_videos(video): path_format = "%s/video/%s.%s" orig_file = path_format % (settings.MEDIA_ROOT, video.filename, video.file_suffix) mp4_file = path_format % (settings.MEDIA_ROOT, video.filename, "mp4") webm_file = path_format % (settings.MEDIA_ROOT, video.filename, "webm") if orig_file != webm_file: launch_encoder(orig_file, webm_file) if orig_file != mp4_file: launch_encoder(orig_file, mp4_file) def launch_encoder(input_file, output_file, codec="", options=""): cmd = "avconv -i %(input)s %(codec)s %(options)s %(output)s" if os.path.exists(output_file): os.remove(output_file) params = {"input": input_file, "output": output_file, "codec": codec, "options": options} subprocess.Popen(cmd % params, shell=True).communicate() # pylint: disable=R0903 class VideoDownloader(object): def __init__(self, video_id): self.video_id = video_id self.video = Video.objects.get(pk=video_id) def _download_monitor(self, piece, block_size, total_size): bytes_downloaded = piece * block_size if total_size: progress = bytes_downloaded / (total_size * 1.0) else: progress = 0 #print "%d / %d " % (bytes_downloaded, total_size) if piece % 100 == 0: self.video.progress = progress * 100 self.video.save() def download(self, url, dest_path): urllib.urlretrieve(url, dest_path, self._download_monitor)
agpl-3.0
Python
1088c960ab450e70d6295d04d916a63a6f87dee7
add local feh dist
jobovy/apogee
apogee/util/__init__.py
apogee/util/__init__.py
import numpy def localfehdist(feh): #From 2 Gaussian XD fit to Casagrande et al. (2011) fehdist= 0.8/0.15*numpy.exp(-0.5*(feh-0.016)**2./0.15**2.)\ +0.2/0.22*numpy.exp(-0.5*(feh+0.15)**2./0.22**2.) return fehdist
bsd-3-clause
Python
c39fd90e9b14e5c7be13be1301c2a68a1fa55158
create the logs directory if it doesn't exist
StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit
cs251tk/lib/save_recordings.py
cs251tk/lib/save_recordings.py
from .format_collected_data import format_collected_data from .helpers import warn, flatten, group_by import yaml from .columnize import asciiify from .gist import post_gist import os def record_recording_to_disk(results, file_identifier): results = sorted(results, key=lambda file: file['student']) results = [file['content'] for file in results] output = '\n'.join(results) try: os.makedirs('logs', exists_ok=True) with open('logs/log-{}.md'.format(file_identifier), 'w', encoding='utf-8') as outfile: outfile.write(output) except Exception as err: warn('error! could not write recording:', err) def send_recording_to_gist(table, results, assignment): # the - at the front is so that github sees it first and names the gist # after the homework table_filename = '-cs251 report %s table.txt' % assignment files = { table_filename: {'content': table}, } for file in results: filename = file['student'] + '.' + file['type'] files[filename] = { 'content': file['content'].strip() } return post_gist('log for ' + assignment, files) def save_recordings(records, table, destination='file', debug=False): # clean up the table and make it plain ascii table = asciiify(table) results = {} records = list(flatten(records)) grouped_records = group_by(records, lambda rec: rec.get('spec', None)) for assignment, recordings in grouped_records: for content in recordings: if debug: formatted = '---\n' + yaml.safe_dump(content, default_flow_style=False) else: formatted = format_collected_data(content, destination == 'gist') if assignment not in results: results[assignment] = [] results[assignment].append({ 'content': formatted, 'student': content['student'], 'type': 'yaml' if debug else 'md', }) for assignment, content in results.items(): if destination == 'file': record_recording_to_disk(content, assignment) elif destination == 'gist': url = send_recording_to_gist(table, content, assignment) print(assignment, 'results are available at', url)
from .format_collected_data import format_collected_data from .helpers import warn, flatten, group_by import yaml from .columnize import asciiify from .gist import post_gist def record_recording_to_disk(results, file_identifier): results = sorted(results, key=lambda file: file['student']) results = [file['content'] for file in results] output = '\n'.join(results) try: with open('logs/log-{}.md'.format(file_identifier), 'w', encoding='utf-8') as outfile: outfile.write(output) except Exception as err: warn('error! could not write recording:', err) def send_recording_to_gist(table, results, assignment): # the - at the front is so that github sees it first and names the gist # after the homework table_filename = '-cs251 report %s table.txt' % assignment files = { table_filename: {'content': table}, } for file in results: filename = file['student'] + '.' + file['type'] files[filename] = { 'content': file['content'].strip() } return post_gist('log for ' + assignment, files) def save_recordings(records, table, destination='file', debug=False): # clean up the table and make it plain ascii table = asciiify(table) results = {} records = list(flatten(records)) grouped_records = group_by(records, lambda rec: rec.get('spec', None)) for assignment, recordings in grouped_records: for content in recordings: if debug: formatted = '---\n' + yaml.safe_dump(content, default_flow_style=False) else: formatted = format_collected_data(content, destination == 'gist') if assignment not in results: results[assignment] = [] results[assignment].append({ 'content': formatted, 'student': content['student'], 'type': 'yaml' if debug else 'md', }) for assignment, content in results.items(): if destination == 'file': record_recording_to_disk(content, assignment) elif destination == 'gist': url = send_recording_to_gist(table, content, assignment) print(assignment, 'results are available at', url)
mit
Python
1ba015fb4f9dd188d2ef32fd55c369f2e79d9547
Add short season mail list aliases
jluttine/django-sportsteam,jluttine/django-sportsteam,jluttine/django-sportsteam,jluttine/django-sportsteam
tuhlaajapojat_lists.py
tuhlaajapojat_lists.py
import os import re import sys #cmd_folder = '/home/jluttine' cmd_folder = '/home/jluttine/tuhlaajapojat' if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sportsteam.settings") #os.environ['DJANGO_SETTINGS_MODULE'] = 'sportsteam.settings' from teamstats.models import * def get_addresses(list): print 'Trying to match a list: ' + list # Some aliases :) if list.lower() == 'vuokravaioma': list = 'jaakko.luttinen' # Try if for everyone if list.lower() == 'tuhlaajapojat': players = Player.objects.all() emails = [player.email for player in players if player.email] emails = filter(None, emails) return emails, '[Tuhlaajapojat] ' # Check short aliases for most recent seasons of leagues # (e.g., 'hakid'->'HaKiD 2015' if 2015 is the latest season of HaKiD). try: season = Season.objects.filter(league__id__iexact=list).order_by('-year')[0] except Season.DoesNotExist: # Try matching to full season IDs try: season = Season.objects.get(id__iexact=list) except Season.DoesNotExist: season = None if season is not None: print('Matched season:', season) players = SeasonPlayer.objects.filter(season__id=season.id,passive=False) emails = [player.player.email for player in players] emails = filter(None, emails) return emails, '[Tuhlaajapojat-' + unicode(season.league) + '] ' else: print('Did not match any season') # Try matching to player IDs try: player = Player.objects.get(id__iexact=list) except Player.DoesNotExist: pass else: return [player.email], '' print 'Did not find recipients for %s' % list # No match return None, ''
import os import re import sys #cmd_folder = '/home/jluttine' cmd_folder = '/home/jluttine/tuhlaajapojat' if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sportsteam.settings") #os.environ['DJANGO_SETTINGS_MODULE'] = 'sportsteam.settings' from teamstats.models import * def get_addresses(list): print 'Trying to match a list: ' + list # Some aliases :) if list.lower() == 'vuokravaioma': list = 'jaakko.luttinen' # Try if for everyone if list.lower() == 'tuhlaajapojat': players = Player.objects.all() emails = [player.email for player in players if player.email] emails = filter(None, emails) return emails, '[Tuhlaajapojat] ' # Check team aliases if list.lower() == 'adidas': list = 'adidas2014' if list.lower() == 'fmhd': list = 'fmhd2012' if list.lower() == 'fmhm': list = 'fmhm2014' if list.lower() == 'esport': list = 'esport2014' if list.lower() == 'haku2': list = 'haku22013' if list.lower() == 'hakud': list = 'hakud2014' if list.lower() == 'hakid': list = 'hakid2015' if list.lower() == 'hakim': list = 'hakim2013' if list.lower() == 'srksm': list = 'srksm2014' # Try matching to season IDs try: season = Season.objects.get(id__iexact=list) except Season.DoesNotExist: pass else: players = SeasonPlayer.objects.filter(season__id=season.id,passive=False) emails = [player.player.email for player in players] emails = filter(None, emails) return emails, '[Tuhlaajapojat-' + unicode(season.league) + '] ' # Try matching to player IDs try: player = Player.objects.get(id__iexact=list) except Player.DoesNotExist: pass else: return [player.email], '' print 'Did not find recipients for %s' % list # No match return None, ''
agpl-3.0
Python
32c671fc59243a7a0b8b665369b5c06aaeb207af
Fix include paths in breakpad_client.gyp to make the build work
tomgr/google-breakpad,tomgr/google-breakpad,tomgr/google-breakpad,tomgr/google-breakpad,tomgr/google-breakpad
src/client/windows/breakpad_client.gyp
src/client/windows/breakpad_client.gyp
# Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS # "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 COPYRIGHT # OWNER OR CONTRIBUTORS 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. { 'includes': [ 'build/common.gypi', ], 'targets': [ { 'target_name': 'build_all', 'type': 'none', 'dependencies': [ './crash_generation/crash_generation.gyp:*', './handler/exception_handler.gyp:*', './sender/crash_report_sender.gyp:*', './unittests/client_tests.gyp:*', './unittests/gtest.gyp:*', ] }, { 'target_name': 'common', 'type': 'static_library', 'include_dirs': [ '<(DEPTH)', '<(DEPTH)/third_party/glog/glog/src/windows/', ], 'direct_dependent_settings': { 'include_dirs': [ '<(DEPTH)', ] }, 'sources': [ '<(DEPTH)/common/windows/guid_string.cc', '<(DEPTH)/common/windows/guid_string.h', '<(DEPTH)/common/windows/http_upload.cc', '<(DEPTH)/common/windows/http_upload.h', ] } ] }
# Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS # "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 COPYRIGHT # OWNER OR CONTRIBUTORS 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. { 'includes': [ 'build/common.gypi', ], 'targets': [ { 'target_name': 'build_all', 'type': 'none', 'dependencies': [ './crash_generation/crash_generation.gyp:*', './handler/exception_handler.gyp:*', './sender/crash_report_sender.gyp:*', './unittests/client_tests.gyp:*', './unittests/gtest.gyp:*', ] }, { 'target_name': 'common', 'type': 'static_library', 'include_dirs': [ '<(DEPTH)', ], 'direct_dependent_settings': { 'include_dirs': [ '<(DEPTH)', ] }, 'sources': [ '<(DEPTH)/common/windows/guid_string.cc', '<(DEPTH)/common/windows/guid_string.h', '<(DEPTH)/common/windows/http_upload.cc', '<(DEPTH)/common/windows/http_upload.h', ] } ] }
bsd-3-clause
Python
aac598d64fc0fa50cc068fc50173068e5d89b3fd
Update numpy dtypes extension for correct type codes.
hohogpb/segpy,stevejpurves/segpy,abingham/segpy,asbjorn/segpy,kjellkongsvik/segpy,Kramer477/segpy,kwinkunks/segpy
segpy/ext/numpyext.py
segpy/ext/numpyext.py
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'int32': numpy.dtype('i4'), 'int16': numpy.dtype('i2'), 'float32': numpy.dtype('f4'), 'int8': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
"""Optional interoperability with Numpy.""" import numpy NUMPY_DTYPES = {'ibm': numpy.dtype('f4'), 'l': numpy.dtype('i4'), 'h': numpy.dtype('i2'), 'f': numpy.dtype('f4'), 'b': numpy.dtype('i1')} def make_dtype(data_sample_format): """Convert a SEG Y data sample format to a compatible numpy dtype. Note : IBM float data sample formats ('ibm') will correspond to IEEE float data types. Args: data_sample_format: A data sample format string. Returns: A numpy.dtype instance. Raises: ValueError: For unrecognised data sample format strings. """ try: return NUMPY_DTYPES[data_sample_format] except KeyError: raise ValueError("Unknown data sample format string {!r}".format(data_sample_format))
agpl-3.0
Python
a799c25f8ecbc841129d0e34e84c6f95531668c5
Fix a misspelled variable
khchine5/django-shop,jrief/django-shop,awesto/django-shop,khchine5/django-shop,jrief/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,nimbis/django-shop,nimbis/django-shop,nimbis/django-shop,divio/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,awesto/django-shop,khchine5/django-shop
shop/models/fields.py
shop/models/fields.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import connection POSTGRES_FLAG = False if str(connection.vendor) == 'postgresql': POSTGRES_FLAG = True try: if POSTGRES_FLAG: from django.contrib.postgres.fields import JSONField else: raise ImportError except ImportError: from jsonfield.fields import JSONField class JSONFieldWrapper(JSONField): def __init__(self, *args, **kwargs): kwargs.update({'default': {}}) super(JSONFieldWrapper, self).__init__(*args, **kwargs)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import connection POSTGRES_FALG = False if str(connection.vendor) == 'postgresql': POSTGRES_FALG = True try: if POSTGRES_FALG: from django.contrib.postgres.fields import JSONField else: raise ImportError except ImportError: from jsonfield.fields import JSONField class JSONFieldWrapper(JSONField): def __init__(self, *args, **kwargs): kwargs.update({'default': {}}) super(JSONFieldWrapper, self).__init__(*args, **kwargs)
bsd-3-clause
Python
9c4425e5cff3d841f6e1120cbb244d7e322d6a96
fix admin.py field eroor
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
src/proposals/admin.py
src/proposals/admin.py
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): model = AdditionalSpeaker fields = ['user', 'status', 'cancelled'] ct_field = 'proposal_type' ct_fk_field = 'proposal_id' extra = 0 class ProposalAdmin(admin.ModelAdmin): list_display = [ 'title', 'category', 'duration', 'language', 'python_level', 'remoting_policy', 'accepted', ] list_filter = [ 'cancelled', 'accepted', 'category', 'duration', 'language', 'python_level', ] fields = [ 'conference', 'submitter', 'title', 'category', 'duration', 'language', 'abstract', 'python_level', 'objective', 'detailed_description', 'outline', 'supplementary', 'recording_policy', 'slide_link', 'referring_policy', 'remoting_policy', 'cancelled', 'accepted', 'slido_embed_link', ] raw_id_fields = ['submitter'] search_fields = ['title', 'abstract'] inlines = [AdditionalSpeakerInline] @admin.register(TalkProposal) class TalkProposalAdmin(ExportMixin, ProposalAdmin): resource_class = TalkProposalResource @admin.register(TutorialProposal) class TutorialProposalAdmin(ProposalAdmin): pass
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from import_export.admin import ExportMixin from .models import AdditionalSpeaker, TalkProposal, TutorialProposal from .resources import TalkProposalResource class AdditionalSpeakerInline(GenericTabularInline): model = AdditionalSpeaker fields = ['user', 'status', 'cancelled'] ct_field = 'proposal_type' ct_fk_field = 'proposal_id' extra = 0 class ProposalAdmin(admin.ModelAdmin): list_display = [ 'title', 'category', 'duration', 'language', 'python_level', 'accepted', 'python_level', 'remoting_policy', 'accepted', ] list_filter = [ 'cancelled', 'accepted', 'category', 'duration', 'language', 'python_level', ] fields = [ 'conference', 'submitter', 'title', 'category', 'duration', 'language', 'abstract', 'python_level', 'objective', 'detailed_description', 'outline', 'supplementary', 'recording_policy', 'slide_link', 'referring_policy', 'cancelled', 'recording_policy', 'slide_link', 'referring_policy', 'remoting_policy', 'cancelled', 'accepted', 'slido_embed_link', ] raw_id_fields = ['submitter'] search_fields = ['title', 'abstract'] inlines = [AdditionalSpeakerInline] @admin.register(TalkProposal) class TalkProposalAdmin(ExportMixin, ProposalAdmin): resource_class = TalkProposalResource @admin.register(TutorialProposal) class TutorialProposalAdmin(ProposalAdmin): pass
mit
Python
edeb1e3d9c953f4699ee3e598e3d758c038eda40
Add PathStats to intermediatePathTypes demo.
visdesignlab/TulipPaths,visdesignlab/TulipPaths
demos/intermediatePathTypes.py
demos/intermediatePathTypes.py
""" Example of finding paths and unique types using PathStats """ from tulip import * from tulipgui import * import tulippaths as tp # Path parameters graphFile = '../data/514_4hops.tlp' sourceNodeId = 593 targetNodeId = 514 maxNumHops = 5 graph = tlp.loadGraph(graphFile) # Find start and end nodes source = tp.getNodeById(sourceNodeId, graph) target = tp.getNodeById(targetNodeId, graph) finder = tp.PathFinder(graph) print 'hops, total, valid, unique, num w\ loop' for i in range(0, maxNumHops): finder.reset() finder.findPaths(source, target, i) stats = tp.PathStats(finder.valid) print str(i) + ', ' + str(len(finder.valid) + len(finder.failed)) + ', ' + str(len(finder.valid)) + ', ' + \ str(stats.getNumUniqueTypes()) + ', ' + str(stats.getNumPathsWithLoop()) # Render the graph in a node-link diagram. nodeLinkView = tlpgui.createNodeLinkDiagramView(graph)
""" Example of finding paths and printing type details. """ from tulip import * from tulipgui import * import tulippaths as tp # Load the graph. graph = tlp.loadGraph("../data/test_one.tlp") # Find start and end nodes source = tp.getNodeById(176, graph) target = tp.getNodeById(606, graph) # Find paths finder = tp.PathFinder(graph) finder.findPaths(source, target, 3) # Print paths print 'The failed paths are:' for path in finder.valid: print ' ' + path.toString() print 'The valid paths are:' for path in finder.valid: print ' ' + path.toString() print 'The valid paths types are:' for path in finder.valid: print ' ' + path.toStringOfTypes() # Render the graph in a node-link diagram. nodeLinkView = tlpgui.createNodeLinkDiagramView(graph)
mit
Python
f1477afc2ff20a702a53ed82549dca07acd388dc
Update jogovelha.py
Augustosimoes/devops-aula05
Src/jogovelha.py
Src/jogovelha.py
def inicializar(): tab = [ ] for i in range (3): linha = [ ] for j in range(3): linha.append("X") tab.append(linha) return tab def main( ): jogo = inicializar ( ) print (jogo) if _name_ == "_main_": main()
def inicializar(): tab = [ ] for i in range (3): linha = [ ] for j in range(3): linha.append(".") tab.append(linha) return tab def main( ): jogo = inicializar ( ) print (jogo) if _name_ == "_main_": main()
apache-2.0
Python
9d14f60713726e05dab00a1b1e8eccfc32b17d58
bump version to 2.2.0
RaRe-Technologies/smart_open,RaRe-Technologies/smart_open
smart_open/version.py
smart_open/version.py
__version__ = '2.2.0'
__version__ = '2.1.1'
mit
Python
3222e6164906956f698c63e26bddd85cd6a941be
use new fetch methods
gabstopper/smc-python
smc/actions/remove.py
smc/actions/remove.py
import logging import smc.actions import smc.api.web as web_api import smc.api.common as common_api from smc.elements.element import SMCElement logger = logging.getLogger(__name__) def element(name, objtype=None): """ Remove by element Args: * name: name for object to remove * objtype (optional): filter to add to search for element, i.e. host,network,single_fw,etc Returns: None """ removable = smc.actions.search.element_info_as_json(name) if removable is not None: logger.debug("Element: %s found and is of type: %s. Attempting to remove" % (name, removable['type'])) element = SMCElement() element.name = name element.type = removable['type'] element.href = removable['href'] common_api._remove(element) else: logger.info("No element named: %s, nothing to remove" % name) if __name__ == '__main__': web_api.session.login('http://172.18.1.150:8082', 'EiGpKD4QxlLJ25dbBEp20001') smc.create.host('test-run', '2.2.2.2') smc.create.host('ami2', '3.4.5.6') smc.remove.element('test-run') #single fw smc.remove.element('ami2') #single host smc.remove.element('anewgroup') #group web_api.session.logout()
import logging import smc.actions import smc.api.web as web_api import smc.api.common as common_api from smc.elements.element import SMCElement logger = logging.getLogger(__name__) def element(name, objtype=None): """ Remove by element Args: * name: name for object to remove * objtype (optional): filter to add to search for element, i.e. host,network,single_fw,etc Returns: None """ removable = smc.actions.search.get_element(name, objtype) if removable is not None: logger.debug("Element: %s found and is of type: %s. Attempting to remove" % (name, removable['type'])) element = SMCElement() element.name = name element.type = removable['type'] element.href = removable['href'] common_api._remove(element) else: logger.info("No element named: %s, nothing to remove" % name) if __name__ == '__main__': web_api.session.login('http://172.18.1.150:8082', 'EiGpKD4QxlLJ25dbBEp20001') smc.remove.element('test-run') #single fw smc.remove.element('ami2') #single host smc.remove.element('anewgroup') #group web_api.session.logout()
apache-2.0
Python
89973ed75031fb4e697b66d9f7d150e11978bce0
Update django_dbq/management/commands/queue_depth.py
dabapps/django-db-queue
django_dbq/management/commands/queue_depth.py
django_dbq/management/commands/queue_depth.py
from django.core.management.base import BaseCommand from django_dbq.models import Job class Command(BaseCommand): help = "Print the current depth of the given queue" def add_arguments(self, parser): parser.add_argument("queue_name", nargs="?", default="default", type=str) def handle(self, *args, **options): queue_name = options["queue_name"] queue_depths = Job.get_queue_depths() all_queues_depth = sum(queue_depths.values()) self.stdout.write( "queue_name={queue_name} queue_depth={depth} all_queues_depth={all_queue_depths}".format( all_queues_depth=all_queues_depth, queue_name=queue_name, depth=queue_depths.get(queue_name, 0), ) )
from django.core.management.base import BaseCommand from django_dbq.models import Job class Command(BaseCommand): help = "Print the current depth of the given queue" def add_arguments(self, parser): parser.add_argument("queue_name", nargs="?", default="default", type=str) def handle(self, *args, **options): queue_name = options["queue_name"] queue_depths = Job.get_queue_depths() all_queues_depth = sum(queue_depths.values()) self.stdout.write( "all_queues_depth= queue_name={queue_name} queue_depth={depth}".format( all_queues_depth=all_queues_depth, queue_name=queue_name, depth=queue_depths.get(queue_name, 0), ) )
bsd-2-clause
Python
f88efe1c63c8f480879cad671b34be854045fb1c
Improve source admin for mutations
IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site
apps/mutations/admin.py
apps/mutations/admin.py
# # Copyright (C) 2016 Dr. Maha Farhat # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ A basic set of administrative functions for genes and mutations """ from django.contrib.admin import * from .models import * from .forms import DrugForm class ImportSourceAdmin(ModelAdmin): list_display = ('name', 'created', 'uploader', 'complete') readonly_fields = ('uploaded',) site.register(ImportSource, ImportSourceAdmin) class DrugAdmin(ModelAdmin): list_display = ('__str__', 'mutation_count') def get_form(self, *args, **kw): return DrugForm def mutation_count(self, obj): return obj.mutations.count() site.register(DrugClass) site.register(Drug, DrugAdmin) class MutationInline(StackedInline): model = Mutation extra = 2 class GeneLocusAdmin(ModelAdmin): inlines = (MutationInline,) list_filter = ('genome',) list_display = ('name', 'description', 'previous_id', 'mutation_count', 'genome') def mutation_count(self, obj): return obj.mutations.count() site.register(Genome) site.register(GeneLocus, GeneLocusAdmin) class MutationAdmin(ModelAdmin): list_display = ('name', 'old_id', 'gene_locus', 'drugs_list') list_filter = ('predictor', 'gene_locus', 'drugs') search_fields = ('name', 'old_id') def drugs_list(self, obj): return ", ".join(obj.drugs.values_list('code', flat=True)) site.register(Mutation, MutationAdmin) site.register(TargetSet) site.register(TargetRegion) class StrainSourceAdmin(ModelAdmin): list_display = ('__str__', 'old_id', 'patient_id', 'country', 'date') list_filter = ('importer', 'source_lab', 'patient_sex', 'patient_hiv', 'resistance_group') site.register(StrainSource, StrainSourceAdmin) site.register(StrainMutation) class StrainResistanceAdmin(ModelAdmin): list_filter = ('resistance', 'drug') site.register(StrainResistance, StrainResistanceAdmin)
# # Copyright (C) 2016 Dr. Maha Farhat # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ A basic set of administrative functions for genes and mutations """ from django.contrib.admin import * from .models import * from .forms import DrugForm site.register(ImportSource) class DrugAdmin(ModelAdmin): list_display = ('__str__', 'mutation_count') def get_form(self, *args, **kw): return DrugForm def mutation_count(self, obj): return obj.mutations.count() site.register(DrugClass) site.register(Drug, DrugAdmin) class MutationInline(StackedInline): model = Mutation extra = 2 class GeneLocusAdmin(ModelAdmin): inlines = (MutationInline,) list_filter = ('genome',) list_display = ('name', 'description', 'previous_id', 'mutation_count', 'genome') def mutation_count(self, obj): return obj.mutations.count() site.register(Genome) site.register(GeneLocus, GeneLocusAdmin) class MutationAdmin(ModelAdmin): list_display = ('name', 'old_id', 'gene_locus', 'drugs_list') list_filter = ('predictor', 'gene_locus', 'drugs') search_fields = ('name', 'old_id') def drugs_list(self, obj): return ", ".join(obj.drugs.values_list('code', flat=True)) site.register(Mutation, MutationAdmin) site.register(TargetSet) site.register(TargetRegion) class StrainSourceAdmin(ModelAdmin): list_display = ('__str__', 'old_id', 'patient_id', 'country', 'date') list_filter = ('importer', 'source_lab', 'patient_sex', 'patient_hiv', 'resistance_group') site.register(StrainSource, StrainSourceAdmin) site.register(StrainMutation) class StrainResistanceAdmin(ModelAdmin): list_filter = ('resistance', 'drug') site.register(StrainResistance, StrainResistanceAdmin)
agpl-3.0
Python
a865dbad699025e9efce4ec08edae9584b2bd178
add MIT license
tedder/aws-release-notes-rss
scrape.py
scrape.py
#!/usr/bin/python # MIT license # (see: http://www.opensource.org/licenses/mit-license.php) # # Copyright (c) 2014 Ted Timmons, ted@timmons.me # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import boto import requests from lxml import html import lxml import PyRSS2Gen import datetime import StringIO import sys from dateutil.parser import parse LINK = "https://aws.amazon.com/releasenotes/" page = requests.get(LINK) try: tree = html.fromstring(page.text) except lxml.etree.XMLSyntaxError: if page.status_code == 500: sys.exit(0) print "page failed. %s" % page.status_code rssitems = [] #items = tree.xpath('//itemsTable/div[@class="item"]') items = tree.xpath('//div[@id="itemsTable"]/div[@class="item"]') for item in items: title = item.xpath('normalize-space(div[@class="title"]/a/text())') itemlink = item.xpath('normalize-space(div[@class="title"]/a/@href)') desc = item.xpath('normalize-space(div[@class="desc"]/text())') modDate = item.xpath('normalize-space(div[@class="lastMod"]/text())') # strip off the initial text, the parser doesn't grok it. parsedDate = parse(modDate.replace('Last Modified: ', '')) rssitems.append(PyRSS2Gen.RSSItem( title = title, link = itemlink, guid = itemlink, description = desc, pubDate = parsedDate )) rss = PyRSS2Gen.RSS2( title = "Amazon AWS Release Notes scraped feed", link = LINK, ttl = 3600, # cache 6hrs docs = "https://github.com/tedder/aws-release-notes-rss", description = "new code and features from AWS", lastBuildDate = datetime.datetime.now(), items = rssitems ) rssfile = StringIO.StringIO() rss.write_xml(rssfile) s3bucket = boto.connect_s3().get_bucket('tedder') s3key = s3bucket.new_key('rss/aws-release-notes.xml') s3key.set_metadata('Content-Type', 'application/rss+xml') s3key.set_contents_from_string(rssfile.getvalue(), replace=True, reduced_redundancy=True, headers={'Cache-Control':'public, max-age=3600'}, policy="public-read")
#!/usr/bin/python import boto import requests from lxml import html import lxml import PyRSS2Gen import datetime import StringIO import sys from dateutil.parser import parse LINK = "https://aws.amazon.com/releasenotes/" page = requests.get(LINK) try: tree = html.fromstring(page.text) except lxml.etree.XMLSyntaxError: if page.status_code == 500: sys.exit(0) print "page failed. %s" % page.status_code rssitems = [] #items = tree.xpath('//itemsTable/div[@class="item"]') items = tree.xpath('//div[@id="itemsTable"]/div[@class="item"]') for item in items: title = item.xpath('normalize-space(div[@class="title"]/a/text())') itemlink = item.xpath('normalize-space(div[@class="title"]/a/@href)') desc = item.xpath('normalize-space(div[@class="desc"]/text())') modDate = item.xpath('normalize-space(div[@class="lastMod"]/text())') # strip off the initial text, the parser doesn't grok it. parsedDate = parse(modDate.replace('Last Modified: ', '')) rssitems.append(PyRSS2Gen.RSSItem( title = title, link = itemlink, guid = itemlink, description = desc, pubDate = parsedDate )) rss = PyRSS2Gen.RSS2( title = "Amazon AWS Release Notes scraped feed", link = LINK, ttl = 3600, # cache 6hrs docs = "https://github.com/tedder/aws-release-notes-rss", description = "new code and features from AWS", lastBuildDate = datetime.datetime.now(), items = rssitems ) rssfile = StringIO.StringIO() rss.write_xml(rssfile) s3bucket = boto.connect_s3().get_bucket('tedder') s3key = s3bucket.new_key('rss/aws-release-notes.xml') s3key.set_metadata('Content-Type', 'application/rss+xml') s3key.set_contents_from_string(rssfile.getvalue(), replace=True, reduced_redundancy=True, headers={'Cache-Control':'public, max-age=3600'}, policy="public-read")
mit
Python
29aa96cdbb02ef686bdb0c722955d1ad875d0099
Add check that image sizes match
stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv
plantcv/plantcv/visualize/overlay_two_imgs.py
plantcv/plantcv/visualize/overlay_two_imgs.py
# Overlay two input images """ Created on Tue. September 01 21:00:01 2020 A function @author: hudanyunsheng """ import os import cv2 import numpy as np from plantcv.plantcv import fatal_error from plantcv.plantcv import plot_image from plantcv.plantcv import print_image from plantcv.plantcv import params def overlay_two_imgs(img1, img2, alpha=0.5): """Overlay two images with a given alpha value. Inputs: img1 - RGB or grayscale image data img2 - RGB or grayscale image data alpha - Desired opacity of 1st image, range: (0,1), default value=0.5 Returns: out_img - Blended RGB image :param img1: numpy.ndarray :param img2: numpy.ndarray :param alpha: float :return: out_img: numpy.ndarray """ # Validate alpha if alpha > 1 or alpha < 0: fatal_error("The value of alpha should be in the range of (0,1)!") # Validate image sizes are the same size_img1 = img1.shape[0:2] size_img2 = img2.shape[0:2] if size_img1 != size_img2: fatal_error(f"The height/width of img1 ({size_img1}) needs to match img2 ({size_img2}).") # Copy the input images img1_ = np.copy(img1) img2_ = np.copy(img2) # If the images are grayscale convert to BGR if len(img1_.shape) == 2: img1_ = cv2.cvtColor(img1_, cv2.COLOR_GRAY2BGR) if len(img2_.shape) == 2: img2_ = cv2.cvtColor(img2_, cv2.COLOR_GRAY2BGR) # initialize the output image out_img = np.zeros(size_img1 + (3,), dtype=np.uint8) # blending out_img[:, :, :] = (alpha * img1_[:, :, :]) + ((1 - alpha) * img2_[:, :, :]) params.device += 1 if params.debug == 'print': print_image(out_img, os.path.join(params.debug_outdir, str(params.device) + '_overlay.png')) elif params.debug == 'plot': plot_image(out_img) return out_img
# Overlay two input images """ Created on Tue. September 01 21:00:01 2020 A function @author: hudanyunsheng """ import os import cv2 import numpy as np from plantcv.plantcv import fatal_error from plantcv.plantcv import plot_image from plantcv.plantcv import print_image from plantcv.plantcv import params def overlay_two_imgs(img1, img2, alpha=0.5): """Overlay two images with a given alpha value. Inputs: img1 - RGB or grayscale image data img2 - RGB or grayscale image data alpha - Desired opacity of 1st image, range: (0,1), default value=0.5 Returns: out_img - Blended RGB image :param img1: numpy.ndarray :param img2: numpy.ndarray :param alpha: float :return: out_img: numpy.ndarray """ if alpha > 1 or alpha < 0: fatal_error("The value of alpha should be in the range of (0,1)!") # Copy the input images img1_ = np.copy(img1) img2_ = np.copy(img2) # If the images are grayscale convert to BGR if len(img1_.shape) == 2: img1_ = cv2.cvtColor(img1_, cv2.COLOR_GRAY2BGR) if len(img2_.shape) == 2: img2_ = cv2.cvtColor(img2_, cv2.COLOR_GRAY2BGR) ## sizing # assumption: the sizes of img1 and img2 are the same size_img = img1_.shape[0:2] # initialize the output image out_img = np.zeros(size_img + (3,), dtype='uint8') # blending out_img[:, :, :] = (alpha * img1_[:, :, :]) + ((1 - alpha) * img2_[:, :, :]) params.device += 1 if params.debug == 'print': print_image(out_img, os.path.join(params.debug_outdir, str(params.device) + '_overlay.png')) elif params.debug == 'plot': plot_image(out_img) return out_img
mit
Python
e8badf03203c0a65ac291a0acdd233847dc7df3f
Update alsa_sound_control.py
GraphicalBear/MusiCube,GraphicalBear/MusiCube,GraphicalBear/MusiCube,GraphicalBear/MusiCube
Python/alsa_sound_control.py
Python/alsa_sound_control.py
import time import serial import random from pygame import mixer mixer.init() running = True elapsed_time = 0 next_value = 25 serialPort = serial.Serial(port = '/dev/ttyUSB0', baudrate = 115200) for x in range(3): serialPort.readline() def play_song(): # picker = random.randint(2, 4) global serialPort picker = 2 if picker is 2: file_path = '/home/pi/Music/Still_Alive.mp3' if picker is 3: file_path = '/home/pi/Music/Mario_Theme.mp3' if picker is 4: file_path = '/home/pi/Music/Tetris_Theme.mp3' mixer.music.load(file_path) mixer.music.play() serialPort.write(picker) serialPort.flushInput() serialPort.flushOutput() for x in range(100): serialPort.write(bytes([0])) time.sleep(0.2) serialPort.write(bytes([1])) elapsed_time = time.time() while running: print "EL", print elapsed_time print "CT", print time.time() if serialPort.inWaiting() > 0: next_value = serialPort.readline() try: next_value = float(next_value) except ValueError: next_value = float(0) serialPort.flushInput() print next_value if abs(next_value) > 1500: elapsed_time = time.time() serialPort.write(bytes([1])) if abs(elapsed_time - time.time()) >= 15: play_song() serialPort.write(bytes([0]))
import time import serial import random from pygame import mixer mixer.init() running = True elapsed_time = 0 next_value = 25 serialPort = serial.Serial(port = '/dev/ttyUSB0', baudrate = 115200) for x in range(3): serialPort.readline() def play_song(): # picker = random.randint(2, 4) global serialPort picker = 2 if picker is 2: file_path = '/home/pi/Music/Still_Alive.mp3' if picker is 3: file_path = '/home/pi/Music/Mario_Theme.mp3' if picker is 4: file_path = '/home/pi/Music/Tetris_Theme.mp3' mixer.music.load(file_path) mixer.music.play() serialPort.write(bytes([picker])) serialPort.flushInput() serialPort.flushOutput() for x in range(100): serialPort.write(bytes([0])) time.sleep(0.2) serialPort.write(bytes([1])) elapsed_time = time.time() while running: print "EL", print elapsed_time print "CT", print time.time() if serialPort.inWaiting() > 0: next_value = serialPort.readline() try: next_value = float(next_value) except ValueError: next_value = float(0) serialPort.flushInput() print next_value if abs(next_value) > 1500: elapsed_time = time.time() serialPort.write(bytes([1])) if abs(elapsed_time - time.time()) >= 25: play_song() serialPort.write(bytes([0]))
unlicense
Python
80701d30488cab98c63232723313aef6175e02a8
Fix broken test. (#705)
adarob/magenta,jesseengel/magenta,adarob/magenta,magenta/magenta,magenta/magenta,jesseengel/magenta
magenta/models/shared/events_rnn_graph_test.py
magenta/models/shared/events_rnn_graph_test.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for events_rnn_graph.""" import tempfile # internal imports import tensorflow as tf import magenta from magenta.models.shared import events_rnn_graph from magenta.models.shared import events_rnn_model class EventSequenceRNNGraphTest(tf.test.TestCase): def setUp(self): self._sequence_file = tempfile.NamedTemporaryFile( prefix='EventSequenceRNNGraphTest') self.config = events_rnn_model.EventSequenceRnnConfig( None, magenta.music.OneHotEventSequenceEncoderDecoder( magenta.music.testing_lib.TrivialOneHotEncoding(12)), magenta.common.HParams( batch_size=128, rnn_layer_sizes=[128, 128], dropout_keep_prob=0.5, clip_norm=5, learning_rate=0.01)) def testBuildTrainGraph(self): g = events_rnn_graph.build_graph( 'train', self.config, sequence_example_file_paths=[self._sequence_file.name]) self.assertTrue(isinstance(g, tf.Graph)) def testBuildEvalGraph(self): g = events_rnn_graph.build_graph( 'eval', self.config, sequence_example_file_paths=[self._sequence_file.name]) self.assertTrue(isinstance(g, tf.Graph)) def testBuildGenerateGraph(self): g = events_rnn_graph.build_graph('generate', self.config) self.assertTrue(isinstance(g, tf.Graph)) def testBuildGraphWithAttention(self): self.config.hparams.attn_length = 10 g = events_rnn_graph.build_graph( 'train', self.config, sequence_example_file_paths=[self._sequence_file.name]) self.assertTrue(isinstance(g, tf.Graph)) if __name__ == '__main__': tf.test.main()
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for events_rnn_graph.""" # internal imports import tensorflow as tf import magenta from magenta.models.shared import events_rnn_graph from magenta.models.shared import events_rnn_model class EventSequenceRNNGraphTest(tf.test.TestCase): def setUp(self): self.config = events_rnn_model.EventSequenceRnnConfig( None, magenta.music.OneHotEventSequenceEncoderDecoder( magenta.music.testing_lib.TrivialOneHotEncoding(12)), magenta.common.HParams( batch_size=128, rnn_layer_sizes=[128, 128], dropout_keep_prob=0.5, clip_norm=5, learning_rate=0.01)) def testBuildTrainGraph(self): g = events_rnn_graph.build_graph( 'train', self.config, sequence_example_file_paths=['test']) self.assertTrue(isinstance(g, tf.Graph)) def testBuildEvalGraph(self): g = events_rnn_graph.build_graph( 'eval', self.config, sequence_example_file_paths=['test']) self.assertTrue(isinstance(g, tf.Graph)) def testBuildGenerateGraph(self): g = events_rnn_graph.build_graph('generate', self.config) self.assertTrue(isinstance(g, tf.Graph)) def testBuildGraphWithAttention(self): self.config.hparams.attn_length = 10 g = events_rnn_graph.build_graph( 'train', self.config, sequence_example_file_paths=['test']) self.assertTrue(isinstance(g, tf.Graph)) if __name__ == '__main__': tf.test.main()
apache-2.0
Python
2ba28c83de33ebc75f386d127d0c55e17248a94b
Add location to step metadata.
rchristie/mapclientplugins.meshgeneratorstep
mapclientplugins/meshgeneratorstep/__init__.py
mapclientplugins/meshgeneratorstep/__init__.py
""" MAP Client Plugin """ __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = 'https://github.com/ABI-Software/mapclientplugins.meshgeneratorstep' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
""" MAP Client Plugin """ __version__ = '0.2.0' __author__ = 'Richard Christie' __stepname__ = 'Mesh Generator' __location__ = '' # import class that derives itself from the step mountpoint. from mapclientplugins.meshgeneratorstep import step # Import the resource file when the module is loaded, # this enables the framework to use the step icon. from . import resources_rc
apache-2.0
Python
a2df05a5ce93095e33dafb7a3c2807361ca93a37
Add *all* errors to __init__.py
bskinn/sphobjinv
src/sphobjinv/__init__.py
src/sphobjinv/__init__.py
r"""``sphobjinv`` *package definition module*. ``sphobjinv`` is a toolkit for manipulation and inspection of Sphinx |objects.inv| files. **Author** Brian Skinn (bskinn@alum.mit.edu) **File Created** 17 May 2016 **Copyright** \(c) Brian Skinn 2016-2022 **Source Repository** https://github.com/bskinn/sphobjinv **Documentation** https://sphobjinv.readthedocs.io/en/latest **License** The MIT License; see |license_txt|_ for full license terms **Members** """ from sphobjinv import intersphinx from sphobjinv.data import DataFields, DataObjBytes, DataObjStr from sphobjinv.enum import HeaderFields, SourceTypes from sphobjinv.error import ( SOIIntersphinxError, SOIIsphxNoMatchingObjectError, SOIIsphxNotASuffixError, SphobjinvError, VersionError, ) from sphobjinv.fileops import readbytes, readjson, urlwalk, writebytes, writejson from sphobjinv.inventory import Inventory from sphobjinv.re import p_data, pb_comments, pb_data, pb_project, pb_version from sphobjinv.schema import json_schema from sphobjinv.version import __version__ from sphobjinv.zlib import compress, decompress
r"""``sphobjinv`` *package definition module*. ``sphobjinv`` is a toolkit for manipulation and inspection of Sphinx |objects.inv| files. **Author** Brian Skinn (bskinn@alum.mit.edu) **File Created** 17 May 2016 **Copyright** \(c) Brian Skinn 2016-2022 **Source Repository** https://github.com/bskinn/sphobjinv **Documentation** https://sphobjinv.readthedocs.io/en/latest **License** The MIT License; see |license_txt|_ for full license terms **Members** """ from sphobjinv import intersphinx from sphobjinv.data import DataFields, DataObjBytes, DataObjStr from sphobjinv.enum import HeaderFields, SourceTypes from sphobjinv.error import SphobjinvError, VersionError from sphobjinv.fileops import readbytes, readjson, urlwalk, writebytes, writejson from sphobjinv.inventory import Inventory from sphobjinv.re import p_data, pb_comments, pb_data, pb_project, pb_version from sphobjinv.schema import json_schema from sphobjinv.version import __version__ from sphobjinv.zlib import compress, decompress
mit
Python
6cefc4f94bd78de84a6e5713e28111834307576d
Create model Member
rocity/dj-instagram,rocity/dj-instagram,rocity/dj-instagram
djinstagram/instaapp/models.py
djinstagram/instaapp/models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Follow(models.Model): follower = models.ForeignKey(User, related_name='+', null=True) following = models.ForeignKey(User, related_name='+', null=True) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def get_follower(self): return self.follower def get_following(self): return self.following class Tag(models.Model): name = models.TextField(max_length=255) def __str__(self): return self.name class Photo(models.Model): owner = models.ForeignKey(User, null=True) caption = models.TextField(max_length=255) image = models.ImageField(upload_to="uploads/photos", null=True) tags = models.ManyToManyField(Tag) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.caption class Like(models.Model): owner = models.ForeignKey(User, null=True) photo = models.ForeignKey(Photo, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.photo class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to="uploads/dp", null=True)
from django.db import models from django.contrib.auth.models import User # Create your models here. class Follow(models.Model): follower = models.ForeignKey(User, related_name='+', null=True) following = models.ForeignKey(User, related_name='+', null=True) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def get_follower(self): return self.follower def get_following(self): return self.following class Tag(models.Model): name = models.TextField(max_length=255) def __str__(self): return self.name class Photo(models.Model): owner = models.ForeignKey(User, null=True) caption = models.TextField(max_length=255) image = models.ImageField(upload_to="uploads/photos", null=True) tags = models.ManyToManyField(Tag) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.caption class Like(models.Model): owner = models.ForeignKey(User, null=True) photo = models.ForeignKey(Photo, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.photo
apache-2.0
Python
f61e0aaef192b20c445f270671470d3a0d6d4161
test that random_land actually returns land
MM1nd/worldengine,MM1nd/worldengine,Mindwerks/worldengine,Mindwerks/worldengine
tests/simulation_test.py
tests/simulation_test.py
import unittest import numpy from worldengine.simulations.hydrology import WatermapSimulation from worldengine.model.world import World, Size, GenerationParameters class TestSimulation(unittest.TestCase): # The hydrology simulation indirectly calls the global rng. # We want different implementations of _watermap # and internally called functions (especially random_land) # to show the same rng behaviour and not contamine the state of the global rng # should anyone else happen to rely on it. # This does only test that watermap leaves the rng in the state that the # original implementation would have left it in and that a very small sample # of results is the same as the original results. # It does not test if the implementation is actually correct. # In fact it is hard to tell how "correctness" of a Monte Carlo process should # be judged. # Should it ever be decided that a "correct" implementation needs fewer or # less calls to the rng, relative to the n parameter, # of course compatibility will be broken. # Implicitly this is tested by the blessed images but it might be useful to # have a finer grained picture. def test_watermap_rng_stabilty(self): seed=12345 numpy.random.seed(seed) size = Size(16,8) ocean = numpy.fromfunction(lambda y, x: y==x, (size.height, size.width)) percipitation = numpy.ones((size.height, size.width)) elevation = numpy.fromfunction(lambda y, x: y*x, (size.height, size.width)) t = numpy.zeros(5) w = World("watermap", size, seed, GenerationParameters(0, 1.0, 0)) w.ocean = ocean w.precipitation = (percipitation, t) w.elevation = (elevation, t) d = numpy.random.randint(0,100) self.assertEqual(d, 98) data, t = WatermapSimulation._watermap(w, 200) self.assertAlmostEqual(data[4,4], 0.0) self.assertAlmostEqual(data[3,5], 4.20750776) d = numpy.random.randint(0,100) self.assertEqual(d, 59) def test_random_land_returns_only_land(self): size = Size(100,100) ocean = numpy.fromfunction(lambda y, x: y>x, (size.height, size.width)) w = World("random_land", size, 0, GenerationParameters(0, 1.0, 0)) w.ocean = ocean num_samples = 1000 land_indices = w.random_land(num_samples) for i in range(0, num_samples, 2): self.assertFalse(ocean[land_indices[i+1],land_indices[i]]) if __name__ == '__main__': unittest.main()
import unittest import numpy from worldengine.simulations.hydrology import WatermapSimulation from worldengine.model.world import World, Size, GenerationParameters class TestSimulation(unittest.TestCase): # The hydrology simulation indirectly calls the global rng. # We want different implementations of _watermap # and internally called functions (especially random_land) # to show the same rng behaviour and not contamine the state of the global rng # should anyone else happen to rely on it. # This does only test that watermap leaves the rng in the state that the # original implementation would have left it in and that a very small sample # of results is the same as the original results. # It does not test if the implementation is actually correct. # In fact it is hard to tell how "correctness" of a Monte Carlo process should # be judged. # Should it ever be decided that a "correct" implementation needs fewer or # less calls to the rng, relative to the n parameter, # of course compatibility will be broken. # Implicitly this is tested by the blessed images but it might be useful to # have a finer grained picture. def test_watermap_rng_stabilty(self): seed=12345 numpy.random.seed(seed) size = Size(16,8) ocean = numpy.fromfunction(lambda y, x: y==x, (size.height, size.width)) percipitation = numpy.ones((size.height, size.width)) elevation = numpy.fromfunction(lambda y, x: y*x, (size.height, size.width)) t = numpy.zeros(5) w = World("watermap", size, seed, GenerationParameters(0, 1.0, 0)) w.ocean = ocean w.precipitation = (percipitation, t) w.elevation = (elevation, t) d = numpy.random.randint(0,100) self.assertEqual(d, 98) data, t = WatermapSimulation._watermap(w, 200) self.assertAlmostEqual(data[4,4], 0.0) self.assertAlmostEqual(data[3,5], 4.20750776) d = numpy.random.randint(0,100) self.assertEqual(d, 59) if __name__ == '__main__': unittest.main()
mit
Python
a3de6cc27266bfb2a71aa910451309ce4b7b6c79
fix newline replacement
natemara/historian
server.py
server.py
#!/usr/bin/env python3 import os import json import argparse import subprocess import tornado.ioloop import tornado.web import tornado.autoreload BASE_PATH = os.path.dirname(os.path.realpath(__file__)) def run_process(command): with subprocess.Popen(command, stdout=subprocess.PIPE) as proc: return proc.stdout.read() def commit(repo, message): os.chdir(os.path.join(BASE_PATH, repo)) run_process(['git', 'add', 'data.txt']) run_process(['git', 'commit', '-m', message]) os.chdir(BASE_PATH) def load_json_file(filename): with open('json/{}'.format(filename), 'r') as jsonfile: return json.load(jsonfile) class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') class EditHandler(tornado.web.RequestHandler): def get(self, user, repo): if os.path.exists(os.path.join('data', user, repo, 'data.txt')): with open(os.path.join('data', user, repo, 'data.txt')) as data_file: data = ''.join(data_file.readlines()).replace('\n', ' ').replace(' $NEWLINE ', '\n') self.render('repo.html', data=data, user=user, repo=repo) else: self.finish('REPO NOT FOUND') def post(self, user, repo): data = self.get_argument('data').replace('\n', ' $NEWLINE ').replace(' ', '\n') commit_message = self.get_argument('commit_message') repo_path = os.path.join('data', user, repo) data_path = os.path.join(repo_path, 'data.txt') if os.path.exists(data_path): with open(data_path, 'w') as data_file: data_file.writelines(data) commit(repo_path, commit_message) self.render('repo.html', data=data, user=user, repo=repo) else: self.finish('REPO NOT FOUND') handlers = [ (r'/', MainHandler), (r'/([^/]+)/([^/]+)/edit', EditHandler), ] settings = { 'debug': True, 'static_path': os.path.join(BASE_PATH, 'static'), 'template_path': os.path.join(BASE_PATH, 'templates') } application = tornado.web.Application(handlers, **settings) def parse_args(): parser = argparse.ArgumentParser( description='Server application for the Historian app', prog='server.py' ) parser.add_argument( '-p', '--port', metavar='PORT', type=int, help='The port that this instance of the server should listen on' ) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() tornado.autoreload.start() application.listen(args.port) tornado.ioloop.IOLoop.instance().start()
#!/usr/bin/env python3 import os import json import argparse import subprocess import tornado.ioloop import tornado.web import tornado.autoreload BASE_PATH = os.path.dirname(os.path.realpath(__file__)) def run_process(command): with subprocess.Popen(command, stdout=subprocess.PIPE) as proc: return proc.stdout.read() def commit(repo, message): os.chdir(os.path.join(BASE_PATH, repo)) run_process(['git', 'add', 'data.txt']) run_process(['git', 'commit', '-m', message]) os.chdir(BASE_PATH) def load_json_file(filename): with open('json/{}'.format(filename), 'r') as jsonfile: return json.load(jsonfile) class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') class RepoHandler(tornado.web.RequestHandler): def get(self, user, repo): if os.path.exists(os.path.join('data', user, repo, 'data.txt')): with open(os.path.join('data', user, repo, 'data.txt')) as data_file: data = ''.join(data_file.readlines()).replace('\n', ' ').replace('$NEWLINE', '\n') self.render('repo.html', data=data, user=user, repo=repo) else: self.finish('REPO NOT FOUND') def post(self, user, repo): data = self.get_argument('data').replace('\n', '$NEWLINE').replace(' ', '\n') commit_message = self.get_argument('commit_message') repo_path = os.path.join('data', user, repo) data_path = os.path.join(repo_path, 'data.txt') if os.path.exists(data_path): with open(data_path, 'w') as data_file: data_file.writelines(data) commit(repo_path, commit_message) self.render('repo.html', data=data, user=user, repo=repo) else: self.finish('REPO NOT FOUND') handlers = [ (r'/', MainHandler), (r'/([^/]+)/([^/]+)', RepoHandler), ] settings = { 'debug': True, 'static_path': os.path.join(BASE_PATH, 'static'), 'template_path': os.path.join(BASE_PATH, 'templates') } application = tornado.web.Application(handlers, **settings) def parse_args(): parser = argparse.ArgumentParser( description='Server application for the Historian app', prog='server.py' ) parser.add_argument( '-p', '--port', metavar='PORT', type=int, help='The port that this instance of the server should listen on' ) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() tornado.autoreload.start() application.listen(args.port) tornado.ioloop.IOLoop.instance().start()
mit
Python
b7fba7c12a9f37665dd8747631fcc9495b55a369
index and protocol fixes
acmuniandes/Sobrecupo,acmuniandes/Sobrecupo,acmuniandes/Sobrecupo
server.py
server.py
import os import redis import logging import datetime from flask import Flask , send_from_directory, render_template, url_for, request r = redis.from_url(os.environ.get("REDIS_URL")) app = Flask(__name__) #"Landing page" @app.route('/') def webprint(): return render_template('index.html') #Saves the string <strng> in the DB @app.route('/db/<strng>') def saveInDB(strng): r.lpush('db', '%s' % strng) return 'OK' #Recalls the stored info in the DB @app.route('/db/recall/test', methods = ['GET']) def recallDB(): try: return __str__(r.lrange('db', 0, -1)).decode('utf-8') except Exception as error: return formatError(error) #DevMode Handling------------------------------------ #Returns devMode.html [GET] #Checks login credentials [POST] @app.route('/devMode', methods = ['POST', 'GET']) def devMode(): if request.method == 'GET': r.incr('devModeGet') return render_template('devMode.html') elif request.method == 'POST': pss = request.get_json() or request.form if checkPassword(pss['password'], request.environ['REMOTE_ADDR']): return os.environ.get('PASSWORD_MESSAGE') else: return 'quePasoAmiguitoxdxd' else: return '¿?' #Recalls the failed log attemps of devMode @app.route('/devMode/recall/logAttempts', methods = ['POST']) def recallLogAttempts(): pss = request.get_json() or request.form if checkPassword(pss['password'], request.environ['REMOTE_ADDR']): try: return __str__(r.lrange('devModeGetList', 0, -1)).decode('utf-8') except Exception as error: return formatError(error) else: return 'la pulenta oe' #Checks for password and logs failed attempts def checkPassword(password, ip): date = str(datetime.datetime.utcnow()) attempt = password == os.environ.get('REDIS_URL') if not attempt: r.lpush('devModeGetList', "*IP: " + ip + " // " + "Timestamp: " + date + " // Attempt: " + password + "\n") return attempt #Format function to redis errors def formatError(error): msg = 'Type: ' + type(error) + '\n' msg += 'Exception: ' + error return msg
import os import redis import logging import datetime from flask import Flask , send_from_directory, render_template, url_for, request r = redis.from_url(os.environ.get("REDIS_URL")) app = Flask(__name__) #"Landing page" @app.route('/') def webprint(): return render_template('index.html') #Saves the string <strng> in the DB @app.route('/db/<strng>') def saveInDB(strng): r.lpush('db', '%s' % strng) return 'OK' #Recalls the stored info in the DB @app.route('/db/recall/test', methods = ['GET']) def recallDB(): try: return str(r.lrange('db', 0, -1)).decode('utf-8') except Exception as error: return formatError(error) #DevMode Handling------------------------------------ #Returns devMode.html [GET] #Checks login credentials [POST] @app.route('/devMode', methods = ['POST', 'GET']) def devMode(): if request.method == 'GET': r.incr('devModeGet') return render_template('devMode.html') elif request.method == 'POST': pss = request.get_json() or request.form if checkPassword(pss['password'], request.environ['REMOTE_ADDR']): return os.environ.get('PASSWORD_MESSAGE') else: return 'quePasoAmiguitoxdxd' else: return '¿?' #Recalls the failed log attemps of devMode @app.route('/devMode/recall/logAttempts', methods = ['POST']) def recallLogAttempts(): pss = request.get_json() or request.form if checkPassword(pss['password'], request.environ['REMOTE_ADDR']): try: return str(r.lrange('devModeGetList', 0, -1)).decode('utf-8') except Exception as error: return formatError(error) else: return 'la pulenta oe' #Checks for password and logs failed attempts def checkPassword(password, ip): date = str(datetime.datetime.utcnow()) attempt = password == os.environ.get('REDIS_URL') if not attempt: r.lpush('devModeGetList', "*IP: " + ip + " // " + "Timestamp: " + date + " // Attempt: " + password + "\n") return attempt #Format function to redis errors def formatError(error): msg = 'Type: ' + type(error) + '\n' msg += 'Exception: ' + error return msg
mit
Python
9664aac88684bfd2b940a8189d95ba7797c6ddd3
add moveTo method
tarukosu/RoombaRPC,tarukosu/RoombaRPC,tarukosu/RoombaRPC
server.py
server.py
import roomba.create as create import time import zerorpc class RoombaRPC(object): def __init__(self, port): self.robot = create.Create(port) self.robot.toSafeMode() self.moving = False self.pause() def __del__(self): self.robot.close() def toSafeMode(self): self.robot.toSafeMode() def pause(self): if self.moving: self.move(0, 0) self.moving = False def move(self, x, theta): print("move: %f, %f" % (x, theta)) self.robot.go(x, theta) self.moving = True def moveTo(self, x, theta): max_x = 20 # max: 500 mm/s max_theta = 40 # max: 2000 mm self.move(x * max_x, theta * max_theta) if __name__=='__main__': RPC_PORT = 6000 ROOMBA_PORT = "/dev/ttyUSB0" s = zerorpc.Server(RoombaRPC(ROOMBA_PORT)) s.bind("tcp://0.0.0.0:{0}".format(RPC_PORT)) s.run()
import roomba.create as create import time import zerorpc class RoombaRPC(object): def __init__(self, port): self.robot = create.Create(port) self.robot.toSafeMode() self.moving = False self.pause() def __del__(self): self.robot.close() def toSafeMode(self): self.robot.toSafeMode() def pause(self): if self.moving: self.move(0, 0) self.moving = False def move(self, x, theta): print("move: %f, %f" % (x, theta)) self.robot.go(x, theta) self.moving = True if __name__=='__main__': RPC_PORT = 6000 ROOMBA_PORT = "/dev/ttyUSB0" s = zerorpc.Server(RoombaRPC(ROOMBA_PORT)) s.bind("tcp://0.0.0.0:{0}".format(RPC_PORT)) s.run()
mit
Python
9fa51ff158c6628992285d85d808687116473626
fix bug
housne/tucao,devharrry/tucao,housne/tucao,devharrry/tucao,devharrry/tucao,housne/tucao
server.py
server.py
#-*- coding:utf-8 -*- from flask import Flask, jsonify, render_template, make_response, request import os from news import News from conf import * from fetch import Fetch import time import datetime app = Flask(__name__, static_url_path='/assets') def jsonResponse(data=None, type=None, extra_data=[]): response = {} status = 200 if type == None: response['code'] = 0 response['result'] = data if(extra_data): [response.update(data) for data in extra_data] elif type == '404': status = 404 response = {"code": 404, "message": "Not Found"} elif type == '500': status = 500 response = {"code": 500, "message": "Server Eroor"} response = jsonify(response) response.status_code = status return response @app.route('/api/news') def index(): news = News() page = request.args.get('page') if page is None: page = 1 data = news.list(page=int(page)) total = news.count() if data is None: return jsonResponse(type='404') for i, item in enumerate(data): data[i]['date'] = time.mktime(item['date'].timetuple()) return jsonResponse(data=data, extra_data=[{'total': total}]) @app.route('/api/news/<int:id>') def news(id): news = News(news_id=id) data = news.get() if data is None: return jsonResponse(type='404') return jsonResponse(data=data) @app.route('/rss') def rss(): news = News() data = news.sort() response = make_response(render_template('rss.xml', data=data, site_url=site_url)) response.headers['Content-Type'] = 'application/atom+xml; charset=utf-8' return response @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': fetch = Fetch() fetch.start() app.run()
#-*- coding:utf-8 -*- from flask import Flask, jsonify, render_template, make_response, request import os from news import News from conf import * from fetch import Fetch from cache import Cache import time import datetime app = Flask(__name__, static_url_path='/assets') def jsonResponse(data=None, type=None, extra_data=[]): response = {} status = 200 if type == None: response['code'] = 0 response['result'] = data if(extra_data): [response.update(data) for data in extra_data] elif type == '404': status = 404 response = {"code": 404, "message": "Not Found"} elif type == '500': status = 500 response = {"code": 500, "message": "Server Eroor"} response = jsonify(response) response.status_code = status return response @app.route('/api/news') def index(): news = News() page = request.args.get('page') if page is None: page = 1 data = news.list(page=int(page)) total = news.count() if data is None: return jsonResponse(type='404') for i, item in enumerate(data): data[i]['date'] = time.mktime(item['date'].timetuple()) return jsonResponse(data=data, extra_data=[{'total': total}]) @app.route('/api/news/<int:id>') def news(id): news = News(news_id=id) data = news.get() if data is None: return jsonResponse(type='404') return jsonResponse(data=data) @app.route('/rss') def rss(): news = News() data = news.sort() response = make_response(render_template('rss.xml', data=data, site_url=site_url)) response.headers['Content-Type'] = 'application/atom+xml; charset=utf-8' return response @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': fetch = Fetch() fetch.start() app.run()
mit
Python
fb8c2fb065449a436dd8ffa11b469bb2f22a9ad1
Add web crawling rule and dataset url regex exp
MaxLikelihood/CODE
spider.py
spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')]
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
mit
Python
477bdb98f8a3e8250de80e1c88b4cab85a82e7ab
Implement bi-directional DiagnosticPort_Formatter
bvanheu/stratasys
stratasys/formatter.py
stratasys/formatter.py
# # See the LICENSE file # import re import binascii class Formatter: def __init__(self): pass def from_source(self, data): raise Exception("this class cannot be used") def to_destination(self, data): raise Exception("this class cannot be used") class DiagnosticPort_Formatter(Formatter): def __init__(self): self.rx = re.compile('^[0-9]{6}: ((?:[0-9a-f-A-F]{2} ?)+).*?$',re.MULTILINE) def from_source(self, data): formatted = b'' idx = 1 for match in self.rx.finditer(data): try: #Get a line of data with whitespace removed line = match.group(1).replace(' ', '') formatted += binascii.unhexlify(line) idx=idx+1 except IndexError: print("Error on line %s when reading diag port formatted data" % (idx,)) raise return formatted def to_destination(self, data): formatted = "\"" for b in data: formatted += binascii.hexlify(b) + " " return formatted[0:-1] + "\""
# # See the LICENSE file # class Formatter: def __init__(self): pass def from_source(self, data): raise Exception("this class cannot be used") def to_destination(self, data): raise Exception("this class cannot be used") class DiagnosticPort_Formatter(Formatter): def __init__(self): pass def from_source(self, data): formatted = "" # TODO - implements me return formatted def to_destination(self, data): formatted = "" for b in data: formatted += binascii.hexlify(b) + ", " return formatted[0:-2]
bsd-3-clause
Python
7cc4069899979719ba0399ae5e9e597a88ede774
enhance celery error handling
sergeii/swat4stats.com,sergeii/swat4stats.com,sergeii/swat4stats.com
swat4tracker/celery.py
swat4tracker/celery.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import os from django.conf import settings import celery import raven from celery.signals import setup_logging from raven.contrib.celery import register_signal, register_logger_signal os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swat4tracker.settings') @setup_logging.connect def configure_logging(sender=None, **kwargs): """ Stop celery from hijacking loggers. https://github.com/celery/celery/issues/1867 """ pass class Celery(celery.Celery): def on_configure(self): if 'raven.contrib.django.raven_compat' in settings.INSTALLED_APPS: client = raven.Client(settings.RAVEN_CONFIG['dsn']) # register a custom filter to filter out duplicate logs register_logger_signal(client) # hook into the Celery error handler register_signal(client) app = Celery('swat4tracker') app.config_from_object(settings) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import os from django.conf import settings import celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swat4tracker.settings') app = celery.Celery('swat4tracker') app.config_from_object(settings) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
mit
Python
6bc2bf86634f056f064a6bef2cdc00b3750556c1
remove import utils file
adnedelcu/SyncSettings,mfuentesg/SyncSettings
sync_settings/reloader.py
sync_settings/reloader.py
# -*- coding: utf-8 -*- # Adapted from @wbond's resource loader. import sys import sublime VERSION = int(sublime.version()) mod_prefix = "sync_settings" reload_mods = [] if VERSION > 3000: mod_prefix = "AdvancedNewFile." + mod_prefix from imp import reload for mod in sys.modules: if mod[0:15] == 'SyncSettings' and sys.modules[mod] is not None: reload_mods.append(mod) else: for mod in sorted(sys.modules): if mod[0:17] == 'sync_settings' and sys.modules[mod] is not None: reload_mods.append(mod) mods_load_order = [ '', '.gistapi', '.sync_settings_manager', ".commands", ".commands.create_and_upload", ".commands.download", ".commands.upload" ".requests" ] for suffix in mods_load_order: mod = mod_prefix + suffix if mod in reload_mods: reload(sys.modules[mod])
# -*- coding: utf-8 -*- # Adapted from @wbond's resource loader. import sys import sublime VERSION = int(sublime.version()) mod_prefix = "sync_settings" reload_mods = [] if VERSION > 3000: mod_prefix = "AdvancedNewFile." + mod_prefix from imp import reload for mod in sys.modules: if mod[0:15] == 'SyncSettings' and sys.modules[mod] is not None: reload_mods.append(mod) else: for mod in sorted(sys.modules): if mod[0:17] == 'sync_settings' and sys.modules[mod] is not None: reload_mods.append(mod) mods_load_order = [ '', '.gistapi', '.utils', '.sync_settings_manager', ".commands", ".commands.create_and_upload", ".commands.download", ".commands.upload" ".requests" ] for suffix in mods_load_order: mod = mod_prefix + suffix if mod in reload_mods: reload(sys.modules[mod])
mit
Python
68034e4d428776ac3fb3fcfa4ee8a53b4f5714a6
Declare readline dependency (#4171)
matthiasdiener/spack,LLNL/spack,TheTimmy/spack,mfherbst/spack,TheTimmy/spack,tmerrick1/spack,LLNL/spack,krafczyk/spack,LLNL/spack,LLNL/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,mfherbst/spack,lgarren/spack,tmerrick1/spack,lgarren/spack,krafczyk/spack,iulian787/spack,TheTimmy/spack,tmerrick1/spack,skosukhin/spack,skosukhin/spack,LLNL/spack,krafczyk/spack,krafczyk/spack,EmreAtes/spack,matthiasdiener/spack,EmreAtes/spack,lgarren/spack,matthiasdiener/spack,skosukhin/spack,iulian787/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,matthiasdiener/spack,iulian787/spack,lgarren/spack,TheTimmy/spack,lgarren/spack,EmreAtes/spack,tmerrick1/spack,tmerrick1/spack,EmreAtes/spack,skosukhin/spack,skosukhin/spack,mfherbst/spack,mfherbst/spack,mfherbst/spack
var/spack/repos/builtin/packages/gdbm/package.py
var/spack/repos/builtin/packages/gdbm/package.py
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the LICENSE file for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## # from spack import * class Gdbm(AutotoolsPackage): """GNU dbm (or GDBM, for short) is a library of database functions that use extensible hashing and work similar to the standard UNIX dbm. These routines are provided to a programmer needing to create and manipulate a hashed database.""" homepage = "http://www.gnu.org.ua/software/gdbm/gdbm.html" url = "ftp://ftp.gnu.org/gnu/gdbm/gdbm-1.13.tar.gz" version('1.13', '8929dcda2a8de3fd2367bdbf66769376') version('1.12', '9ce96ff4c99e74295ea19040931c8fb9') version('1.11', '72c832680cf0999caedbe5b265c8c1bd') version('1.10', '88770493c2559dc80b561293e39d3570') version('1.9.1', '59f6e4c4193cb875964ffbe8aa384b58') version('1.9', '1f0e8e6691edd61bdd6b697b8c02528d') depends_on("readline") def configure_args(self): return ['--enable-libgdbm-compat']
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the LICENSE file for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## # from spack import * class Gdbm(AutotoolsPackage): """GNU dbm (or GDBM, for short) is a library of database functions that use extensible hashing and work similar to the standard UNIX dbm. These routines are provided to a programmer needing to create and manipulate a hashed database.""" homepage = "http://www.gnu.org.ua/software/gdbm/gdbm.html" url = "ftp://ftp.gnu.org/gnu/gdbm/gdbm-1.13.tar.gz" version('1.13', '8929dcda2a8de3fd2367bdbf66769376') version('1.12', '9ce96ff4c99e74295ea19040931c8fb9') version('1.11', '72c832680cf0999caedbe5b265c8c1bd') version('1.10', '88770493c2559dc80b561293e39d3570') version('1.9.1', '59f6e4c4193cb875964ffbe8aa384b58') version('1.9', '1f0e8e6691edd61bdd6b697b8c02528d') def configure_args(self): return ['--enable-libgdbm-compat']
lgpl-2.1
Python
b18fea6c8314da46b5e7b8fc58f404bb4623e4ef
add new versions (#9477)
iulian787/spack,iulian787/spack,LLNL/spack,LLNL/spack,iulian787/spack,LLNL/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack
var/spack/repos/builtin/packages/ncdu/package.py
var/spack/repos/builtin/packages/ncdu/package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Ncdu(Package): """Ncdu is a disk usage analyzer with an ncurses interface. It is designed to find space hogs on a remote server where you don't have an entire gaphical setup available, but it is a useful tool even on regular desktop systems. Ncdu aims to be fast, simple and easy to use, and should be able to run in any minimal POSIX-like environment with ncurses installed. """ homepage = "http://dev.yorhel.nl/ncdu" url = "http://dev.yorhel.nl/download/ncdu-1.11.tar.gz" version('1.13', sha256='f4d9285c38292c2de05e444d0ba271cbfe1a705eee37c2b23ea7c448ab37255a') version('1.12', sha256='820e4e4747a2a2ec7a2e9f06d2f5a353516362c22496a10a9834f871b877499a') version('1.11', '9e44240a5356b029f05f0e70a63c4d12') version('1.10', '7535decc8d54eca811493e82d4bfab2d') version('1.9', '93258079db897d28bb8890e2db89b1fb') version('1.8', '94d7a821f8a0d7ba8ef3dd926226f7d5') version('1.7', '172047c29d232724cc62e773e82e592a') depends_on("ncurses") def install(self, spec, prefix): configure('--prefix=%s' % prefix, '--with-ncurses=%s' % spec['ncurses']) make() make("install")
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Ncdu(Package): """Ncdu is a disk usage analyzer with an ncurses interface. It is designed to find space hogs on a remote server where you don't have an entire gaphical setup available, but it is a useful tool even on regular desktop systems. Ncdu aims to be fast, simple and easy to use, and should be able to run in any minimal POSIX-like environment with ncurses installed. """ homepage = "http://dev.yorhel.nl/ncdu" url = "http://dev.yorhel.nl/download/ncdu-1.11.tar.gz" version('1.11', '9e44240a5356b029f05f0e70a63c4d12') version('1.10', '7535decc8d54eca811493e82d4bfab2d') version('1.9', '93258079db897d28bb8890e2db89b1fb') version('1.8', '94d7a821f8a0d7ba8ef3dd926226f7d5') version('1.7', '172047c29d232724cc62e773e82e592a') depends_on("ncurses") def install(self, spec, prefix): configure('--prefix=%s' % prefix, '--with-ncurses=%s' % spec['ncurses']) make() make("install")
lgpl-2.1
Python
8ef81870bb1f282caecc51a2de7c2c0ba9bf204d
create leave ledger entry for encashment
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
erpnext/hr/doctype/leave_encashment/test_leave_encashment.py
erpnext/hr/doctype/leave_encashment/test_leave_encashment.py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import today, add_months from erpnext.hr.doctype.employee.test_employee import make_employee from erpnext.hr.doctype.salary_structure.test_salary_structure import make_salary_structure from erpnext.hr.doctype.leave_period.test_leave_period import create_leave_period from erpnext.hr.doctype.leave_policy.test_leave_policy import create_leave_policy\ test_dependencies = ["Leave Type"] class TestLeaveEncashment(unittest.TestCase): def setUp(self): frappe.db.sql('''delete from `tabLeave Period`''') frappe.db.sql('''delete from `tabLeave Allocation`''') # create the leave policy leave_policy = create_leave_policy( leave_type="_Test Leave Type Encashment", annual_allocation=10) leave_policy.submit() # create employee, salary structure and assignment self.employee = make_employee("test_employee_encashment@example.com") frappe.db.set_value("Employee", "test_employee_encashment@example.com", "leave_policy", leave_policy.name) salary_structure = make_salary_structure("Salary Structure for Encashment", "Monthly", self.employee, other_details={"leave_encashment_amount_per_day": 50}) # create the leave period and assign the leaves self.leave_period = create_leave_period(add_months(today(), -3), add_months(today(), 3)) self.leave_period.grant_leave_allocation(employee=self.employee) def test_leave_balance_value_and_amount(self): frappe.db.sql('''delete from `tabLeave Encashment`''') leave_encashment = frappe.get_doc(dict( doctype = 'Leave Encashment', employee = self.employee, leave_type = "_Test Leave Type Encashment", leave_period = self.leave_period.name, payroll_date = today() )).insert() self.assertEqual(leave_encashment.leave_balance, 10) self.assertEqual(leave_encashment.encashable_days, 5) self.assertEqual(leave_encashment.encashment_amount, 250) leave_encashment.submit() self.assertTrue(frappe.db.get_value("Leave Encashment", leave_encashment.name, "additional_salary")) def test_creation_of_leave_ledger_entry_on_submit(self): frappe.db.sql('''delete from `tabLeave Encashment`''') leave_encashment = frappe.get_doc(dict( doctype = 'Leave Encashment', employee = self.employee, leave_type = "_Test Leave Type Encashment", leave_period = self.leave_period.name, payroll_date = today() )).insert() leave_encashment.submit() leave_ledger_entry = frappe.get_all('Leave Ledger Entry', fields='*', filters=dict(transaction_name=leave_encashment.name)) self.assertEquals(len(leave_ledger_entry), 1) self.assertEquals(leave_ledger_entry[0].employee, leave_encashment.employee) self.assertEquals(leave_ledger_entry[0].leave_type, leave_encashment.leave_type) self.assertEquals(leave_ledger_entry[0].leaves, leave_encashment.encashable_days * -1) # check if leave ledger entry is deleted on cancellation leave_encashment.cancel() self.assertFalse(frappe.db.exists("Leave Ledger Entry", {'transaction_name':leave_encashment.name}))
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import today, add_months from erpnext.hr.doctype.employee.test_employee import make_employee from erpnext.hr.doctype.salary_structure.test_salary_structure import make_salary_structure from erpnext.hr.doctype.leave_period.test_leave_period import create_leave_period test_dependencies = ["Leave Type"] class TestLeaveEncashment(unittest.TestCase): def setUp(self): frappe.db.sql('''delete from `tabLeave Period`''') def test_leave_balance_value_and_amount(self): employee = "test_employee_encashment@salary.com" leave_type = "_Test Leave Type Encashment" # create the leave policy leave_policy = frappe.get_doc({ "doctype": "Leave Policy", "leave_policy_details": [{ "leave_type": leave_type, "annual_allocation": 10 }] }).insert() leave_policy.submit() # create employee, salary structure and assignment employee = make_employee(employee) frappe.db.set_value("Employee", employee, "leave_policy", leave_policy.name) salary_structure = make_salary_structure("Salary Structure for Encashment", "Monthly", employee, other_details={"leave_encashment_amount_per_day": 50}) # create the leave period and assign the leaves leave_period = create_leave_period(add_months(today(), -3), add_months(today(), 3)) leave_period.grant_leave_allocation(employee=employee) leave_encashment = frappe.get_doc(dict( doctype = 'Leave Encashment', employee = employee, leave_type = leave_type, leave_period = leave_period.name, payroll_date = today() )).insert() self.assertEqual(leave_encashment.leave_balance, 10) self.assertEqual(leave_encashment.encashable_days, 5) self.assertEqual(leave_encashment.encashment_amount, 250) leave_encashment.submit() self.assertTrue(frappe.db.get_value("Leave Encashment", leave_encashment.name, "additional_salary"))
agpl-3.0
Python
e010175f9514b778e832fea3144c78c31c6ac965
remove abandoned todo
buxx/intelligine
intelligine/simulation/object/brain/part/move/AntStar/Host.py
intelligine/simulation/object/brain/part/move/AntStar/Host.py
from intelligine.simulation.object.brain.part.move.AntStar.HostFeeler import HostFeeler from intelligine.synergy.event.move.direction import get_position_with_direction_decal from synergine_xyz.cst import POSITION class Host: def __init__(self, context, object_id): self._context = context self._object_id = object_id self._feeler = HostFeeler(context, object_id) self._moved_to_direction = None self._position_3d = self._context.metas.value.get(POSITION, self._object_id) def get_position(self): return self._position_3d[1], self._position_3d[2] def get_feeler(self): return self._feeler def move_to(self, direction): self._moved_to_direction = direction self._position_3d = get_position_with_direction_decal(direction, self._position_3d) def get_moved_to_direction(self): return self._moved_to_direction
from intelligine.simulation.object.brain.part.move.AntStar.HostFeeler import HostFeeler from intelligine.synergy.event.move.direction import get_position_with_direction_decal from synergine_xyz.cst import POSITION class Host: def __init__(self, context, object_id): self._context = context self._object_id = object_id self._feeler = HostFeeler(context, object_id) self._moved_to_direction = None self._position_3d = self._context.metas.value.get(POSITION, self._object_id) def get_position(self): return self._position_3d[1], self._position_3d[2] def get_feeler(self): return self._feeler def move_to(self, direction): # TODO: Heriter de Host AntStar au lieu de tout repeter ici ... self._moved_to_direction = direction self._position_3d = get_position_with_direction_decal(direction, self._position_3d) def get_moved_to_direction(self): return self._moved_to_direction
apache-2.0
Python
541a2b49ac80800912a4bd867cbddc56d245fa25
configure logging (#6873)
cseed/hail,hail-is/hail,hail-is/hail,danking/hail,danking/hail,danking/hail,cseed/hail,hail-is/hail,cseed/hail,danking/hail,hail-is/hail,cseed/hail,hail-is/hail,danking/hail,hail-is/hail,cseed/hail,cseed/hail,hail-is/hail,danking/hail,danking/hail,cseed/hail,danking/hail,hail-is/hail,cseed/hail
batch/batch/__main__.py
batch/batch/__main__.py
from aiohttp import web from hailtop import gear from .batch import app gear.configure_logging() web.run_app(app, host='0.0.0.0', port=5000)
from aiohttp import web from .batch import app web.run_app(app, host='0.0.0.0', port=5000)
mit
Python
a7d15651fcf6ff75c1330a8d568f0d77d521ef8f
update refit auto-test
mick-d/nipype,mick-d/nipype,mick-d/nipype,mick-d/nipype
nipype/interfaces/afni/tests/test_auto_Refit.py
nipype/interfaces/afni/tests/test_auto_Refit.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..utils import Refit def test_Refit_inputs(): input_map = dict(args=dict(argstr='%s', ), atrcopy=dict(argstr='-atrcopy %s %s', ), atrfloat=dict(argstr='-atrfloat %s %s', ), atrint=dict(argstr='-atrint %s %s', ), atrstring=dict(argstr='-atrstring %s %s', ), deoblique=dict(argstr='-deoblique', ), duporigin_file=dict(argstr='-duporigin %s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='%s', copyfile=True, mandatory=True, position=-1, ), nosaveatr=dict(argstr='-nosaveatr', ), saveatr=dict(argstr='-saveatr', ), space=dict(argstr='-space %s', ), terminal_output=dict(nohash=True, ), xdel=dict(argstr='-xdel %f', ), xorigin=dict(argstr='-xorigin %s', ), ydel=dict(argstr='-ydel %f', ), yorigin=dict(argstr='-yorigin %s', ), zdel=dict(argstr='-zdel %f', ), zorigin=dict(argstr='-zorigin %s', ), ) inputs = Refit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_Refit_outputs(): output_map = dict(out_file=dict(), ) outputs = Refit.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..utils import Refit def test_Refit_inputs(): input_map = dict(args=dict(argstr='%s', ), deoblique=dict(argstr='-deoblique', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='%s', copyfile=True, mandatory=True, position=-1, ), space=dict(argstr='-space %s', ), terminal_output=dict(nohash=True, ), xdel=dict(argstr='-xdel %f', ), xorigin=dict(argstr='-xorigin %s', ), ydel=dict(argstr='-ydel %f', ), yorigin=dict(argstr='-yorigin %s', ), zdel=dict(argstr='-zdel %f', ), zorigin=dict(argstr='-zorigin %s', ), ) inputs = Refit.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_Refit_outputs(): output_map = dict(out_file=dict(), ) outputs = Refit.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
bsd-3-clause
Python
e25fcef7f137752f80b0740cf1f9536ad9b6c2b0
Add retrieval of career goal leaders
leaffan/pynhldb
analysis/_goal_leaders.py
analysis/_goal_leaders.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests from lxml import html SEASON_URL_TEMPLATE = "http://www.hockey-reference.com/leagues/NHL_%d.html" CAREER_GOAL_LEADERS_URL = "http://www.hockey-reference.com/leaders/goals_career.html" def retrieve_yearly_leaders(): """ Retrieves yearly NHL goal-scoring leaders. """ yearly_leaders = set() # retrieving leading goal scorers for each NHL first for year in range(1918, 2017)[:]: # skipping season completely lost to a lockout if year == 2005: continue season = "%d-%s" % (year - 1, str(year)[-2:]) print("+ Retrieving top goal scorers for season %s" % season) # retrieving raw html data and parsing it url = SEASON_URL_TEMPLATE % year r = requests.get(url) doc = html.fromstring(r.text) # the stuff we're interested in is hidden in comments comments = doc.xpath("//comment()") for comment in comments: # removing comment markup sub = html.fromstring(str(comment)[3:-3]) if not sub.xpath("//table/caption/text()"): continue if sub.xpath("//table/caption/text()")[0] == "Goals": leaders = sub break # retrieving five best goalscorers in current season as list five_goal_leaders = leaders.xpath( "//div[@id='leaders_goals']/table/tr/td[@class='who']/a") # adding name and link to player page to goalscorer dictionary for leader in five_goal_leaders: print("\t%s" % leader.xpath("text()")[0]) yearly_leaders.add( (leader.xpath("@href")[0], leader.xpath("text()")[0])) return yearly_leaders def retrieve_career_leaders(min_goals): """ Retrieves NHL career goal scoring leaders with at least the number of specified goals. """ career_leaders = set() r = requests.get(CAREER_GOAL_LEADERS_URL) doc = html.fromstring(r.text) # retrieving goal scorers with more than 300 career goals for leader_row in doc.xpath("//table[@id='stats_career_NHL']/tbody/tr"): goals = int(leader_row.xpath( "td[4]/text()")[0]) if goals >= min_goals: print(leader_row.xpath("td//a/text()")[0]) career_leaders.add(( leader_row.xpath("td//a/@href")[0], leader_row.xpath("td//a/text()")[0])) return career_leaders if __name__ == '__main__': yearly_leaders = retrieve_yearly_leaders() career_leaders = retrieve_career_leaders(300) goal_leaders = yearly_leaders.union(career_leaders) open(r"nhl_goals_leaders.json", 'w').write( json.dumps(list(goal_leaders), sort_keys=True, indent=2))
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from lxml import html SEASON_URL_TEMPLATE = "http://www.hockey-reference.com/leagues/NHL_%d.html" CAREER_GOAL_LEADERS_URL = "http://www.hockey-reference.com/leaders/goals_career.html" season_goal_leaders = set() for year in range(1918, 2017)[:0]: # skipping season completely lost to a lockout if year == 2005: continue season = "%d-%s" % (year - 1, str(year)[-2:]) # retrieving raw html data and parsing it url = SEASON_URL_TEMPLATE % year r = requests.get(url) doc = html.fromstring(r.text) # the stuff we're interested in is hidden in comments comments = doc.xpath("//comment()") for comment in comments: # removing comment markup sub = html.fromstring(str(comment)[3:-3]) if not sub.xpath("//table/caption/text()"): continue if sub.xpath("//table/caption/text()")[0] == "Goals": leaders = sub break # retrieving five best goalscorers in current season as list five_goal_leaders = leaders.xpath( "//div[@id='leaders_goals']/table/tr/td[@class='who']/a") # adding name and link to player page to goalscorer dictionary for leader in five_goal_leaders: season_goal_leaders.add( (leader.xpath("@href")[0], leader.xpath("text()")[0])) r = requests.get(CAREER_GOAL_LEADERS_URL) doc = html.fromstring(r.text) print(sorted(season_goal_leaders))
mit
Python
fc569f99501f5a7a33c861730132657abfcb642c
Update decompression.py
HugoPouliquen/lzw-tools
utils/decompression.py
utils/decompression.py
from os.path import splitext from os.path import getsize from utils.make_list import byteList def decompress(compressed, path): """ Purpose: Decompress file Description: Read the file to decompress, remove the fist couple of byte. Then, decompress each byte using the ASCII list. Finally convert it into 1 bytes and write each decompress sequence to the file. Param: Path of file to compress Return: Name of the file in param .txt (for the moment) """ list_ascii, list_ascii_size = byteList() uncompressed = [] i = 0 filename, file_extension = splitext(path) f = open(filename + '2.txt', 'wb') w = compressed[0] compressed.remove(compressed[0]) f.write(w) for byte_element in compressed: int_element = int.from_bytes(byte_element, byteorder='big') if int_element < list_ascii_size: entry = list_ascii[int_element] elif int_element == list_ascii_size: entry = w + w else: raise ValueError('Bad uncompressed for: %s' % byte_element) for byte in entry: if i % 2 == 1: f.write(byte.to_bytes(1, byteorder='big')) i += 1 list_ascii.insert(list_ascii_size, w + byte_element) list_ascii_size += 1 w = entry f.close() return filename + '2.txt' def fileDecompression(path): """ Purpose: Decompress a file Description: Open a file in read and byte mode. Put each group of two byte in an array. Param: Path of file to decompress Return: Decompressed content file """ f = open(path, "rb") content = [] for i in range(int(getsize(path)/2)): content.insert(i, f.read(2)) f.close() return decompress(content, path)
from os.path import splitext from os.path import getsize from utils.make_list import byteList def decompress(compressed, path): """ Purpose: Decompress file Description: Read the file to decompress, remove the fist couple of byte. Then, decompress each byte using the ASCII list and convert it into 2 bytes. ??? . And finally write the decompress sequence to the file. Param: Path of file to compress Return: Name of the file in param .txt (for the moment) """ list_ascii, list_ascii_size = byteList() uncompressed = [] i = 0 filename, file_extension = splitext(path) f = open(filename + '2.txt', 'wb') w = compressed[0] compressed.remove(compressed[0]) f.write(w) for byte_element in compressed: int_element = int.from_bytes(byte_element, byteorder='big') if int_element < list_ascii_size: entry = list_ascii[int_element] elif int_element == list_ascii_size: entry = w + w else: raise ValueError('Bad uncompressed for: %s' % byte_element) for byte in entry: if i % 2 == 1: f.write(byte.to_bytes(1, byteorder='big')) i += 1 list_ascii.insert(list_ascii_size, w + byte_element) list_ascii_size += 1 w = entry f.close() return filename + '2.txt' def fileDecompression(path): """ Purpose: Decompresse a file Description: Open a file in read and byte mode. Put each group of two byte in an array. Param: Path of file to decompress Return: Decompressed content file """ f = open(path, "rb") content = [] for i in range(int(getsize(path)/2)): content.insert(i, f.read(2)) f.close() return decompress(content, path)
mit
Python
25751d5814e5afa896dcce0823490bdb893b513f
comment out the enabling of local cache. Local cache is disabled by default.
jmakov/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,vladan-m/ggrc-core,uskudnik/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,hasanalom/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,vladan-m/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,uskudnik/ggrc-core,vladan-m/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,hyperNURb/ggrc-core,j0gurt/ggrc-core,hyperNURb/ggrc-core,prasannav7/ggrc-core,prasannav7/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,uskudnik/ggrc-core,hasanalom/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,selahssea/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core
src/ggrc/cache/factory.py
src/ggrc/cache/factory.py
# cache/factory.py # # This module creates the cache based on parameters specified # # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # # Maintained By: dan@reciprocitylabs.com # from .localcache import LocalCache from .memcache import MemCache class Factory: def __init__(self): pass def create(self, name, arguments=None): if "memcache" in name : return MemCache(); else: return None
# cache/factory.py # # This module creates the cache based on parameters specified # # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # # Maintained By: dan@reciprocitylabs.com # from .localcache import LocalCache from .memcache import MemCache class Factory: def __init__(self): pass def create(self, name, arguments=None): if "local" in name : return LocalCache(); elif "memcache" in name : return MemCache(); else: return None
apache-2.0
Python
f461180a9c1f5d578372baa6cc1e9deac3c27994
update bmp180
crazyquark/tentacle_pi,lexruee/tentacle_pi
bmp180/examples/test.py
bmp180/examples/test.py
from tentacle_pi.BMP180 import BMP180 import time bmp = BMP180(0x77,"/dev/i2c-1") for x in range(0,100): print "temperature: %0.1f" % bmp.temperature() print "pressure: %s" % bmp.pressure() print "altitude: %0.1f" % bmp.altitude() print time.sleep(2)
from tentacle_pi.BMP180 import BMP180 import time bmp = BMP180(0x77,"/dev/i2c-1") for x in range(0,5): print "temperature: %s" % bmp.temperature() print "pressure: %s" % bmp.pressure() print "altitude: %s" % bmp.altitude() print time.sleep(2)
mit
Python
77eab288ae870f35922a44d0f22e479c62dad1dc
Use correct byte count function
smartfile/client-python
test/test_smartfile.py
test/test_smartfile.py
from __future__ import absolute_import import os import unittest try: from StringIO import StringIO except ImportError: from io import StringIO from smartfile import BasicClient from smartfile.errors import ResponseError API_KEY = os.environ.get("API_KEY") API_PASSWORD = os.environ.get("API_PASSWORD") if API_KEY is None: raise RuntimeError("API_KEY is required") if API_PASSWORD is None: raise RuntimeError("API_PASSWORD is required") TESTFN = "testfn" file_contents = "hello" TESTFN2 = "testfn2" class CustomOperationsTestCase(unittest.TestCase): def setUp(self): self.api = BasicClient(API_KEY, API_PASSWORD) # Make directory for tests self.api.post('/path/oper/mkdir/', path=TESTFN2) def get_data(self): data = self.api.get("/path/info/testfn") return data def tearDown(self): self.api.remove('/testfn2') os.remove('testfn') def upload(self): f = StringIO(file_contents) f.seek(0) self.api.upload(TESTFN, f) self.assertEquals(self.get_data()['size'], f.tell()) def download(self): self.api.download(TESTFN) self.assertEquals(self.get_data()['size'], os.path.getsize(TESTFN)) def move(self): self.api.move(TESTFN, TESTFN2) def remove(self): self.api.remove(os.path.join(TESTFN2, TESTFN)) with self.assertRaises(ResponseError): self.api.remove(os.path.join(TESTFN2, TESTFN)) def test_upload_download_move_delete(self): self.upload() self.download() self.move() self.remove()
from __future__ import absolute_import import os import unittest try: from StringIO import StringIO except ImportError: from io import StringIO from smartfile import BasicClient from smartfile.errors import ResponseError API_KEY = os.environ.get("API_KEY") API_PASSWORD = os.environ.get("API_PASSWORD") if API_KEY is None: raise RuntimeError("API_KEY is required") if API_PASSWORD is None: raise RuntimeError("API_PASSWORD is required") TESTFN = "testfn" file_contents = "hello" TESTFN2 = "testfn2" class CustomOperationsTestCase(unittest.TestCase): def setUp(self): self.api = BasicClient(API_KEY, API_PASSWORD) # Make directory for tests self.api.post('/path/oper/mkdir/', path=TESTFN2) def get_data(self): data = self.api.get("/path/info/testfn") return data def tearDown(self): self.api.remove('/testfn2') os.remove('testfn') def upload(self): f = StringIO(file_contents) f.seek(0) self.api.upload(TESTFN, f) self.assertEquals(self.get_data()['size'], f.len) def download(self): self.api.download(TESTFN) self.assertEquals(self.get_data()['size'], os.path.getsize(TESTFN)) def move(self): self.api.move(TESTFN, TESTFN2) def remove(self): self.api.remove(os.path.join(TESTFN2, TESTFN)) with self.assertRaises(ResponseError): self.api.remove(os.path.join(TESTFN2, TESTFN)) def test_upload_download_move_delete(self): self.upload() self.download() self.move() self.remove()
mit
Python
fb4341a100e62fa0ca82ebb81fb489b0fc63a465
Fix tests for Py3
ecordell/burninator
tests/burninator_tests.py
tests/burninator_tests.py
from mock import * from nose.tools import * from burninator import Burninator try: import builtins patch_string = 'builtins.print' except ImportError: import __builtin__ patch_string = '__builtin__.print' class TestBurninator(object): def setup(self): self.burninator = Burninator() def test_burninate(self): with patch(patch_string) as mock_print: self.burninator.burninate() mock_print.assert_has_calls( [ call('Burninated!') ] )
from mock import * from nose.tools import * from burninator import Burninator class TestBurninator(object): def setup(self): self.burninator = Burninator() def test_burninate(self): with patch('__builtin__.print') as mock_print: self.burninator.burninate() mock_print.assert_has_calls( [ call('Burninated!') ] )
mit
Python
910699eac10482a22a9de7151b8de7de0e00f104
Remove import
xuru/vixDiskLib
vixDiskLib/__init__.py
vixDiskLib/__init__.py
__version__ = "0.2" from vixDiskLib import * # IGNORE:F0401
mit
Python
0d7fb483706eca39c44fe3748d93d5d9deea3872
put pragma no cover on django ext
mathom/Zappa,pjz/Zappa,parroyo/Zappa,scoates/Zappa,longzhi/Zappa,pjz/Zappa,michi88/Zappa,mathom/Zappa,Miserlou/Zappa,longzhi/Zappa,scoates/Zappa,anush0247/Zappa,Miserlou/Zappa,michi88/Zappa,parroyo/Zappa,anush0247/Zappa
zappa/ext/django.py
zappa/ext/django.py
import sys # add the Lambda root path into the sys.path sys.path.append('/var/task') from django.core.handlers.wsgi import WSGIHandler from django.core.wsgi import get_wsgi_application import os def get_django_wsgi(settings_module): # pragma: no cover os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) import django django.setup() return get_wsgi_application()
import sys # add the Lambda root path into the sys.path sys.path.append('/var/task') from django.core.handlers.wsgi import WSGIHandler from django.core.wsgi import get_wsgi_application import os def get_django_wsgi(settings_module): os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) import django django.setup() return get_wsgi_application()
mit
Python
3ae67a03018db45f821935d8fa36bb7cd106dcc9
add user endpoint
Zombusters/zchat-lambdas
zchat/zchat/urls.py
zchat/zchat/urls.py
"""zchat URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets, status from rest_framework.generics import CreateAPIView from rest_framework.response import Response from rest_framework_jwt.views import verify_jwt_token, refresh_jwt_token, obtain_jwt_token from zmessages.serializers import MessageViewSet, MyMessageViewSet class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'first_name', 'last_name', 'username', 'email', 'is_staff') class NewUserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=254, min_length=5) class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password') class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class AddUserView(CreateAPIView): queryset = User.objects.all() serializer_class = NewUserSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): password = make_password(serializer.validated_data['password']) serializer.save(password=password) router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'messages', MessageViewSet, base_name='messages') router.register(r'my-messages', MyMessageViewSet, base_name='my-messages') urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-add-user', AddUserView.as_view(), name='add-new-user'), # jwt url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
"""zchat URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from rest_framework_jwt.views import verify_jwt_token, refresh_jwt_token, obtain_jwt_token from zmessages.serializers import MessageViewSet, MyMessageViewSet class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'first_name', 'last_name', 'username', 'email', 'is_staff') class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'messages', MessageViewSet, base_name='messages') router.register(r'my-messages', MyMessageViewSet, base_name='my-messages') urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^admin/', admin.site.urls), # jwt url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
mit
Python
e38f994d707a6c26c014b57278391d067c071879
Use an innerjoin to optimize the RSS view
wlonk/warehouse,alex/warehouse,karan/warehouse,alex/warehouse,wlonk/warehouse,karan/warehouse,dstufft/warehouse,dstufft/warehouse,karan/warehouse,pypa/warehouse,karan/warehouse,pypa/warehouse,alex/warehouse,wlonk/warehouse,pypa/warehouse,dstufft/warehouse,pypa/warehouse,alex/warehouse,karan/warehouse,alex/warehouse,dstufft/warehouse
warehouse/rss/views.py
warehouse/rss/views.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyramid.view import view_config from sqlalchemy.orm import joinedload, load_only from warehouse.cache.origin import origin_cache from warehouse.packaging.models import Project, Release from warehouse.xml import XML_CSP @view_config( route_name="rss.updates", renderer="rss/updates.xml", decorator=[ origin_cache( 1 * 24 * 60 * 60, # 1 day stale_while_revalidate=1 * 24 * 60 * 60, # 1 day stale_if_error=5 * 24 * 60 * 60, # 5 days ), ], ) def rss_updates(request): request.response.content_type = "text/xml" request.find_service(name="csp").merge(XML_CSP) latest_releases = ( request.db.query(Release) .options(joinedload(Release.project)) .order_by(Release.created.desc()) .limit(40) .all() ) return {"latest_releases": latest_releases} @view_config( route_name="rss.packages", renderer="rss/packages.xml", decorator=[ origin_cache( 1 * 24 * 60 * 60, # 1 day stale_while_revalidate=1 * 24 * 60 * 60, # 1 day stale_if_error=5 * 24 * 60 * 60, # 5 days ), ], ) def rss_packages(request): request.response.content_type = "text/xml" request.find_service(name="csp").merge(XML_CSP) newest_projects = ( request.db.query(Project) .options(load_only("created", "normalized_name")) .options(joinedload(Project.releases, innerjoin=True) .load_only("summary")) .order_by(Project.created.desc()) .limit(40) .all() ) return {"newest_projects": newest_projects}
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyramid.view import view_config from sqlalchemy.orm import joinedload from warehouse.cache.origin import origin_cache from warehouse.packaging.models import Project, Release from warehouse.xml import XML_CSP @view_config( route_name="rss.updates", renderer="rss/updates.xml", decorator=[ origin_cache( 1 * 24 * 60 * 60, # 1 day stale_while_revalidate=1 * 24 * 60 * 60, # 1 day stale_if_error=5 * 24 * 60 * 60, # 5 days ), ], ) def rss_updates(request): request.response.content_type = "text/xml" request.find_service(name="csp").merge(XML_CSP) latest_releases = ( request.db.query(Release) .options(joinedload(Release.project)) .order_by(Release.created.desc()) .limit(40) .all() ) return {"latest_releases": latest_releases} @view_config( route_name="rss.packages", renderer="rss/packages.xml", decorator=[ origin_cache( 1 * 24 * 60 * 60, # 1 day stale_while_revalidate=1 * 24 * 60 * 60, # 1 day stale_if_error=5 * 24 * 60 * 60, # 5 days ), ], ) def rss_packages(request): request.response.content_type = "text/xml" request.find_service(name="csp").merge(XML_CSP) newest_projects = ( request.db.query(Project) .options(joinedload(Project.releases)) .order_by(Project.created.desc()) .filter(Project.releases.any()) .limit(40) .all() ) return {"newest_projects": newest_projects}
apache-2.0
Python
6fbc027a8fc25ac69ddca755e1fbac3aebd845cb
reformat code
geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info
tests/inside_worker_test/burial_ground_sql_test.py
tests/inside_worker_test/burial_ground_sql_test.py
from contextlib import contextmanager, closing import pytest import sqlalchemy from sqlalchemy.sql.schema import Table as DbTable from tests.conftest import area_polyfile_string from tests.inside_worker_test.conftest import slow from tests.inside_worker_test.declarative_schema import osm_models @slow def test_osmaxx_data_model_processing_puts_amenity_grave_yard_with_religion_into_table_pow_a(data_import): data = { osm_models.t_osm_polygon: dict( amenity='grave_yard', religion='any value will do, as long as one is present', ), } with data_import(data) as engine: t_pow_a = DbTable('pow_a', osm_models.metadata, schema='osmaxx') with closing(engine.execute(sqlalchemy.select([t_pow_a]))) as result: assert result.rowcount == 1 @pytest.fixture() def data_import(osmaxx_schemas, clean_osm_tables, monkeypatch): from tests.inside_worker_test.conftest import cleanup_osmaxx_schemas from osmaxx.conversion.converters.converter_gis.bootstrap.bootstrap import BootStrapper assert osmaxx_schemas == clean_osm_tables # same db-connection engine = osmaxx_schemas monkeypatch.setattr( 'osmaxx.conversion.converters.converter_gis.helper.postgres_wrapper.create_engine', lambda *_, **__: engine) class _BootStrapperWithoutPbfFile(BootStrapper): def __init__(self, data): super().__init__(area_polyfile_string=area_polyfile_string()) self.data = data def _reset_database(self): pass # Already taken care of by clean_osm_tables fixture. def _import_from_world_db(self): for table, values in self.data.items(): engine.execute(table.insert().execution_options(autocommit=True), values) def _setup_db_functions(self): pass # Already taken care of by osmaxx_functions fixture. @contextmanager def import_data(data): bootstrapper = _BootStrapperWithoutPbfFile(data) try: bootstrapper.bootstrap() yield engine finally: cleanup_osmaxx_schemas(bootstrapper._postgres._engine) return import_data
from contextlib import contextmanager, closing import pytest import sqlalchemy from sqlalchemy.sql.schema import Table as DbTable from tests.conftest import area_polyfile_string from tests.inside_worker_test.conftest import slow from tests.inside_worker_test.declarative_schema import osm_models @slow def test_osmaxx_data_model_processing_puts_amenity_grave_yard_with_religion_into_table_pow_a(data_import): data = { osm_models.t_osm_polygon: dict( amenity='grave_yard', religion='any value will do, as long as one is present', ), } with data_import(data) as engine: t_pow_a = DbTable('pow_a', osm_models.metadata, schema='osmaxx') with closing(engine.execute(sqlalchemy.select([t_pow_a]))) as result: assert result.rowcount == 1 @pytest.fixture() def data_import(osmaxx_schemas, clean_osm_tables, monkeypatch): from tests.inside_worker_test.conftest import cleanup_osmaxx_schemas from osmaxx.conversion.converters.converter_gis.bootstrap.bootstrap import BootStrapper assert osmaxx_schemas == clean_osm_tables # same db-connection engine = osmaxx_schemas monkeypatch.setattr( 'osmaxx.conversion.converters.converter_gis.helper.postgres_wrapper.create_engine', lambda *_, **__: engine) class _BootStrapperWithoutPbfFile(BootStrapper): def __init__(self, data): super().__init__(area_polyfile_string=area_polyfile_string()) self.data = data def _reset_database(self): pass # Already taken care of by clean_osm_tables fixture. def _import_from_world_db(self): for table, values in self.data.items(): engine.execute(table.insert().execution_options(autocommit=True), values) def _setup_db_functions(self): pass # Already taken care of by osmaxx_functions fixture. @contextmanager def import_data(data): bootstrapper = _BootStrapperWithoutPbfFile(data) try: bootstrapper.bootstrap() yield engine finally: cleanup_osmaxx_schemas(bootstrapper._postgres._engine) return import_data
mit
Python
ef2813a0683e15dcedfe747f7dd2e55dc76cc832
Improve load env config log output
espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf
tools/ci/python_packages/tiny_test_fw/EnvConfig.py
tools/ci/python_packages/tiny_test_fw/EnvConfig.py
# Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The test env could change when we running test from different computers. Test env config provide ``get_variable`` method to allow user get test environment related variables. It will first try to get variable from config file. If failed, then it will try to auto detect (Not supported yet). Config file format is yaml. it's a set of key-value pair. The following is an example of config file:: Example_WIFI: ap_ssid: "myssid" ap_password: "mypassword" Example_ShieldBox: attenuator_port: "/dev/ttyUSB2" ap_ssid: "myssid" ap_password: "mypassword" It will first define the env tag for each environment, then add its key-value pairs. This will prevent test cases from getting configs from other env when there're configs for multiple env in one file. """ import logging import yaml try: from yaml import CLoader as Loader except ImportError: from yaml import Loader as Loader class Config(object): """ Test Env Config """ def __init__(self, config_file, env_tag): self.configs = self.load_config_file(config_file, env_tag) @staticmethod def load_config_file(config_file, env_name): """ load configs from config file. :param config_file: config file path :param env_name: env tag name :return: configs for the test env """ try: with open(config_file) as f: configs = yaml.load(f, Loader=Loader)[env_name] except (OSError, TypeError, IOError): configs = dict() except KeyError: logging.error('No config env "{}" in config file "{}"'.format(env_name, config_file)) raise return configs def get_variable(self, variable_name): """ first try to get from config file. if not found, try to auto detect the variable. :param variable_name: name of variable :return: value or None """ try: value = self.configs[variable_name] except KeyError: # TODO: to support auto get variable here value = None if value is None: raise ValueError("Failed to get variable") return value
# Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The test env could change when we running test from different computers. Test env config provide ``get_variable`` method to allow user get test environment related variables. It will first try to get variable from config file. If failed, then it will try to auto detect (Not supported yet). Config file format is yaml. it's a set of key-value pair. The following is an example of config file:: Example_WIFI: ap_ssid: "myssid" ap_password: "mypassword" Example_ShieldBox: attenuator_port: "/dev/ttyUSB2" ap_ssid: "myssid" ap_password: "mypassword" It will first define the env tag for each environment, then add its key-value pairs. This will prevent test cases from getting configs from other env when there're configs for multiple env in one file. """ import yaml try: from yaml import CLoader as Loader except ImportError: from yaml import Loader as Loader class Config(object): """ Test Env Config """ def __init__(self, config_file, env_tag): self.configs = self.load_config_file(config_file, env_tag) @staticmethod def load_config_file(config_file, env_name): """ load configs from config file. :param config_file: config file path :param env_name: env tag name :return: configs for the test env """ try: with open(config_file) as f: configs = yaml.load(f, Loader=Loader)[env_name] except (OSError, TypeError, IOError): configs = dict() return configs def get_variable(self, variable_name): """ first try to get from config file. if not found, try to auto detect the variable. :param variable_name: name of variable :return: value or None """ try: value = self.configs[variable_name] except KeyError: # TODO: to support auto get variable here value = None if value is None: raise ValueError("Failed to get variable") return value
apache-2.0
Python
2acfe55b746a72088e5aaad31e6ed264857895c6
fix expat dependency (#26221)
LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack
var/spack/repos/builtin/packages/exempi/package.py
var/spack/repos/builtin/packages/exempi/package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Exempi(AutotoolsPackage): """exempi is a port of Adobe XMP SDK to work on UNIX and to be build with GNU automake. It includes XMPCore and XMPFiles, libexempi, a C-based API and exempi a command line tool. """ homepage = "https://libopenraw.freedesktop.org/wiki/Exempi" url = "https://libopenraw.freedesktop.org/download/exempi-2.5.2.tar.bz2" version('2.5.2', sha256='52f54314aefd45945d47a6ecf4bd21f362e6467fa5d0538b0d45a06bc6eaaed5') depends_on('zlib') depends_on('iconv') depends_on('boost@1.48.0:') depends_on('pkgconfig') depends_on('expat') conflicts('%gcc@:4.5') def patch(self): # fix make check: Fix undefined reference to `boost::unit_test::unit_test_main`: # BOOST_TEST_DYN_LINK only works with shlib and when boost is linked after src: # https://bugs.launchpad.net/widelands/+bug/662908 # https://github.com/bincrafters/community/issues/127 filter_file('#define BOOST_TEST_DYN_LINK', '', 'exempi/tests/test-adobesdk.cpp') def configure_args(self): args = ['--with-boost={0}'.format(self.spec['boost'].prefix)] if self.spec.satisfies('polatform=darwin'): args += ['--with-darwinports', '--with-fink'] return args
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Exempi(AutotoolsPackage): """exempi is a port of Adobe XMP SDK to work on UNIX and to be build with GNU automake. It includes XMPCore and XMPFiles, libexempi, a C-based API and exempi a command line tool. """ homepage = "https://libopenraw.freedesktop.org/wiki/Exempi" url = "https://libopenraw.freedesktop.org/download/exempi-2.5.2.tar.bz2" version('2.5.2', sha256='52f54314aefd45945d47a6ecf4bd21f362e6467fa5d0538b0d45a06bc6eaaed5') depends_on('zlib') depends_on('iconv') depends_on('boost@1.48.0:') depends_on('pkgconfig') conflicts('%gcc@:4.5') def configure_args(self): args = ['--with-boost={0}'.format(self.spec['boost'].prefix)] if self.spec.satisfies('polatform=darwin'): args += ['--with-darwinports', '--with-fink'] return args
lgpl-2.1
Python
08f7020e0ab9906962fcef43c369fae7c6f00c0e
add v2.0.6 (#23397)
LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack
var/spack/repos/builtin/packages/opari2/package.py
var/spack/repos/builtin/packages/opari2/package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Opari2(AutotoolsPackage): """OPARI2 is a source-to-source instrumentation tool for OpenMP and hybrid codes. It surrounds OpenMP directives and runtime library calls with calls to the POMP2 measurement interface. OPARI2 will provide you with a new initialization method that allows for multi-directory and parallel builds as well as the usage of pre-instrumented libraries. Furthermore, an efficient way of tracking parent-child relationships was added. Additionally, we extended OPARI2 to support instrumentation of OpenMP 3.0 tied tasks. """ homepage = "http://www.vi-hps.org/projects/score-p" url = "https://www.vi-hps.org/cms/upload/packages/opari2/opari2-2.0.4.tar.gz" version('2.0.6', sha256='55972289ce66080bb48622110c3189a36e88a12917635f049b37685b9d3bbcb0', url='https://perftools.pages.jsc.fz-juelich.de/cicd/opari2/tags/opari2-2.0.6/opari2-2.0.6.tar.gz') version('2.0.5', sha256='9034dd7596ac2176401090fd5ced45d0ab9a9404444ff767f093ccce68114ef5') version('2.0.4', sha256='f69e324792f66780b473daf2b3c81f58ee8188adc72b6fe0dacf43d4c1a0a131') version('2.0.3', sha256='7e2efcfbc99152ee6e31454ef4fb747f77165691539d5d2c1df2abc4612de86c') version('2.0.1', sha256='f49d74d7533f428a4701cd561eba8a69f60615332e81b66f01ef1c9b7ee54666') version('2.0', sha256='0c4e575be05627cd001d692204f10caef37b2f3d1ec825f98cbe1bfa4232b0b7') version('1.1.4', sha256='b80c04fe876faaa4ee9a0654486ecbeba516b27fc14a90d20c6384e81060cffe') version('1.1.2', sha256='8405c2903730d94c828724b3a5f8889653553fb8567045a6c54ac0816237835d') def configure_args(self): return ["--enable-shared"]
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Opari2(AutotoolsPackage): """OPARI2 is a source-to-source instrumentation tool for OpenMP and hybrid codes. It surrounds OpenMP directives and runtime library calls with calls to the POMP2 measurement interface. OPARI2 will provide you with a new initialization method that allows for multi-directory and parallel builds as well as the usage of pre-instrumented libraries. Furthermore, an efficient way of tracking parent-child relationships was added. Additionally, we extended OPARI2 to support instrumentation of OpenMP 3.0 tied tasks. """ homepage = "http://www.vi-hps.org/projects/score-p" url = "https://www.vi-hps.org/cms/upload/packages/opari2/opari2-2.0.4.tar.gz" version('2.0.5', sha256='9034dd7596ac2176401090fd5ced45d0ab9a9404444ff767f093ccce68114ef5') version('2.0.4', sha256='f69e324792f66780b473daf2b3c81f58ee8188adc72b6fe0dacf43d4c1a0a131') version('2.0.3', sha256='7e2efcfbc99152ee6e31454ef4fb747f77165691539d5d2c1df2abc4612de86c') version('2.0.1', sha256='f49d74d7533f428a4701cd561eba8a69f60615332e81b66f01ef1c9b7ee54666') version('2.0', sha256='0c4e575be05627cd001d692204f10caef37b2f3d1ec825f98cbe1bfa4232b0b7') version('1.1.4', sha256='b80c04fe876faaa4ee9a0654486ecbeba516b27fc14a90d20c6384e81060cffe') version('1.1.2', sha256='8405c2903730d94c828724b3a5f8889653553fb8567045a6c54ac0816237835d') def configure_args(self): return ["--enable-shared"]
lgpl-2.1
Python
2dc4221308bd60254ce937a7501382fbdd07f3b5
Fix test name so it actually runs
rickerbh/tictactoe_py
tests/game_board_tests.py
tests/game_board_tests.py
from nose.tools import * from tictactoe.game_board import GameBoard def game_board_is_empty_on_creation_test(): board = GameBoard() current_state = board.game_state assert_equal(["", "", "", "", "", "", "", "", ""], current_state) def game_board_registers_initial_move_test(): board = GameBoard() board.play_move("X", 3) current_state = board.game_state assert_equal(["", "", "", "X", "", "", "", "", ""], current_state) def game_board_raises_exception_when_playing_invalid_positions_test(): board = GameBoard() ex1 = None ex2 = None try: board.play_move("X", -1) except ValueError as ex: ex1 = ex try: board.play_move("O", 100) except ValueError as ex: ex2 = ex assert_equal('-1 is not a valid board position', ex1.args[0]) assert_equal('100 is not a valid board position', ex2.args[0]) def game_board_raises_exception_when_playing_a_position_already_played_test(): board = GameBoard() ex1 = None board.play_move("X", 2) try: board.play_move("X", 2) except ValueError as ex: ex1 = ex assert_equal('2 is already taken', ex1.args[0]) def game_is_won_on_a_row_test(): board = GameBoard() board.play_move("X", 3) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 5) assert_equal(True, board.has_winner()) def game_is_won_on_a_column_test(): board = GameBoard() board.play_move("X", 1) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 7) assert_equal(True, board.has_winner()) def game_is_won_on_a_diagonal_test(): board = GameBoard() board.play_move("X", 2) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 6) assert_equal(True, board.has_winner()) def game_raises_exception_when_making_a_move_and_the_game_is_won_test(): board = GameBoard() board.play_move("X", 3) board.play_move("X", 4) board.play_move("X", 5) ex1 = None try: board.play_move("X", 0) except ValueError as ex: ex1 = ex assert_equal('Game is over', ex1.args[0])
from nose.tools import * from tictactoe.game_board import GameBoard def game_board_is_empty_on_creation_test(): board = GameBoard() current_state = board.game_state assert_equal(["", "", "", "", "", "", "", "", ""], current_state) def game_board_registers_initial_move_test(): board = GameBoard() board.play_move("X", 3) current_state = board.game_state assert_equal(["", "", "", "X", "", "", "", "", ""], current_state) def game_board_raises_exception_when_playing_invalid_positions_test(): board = GameBoard() ex1 = None ex2 = None try: board.play_move("X", -1) except ValueError as ex: ex1 = ex try: board.play_move("O", 100) except ValueError as ex: ex2 = ex assert_equal('-1 is not a valid board position', ex1.args[0]) assert_equal('100 is not a valid board position', ex2.args[0]) def game_board_raises_exception_when_playing_a_position_already_played_test(): board = GameBoard() ex1 = None board.play_move("X", 2) try: board.play_move("X", 2) except ValueError as ex: ex1 = ex assert_equal('2 is already taken', ex1.args[0]) def game_is_won_on_a_row_test(): board = GameBoard() board.play_move("X", 3) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 5) assert_equal(True, board.has_winner()) def game_is_won_on_a_column_test(): board = GameBoard() board.play_move("X", 1) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 7) assert_equal(True, board.has_winner()) def game_is_won_on_a_diagonal_test(): board = GameBoard() board.play_move("X", 2) assert_equal(False, board.has_winner()) board.play_move("X", 4) assert_equal(False, board.has_winner()) board.play_move("X", 6) assert_equal(True, board.has_winner()) def game_raises_exception_when_making_a_move_and_the_game_is_won(): board = GameBoard() board.play_move("X", 3) board.play_move("X", 4) board.play_move("X", 5) ex1 = None try: board.play_move("X", 0) except ValueError as ex: ex1 = ex assert_equal('Game is over', ex1.args[0])
mit
Python
a82ecc8b6a544d88e23feee7496ce4ddfa8cae5d
Update version number
PaulMcInnis/JobPy
jobfunnel/__init__.py
jobfunnel/__init__.py
__version__ = '2.1.4'
__version__ = '2.1.3'
mit
Python
7dea728044ab0477670b0690c202ea8270dbbfb4
Fix java tests
jorgebastida/gordon,jorgebastida/gordon,jorgebastida/gordon
tests/lambdajava/tests.py
tests/lambdajava/tests.py
import os import unittest import boto3 from gordon.utils_tests import BaseIntegrationTest, BaseBuildTest from gordon.utils import valid_cloudformation_name from gordon import utils @unittest.skip("Temporarily disabled") class IntegrationTest(BaseIntegrationTest): def test_0001_project(self): self._test_project_step('0001_project') self.assert_stack_succeed('p') self.assert_stack_succeed('r') lambda_ = self.get_lambda(utils.valid_cloudformation_name('javaexample:javaexample')) self.assertEqual(lambda_['Runtime'], 'java8') self.assertEqual(lambda_['Description'], 'My description') self.assertEqual(lambda_['MemorySize'], 192) self.assertEqual(lambda_['Timeout'], 123) aliases = self.get_lambda_aliases(function_name=lambda_['FunctionName']) self.assertEqual(aliases.keys(), ['current']) response = self.invoke_lambda( function_name=lambda_['FunctionName'], payload={'key1': 'hello'} ) self.assert_lambda_response(response, 'hello') @unittest.skip("Temporarily disabled") class BuildTest(BaseBuildTest): def test_0001_project(self): self._test_project_step('0001_project') self.assertBuild('0001_project', '0001_p.json') self.assertBuild('0001_project', '0002_pr_r.json') self.assertBuild('0001_project', '0003_r.json') self.assertRun( '0001_project', 'javaexample.javaexample', '{"key1":"value1", "key2":"value2", "key3":"value3"}', ['Loading function', 'value1 = value1', 'output: value1', ''] )
import os import unittest import boto3 from gordon.utils_tests import BaseIntegrationTest, BaseBuildTest from gordon.utils import valid_cloudformation_name from gordon import utils @unittest.skipIf(os.environ.get('TRAVIS') == 'true', "Test not yet supported on travis") class IntegrationTest(BaseIntegrationTest): def test_0001_project(self): self._test_project_step('0001_project') self.assert_stack_succeed('p') self.assert_stack_succeed('r') lambda_ = self.get_lambda(utils.valid_cloudformation_name('javaexample:javaexample')) self.assertEqual(lambda_['Runtime'], 'java8') self.assertEqual(lambda_['Description'], 'My description') self.assertEqual(lambda_['MemorySize'], 192) self.assertEqual(lambda_['Timeout'], 123) aliases = self.get_lambda_aliases(function_name=lambda_['FunctionName']) self.assertEqual(aliases.keys(), ['current']) response = self.invoke_lambda( function_name=lambda_['FunctionName'], payload={'key1': 'hello'} ) self.assert_lambda_response(response, 'hello') @unittest.skipIf(os.environ.get('TRAVIS') == 'true', "Test not yet supported on travis") class BuildTest(BaseBuildTest): def test_0001_project(self): self._test_project_step('0001_project') self.assertBuild('0001_project', '0001_p.json') self.assertBuild('0001_project', '0002_pr_r.json') self.assertBuild('0001_project', '0003_r.json') self.assertRun( '0001_project', 'javaexample.javaexample', '{"key1":"value1", "key2":"value2", "key3":"value3"}', ['Loading function', 'value1 = value1', 'output: value1', ''] )
bsd-3-clause
Python
730d786d03119f74b1ddddd0ce1d17d210cb0ac2
test api: set status codes for create recording
webrecorder/webrecorder,webrecorder/webrecorder,webrecorder/webrecorder,webrecorder/webrecorder
webrecorder/test/api/v1.py
webrecorder/test/api/v1.py
from bottle import get, post, request, response, run from random import randint import re # GET /recordings @get('/api/v1/recordings') def recordings_index(): user = request.query.user collection = request.query.collection return { "recordings": [{"id": "a-la-recherche", "title": "À la recherche", "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 1000000}, {"id": "du-temps-perdu", "title": "du temps perdu", "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 1000000}]} # POST /recordings @post('/api/v1/recordings') def create_recording(): title = request.forms.get('title') id = id_from_title(title) if is_valid(id): response.status = 200 return {"status": "success", "recording": {"id": id, "title": title, "created_at": "2016010203000000", "modified_at": "2016010203000000", "size": 0}} else: response.status = 400 return {"status": "AlreadyExists", "recording": {"id": id, "title": title, "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 100000}} # GET /recordings/<id> @get('/api/v1/recordings/<id>') def get_recording(id): user = request.query.user collection = request.query.collection title = title_from_id(id) return {"id": id, "title": title, "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 87000} # @delete('/api/v1/recordings/<id>') # @get('/api/v1/recordings/<id>/download') # @get('/api/v1/recordings/<id>/pages') # @post('/api/v1/recordings/<id>/pages') # @get('/api/v1/collections') # @post('/api/v1/collections') # @get('/api/v1/collections/<id>') # @delete('/api/v1/collections/<id>') # @get('/api/v1/collections/<id>/download') # Utilities def is_valid(id): if randint(0,1) == 0: return True else: return False def id_from_title(title): p = re.compile('[\s]') return p.sub('-', title) def title_from_id(id): p = re.compile('[-]') return p.sub(' ', id) run(host='localhost', port=8080, debug=True)
from bottle import get, post, request, run from random import randint import re # GET /recordings @get('/api/v1/recordings') def recordings_index(): user = request.query.user collection = request.query.collection return { "recordings": [{"id": "a-la-recherche", "title": "À la recherche", "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 1000000}, {"id": "du-temps-perdu", "title": "du temps perdu", "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 1000000}]} # POST /recordings @post('/api/v1/recordings') def create_recording(): title = request.forms.get('title') id = id_from_title(title) if is_valid(id): return {"status": "success", "recording": {"id": id, "title": title, "created_at": "2016010203000000", "modified_at": "2016010203000000", "size": 0}} else: return {"status": "AlreadyExists", "recording": {"id": id, "title": title, "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 100000}} # GET /recordings/<id> @get('/api/v1/recordings/<id>') def get_recording(id): user = request.query.user collection = request.query.collection title = title_from_id(id) return {"id": id, "title": title, "created_at": "2016010203000000", "updated_at": "2016010203000000", "size": 87000} # @delete('/api/v1/recordings/<id>') # @get('/api/v1/recordings/<id>/download') # @get('/api/v1/recordings/<id>/pages') # @post('/api/v1/recordings/<id>/pages') # @get('/api/v1/collections') # @post('/api/v1/collections') # @get('/api/v1/collections/<id>') # @delete('/api/v1/collections/<id>') # @get('/api/v1/collections/<id>/download') # Utilities def is_valid(id): if randint(0,1) == 0: return True else: return False def id_from_title(title): p = re.compile('[\s]') return p.sub('-', title) def title_from_id(id): p = re.compile('[-]') return p.sub(' ', id) run(host='localhost', port=8080, debug=True)
apache-2.0
Python
f268e841194b941ac74bee34f59dfa49c5d99c21
remove raw unicode strings as they aren't supported in py3
pidydx/artifacts,destijl/artifacts,pidydx/artifacts,destijl/artifacts
tests/source_type_test.py
tests/source_type_test.py
# -*- coding: utf-8 -*- """Tests for the source type objects.""" import unittest from artifacts import errors from artifacts import source_type class SourceTypeTest(unittest.TestCase): """Class to test the artifact source type.""" class ArtifactSourceTypeTest(unittest.TestCase): """Class to test the artifacts source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.ArtifactSourceType(names=[u'test']) class FileSourceTypeTest(unittest.TestCase): """Class to test the files source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.FileSourceType(paths=[u'test']) source_type.FileSourceType(paths=[u'test'], separator=u'\\') class PathSourceTypeTest(unittest.TestCase): """Class to test the paths source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.PathSourceType(paths=[u'test']) source_type.PathSourceType(paths=[u'test'], separator=u'\\') class WindowsRegistryKeySourceTypeTest(unittest.TestCase): """Class to test the Windows Registry keys source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WindowsRegistryKeySourceType(keys=[u'HKEY_LOCAL_MACHINE\\test']) class WindowsRegistryValueSourceTypeTest(unittest.TestCase): """Class to test the Windows Registry value source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WindowsRegistryValueSourceType( key_value_pairs=[{'key': u'HKEY_LOCAL_MACHINE\\test', 'value': u'test'}]) with self.assertRaises(errors.FormatError): source_type.WindowsRegistryValueSourceType( key_value_pairs=[{'bad': u'test', 'value': u'test'}]) with self.assertRaises(errors.FormatError): source_type.WindowsRegistryValueSourceType( key_value_pairs={'bad': u'test', 'value': u'test'}) class WMIQuerySourceType(unittest.TestCase): """Class to test the WMI query source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WMIQuerySourceType(query=u'test') if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """Tests for the source type objects.""" import unittest from artifacts import errors from artifacts import source_type class SourceTypeTest(unittest.TestCase): """Class to test the artifact source type.""" class ArtifactSourceTypeTest(unittest.TestCase): """Class to test the artifacts source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.ArtifactSourceType(names=[u'test']) class FileSourceTypeTest(unittest.TestCase): """Class to test the files source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.FileSourceType(paths=[u'test']) source_type.FileSourceType(paths=[u'test'], separator=u'\\') class PathSourceTypeTest(unittest.TestCase): """Class to test the paths source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.PathSourceType(paths=[u'test']) source_type.PathSourceType(paths=[u'test'], separator=u'\\') class WindowsRegistryKeySourceTypeTest(unittest.TestCase): """Class to test the Windows Registry keys source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WindowsRegistryKeySourceType(keys=[ur'HKEY_LOCAL_MACHINE\test']) class WindowsRegistryValueSourceTypeTest(unittest.TestCase): """Class to test the Windows Registry value source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WindowsRegistryValueSourceType( key_value_pairs=[{'key': ur'HKEY_LOCAL_MACHINE\test', 'value': u'test'}]) with self.assertRaises(errors.FormatError): source_type.WindowsRegistryValueSourceType( key_value_pairs=[{'bad': u'test', 'value': u'test'}]) with self.assertRaises(errors.FormatError): source_type.WindowsRegistryValueSourceType( key_value_pairs={'bad': u'test', 'value': u'test'}) class WMIQuerySourceType(unittest.TestCase): """Class to test the WMI query source type.""" def testInitialize(self): """Tests the __init__ function.""" source_type.WMIQuerySourceType(query=u'test') if __name__ == '__main__': unittest.main()
apache-2.0
Python
5c22244ee834db213052513474898317ce867f4f
Fix duplicate tests
zero323/pyspark-stubs
tests/unit/testpyspark.py
tests/unit/testpyspark.py
from mypy.test.data import DataDrivenTestCase, DataSuite from mypy.test.testcheck import TypeCheckSuite TypeCheckSuite.files = [ "context.test", "ml-classification.test", "ml-evaluation.test", "ml-feature.test", "ml-param.test", "ml-readable.test", "resultiterable.test", "sql-readwriter.test", "sql-udf.test", ]
from mypy.test.data import DataDrivenTestCase, DataSuite from mypy.test.testcheck import TypeCheckSuite class PySparkCoreSuite(TypeCheckSuite): TypeCheckSuite.files = [ "context.test", "ml-classification.test", "ml-evaluation.test", "ml-feature.test", "ml-param.test", "ml-readable.test", "resultiterable.test", "sql-readwriter.test", "udf.test", ] required_out_section = True
apache-2.0
Python
561ffb4b5ea32383447ff1af29b849f1435d4337
update init arguments
mir-group/flare,mir-group/flare
tests/test_OTF_vasp.py
tests/test_OTF_vasp.py
import pytest import os import sys import numpy as np from flare.otf import OTF from flare.gp import GaussianProcess from flare.struc import Structure from flare.dft_interface.vasp_util import * # ------------------------------------------------------ # test otf runs # ------------------------------------------------------ def test_otf_h2(): """ :return: """ os.system('cp ./test_files/test_POSCAR_2 POSCAR') vasp_input = './POSCAR' dt = 0.0001 number_of_steps = 5 cutoffs = {'twobody':5} dft_loc = 'cp ./test_files/test_vasprun_h2.xml vasprun.xml' std_tolerance_factor = -0.1 # make gp model hyps = np.array([1, 1, 1]) hyp_labels = ['Signal Std', 'Length Scale', 'Noise Std'] gp = GaussianProcess(kernel_name='2', hyps=hyps, cutoffs=cutoffs, hyp_labels=hyp_labels, maxiter=50) otf = OTF(dt=dt, number_of_steps=number_of_steps, gp=gp, calculate_energy=True, std_tolerance_factor=std_tolerance_factor, init_atoms=[0], output_name='h2_otf_vasp', max_atoms_added=1, force_source='vasp', dft_input=vasp_input, dft_loc=dft_loc, dft_output="vasprun.xml", n_cpus=1) otf.run() os.system('mv h2_otf_vasp* test_outputs')
import pytest import os import sys import numpy as np from flare.otf import OTF from flare.gp import GaussianProcess from flare.struc import Structure from flare.dft_interface.vasp_util import * # ------------------------------------------------------ # test otf runs # ------------------------------------------------------ def test_otf_h2(): """ :return: """ os.system('cp ./test_files/test_POSCAR_2 POSCAR') vasp_input = './POSCAR' dt = 0.0001 number_of_steps = 5 cutoffs = {'twobody':5} dft_loc = 'cp ./test_files/test_vasprun_h2.xml vasprun.xml' std_tolerance_factor = -0.1 # make gp model hyps = np.array([1, 1, 1]) hyp_labels = ['Signal Std', 'Length Scale', 'Noise Std'] gp = GaussianProcess(kernel_name='2', hyps=hyps, cutoffs=cutoffs, hyp_labels=hyp_labels, maxiter=50) otf = OTF(vasp_input, dt, number_of_steps, gp, dft_loc, std_tolerance_factor, init_atoms=[0], calculate_energy=True, max_atoms_added=1, n_cpus=1, force_source='vasp', dft_output="vasprun.xml", output_name='h2_otf_vasp') otf.run() os.system('mv h2_otf_vasp* test_outputs')
mit
Python
d915efcd0df748d0872b2b2e905e94e65841ee9c
Switch test to pytest.
okin/nikola,getnikola/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola
tests/test_commands.py
tests/test_commands.py
# -*- coding: utf-8 -*- from nikola.plugins.command.version import CommandVersion def test_version(): """Test `nikola version`.""" CommandVersion().execute()
# -*- coding: utf-8 -*- import unittest from nikola.plugins.command.version import CommandVersion class CommandVersionCallTest(unittest.TestCase): def test_version(self): """Test `nikola version`.""" CommandVersion().execute()
mit
Python
b3c5707f90590af9ff63a76ba4b8101bd590d147
Document tests for copy feature
caleb531/youversion-suggest,caleb531/youversion-suggest
tests/test_copy_ref.py
tests/test_copy_ref.py
#!/usr/bin/env python import nose.tools as nose import yv_suggest.copy_ref as yvs import context_managers as ctx from mock import patch, mock_open, Mock with open('tests/files/psa.23.html') as html_file: TEST_REF_HTML = html_file.read() def before_each(): yvs.urllib2.urlopen = Mock() yvs.urllib2.urlopen.return_value.read = Mock(return_value=TEST_REF_HTML) def after_each(): pass @nose.with_setup(before_each, after_each) def test_copy_chapter(): '''should copy reference content for chapter''' with open('tests/files/psa.23.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_copy_verse(): '''should copy reference content for verse''' with open('tests/files/psa.23.2.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23.2') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_copy_verse_range(): '''should copy reference content for verse range''' with open('tests/files/psa.23.1-2.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23.1-2') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_language(): '''should copy reference content in another language''' with open('tests/files/psa.23.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('128/psa.23', prefs={ 'language': 'es' }) ref_text = text_file.read().strip() ref_text = ref_text.replace('Psalm', 'Salmos') ref_text = ref_text.replace('NIV', 'NVI') nose.assert_equal(out.getvalue().strip(), ref_text)
#!/usr/bin/env python import nose.tools as nose import yv_suggest.copy_ref as yvs import context_managers as ctx from mock import patch, mock_open, Mock with open('tests/files/psa.23.html') as html_file: TEST_REF_HTML = html_file.read() def before_each(): yvs.urllib2.urlopen = Mock() yvs.urllib2.urlopen.return_value.read = Mock(return_value=TEST_REF_HTML) def after_each(): pass @nose.with_setup(before_each, after_each) def test_copy_chapter(): with open('tests/files/psa.23.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_copy_verse(): with open('tests/files/psa.23.2.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23.2') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_copy_verse_range(): with open('tests/files/psa.23.1-2.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('111/psa.23.1-2') nose.assert_equal(out.getvalue().strip(), text_file.read().strip()) @nose.with_setup(before_each, after_each) def test_language(): with open('tests/files/psa.23.txt') as text_file: with ctx.redirect_stdout() as out: yvs.main('128/psa.23', prefs={ 'language': 'es' }) ref_text = text_file.read().strip() ref_text = ref_text.replace('Psalm', 'Salmos') ref_text = ref_text.replace('NIV', 'NVI') nose.assert_equal(out.getvalue().strip(), ref_text)
mit
Python
d1252fde02f21cbf24e8fbf59d72083c40b2c0a2
make payload nullable
uwekamper/justeventme
justeventme/models.py
justeventme/models.py
# -*- coding: utf-8 -*- from django.db import models from django.db.models.base import ModelBase from django.contrib.postgres.fields import HStoreField class ReadModel(models.Model): """ The read model is an abstract class for creating read-only models that present the state of the system to the outside. """ class Meta: abstract = True def save(self, *args, **kwargs): """ Disable the save method """ raise NotImplementedError() def _super_save(self, *args, **kwargs): super(ReadModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """ Disable the delete method. """ raise NotImplementedError() def _super_delete(self, *args, **kwargs): super(ReadModel, self).delete(*args, **kwargs) class BaseEventMetaclass(ModelBase): def __call__(cls, *args, **kwargs): obj = super(BaseEventMetaclass, cls).__call__(*args, **kwargs) return obj.get_object() class Event(models.Model): """ """ __metaclass__ = BaseEventMetaclass object_class = models.CharField(max_length=20) stream_id = models.UUIDField(null=True, blank=True) seq = models.IntegerField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) payload = HStoreField(null=True, blank=True) def save(self, *args, **kwargs): if not self.object_class: self.object_class = self._meta.object_name super().save(*args, **kwargs) def get_object(self): """ After retrieving the Event object from the database this methods is used to get the """ SUBCLASSES_OF_EVENT = dict([(cls.__name__, cls) for cls in Event.__subclasses__()]) if self.object_class in SUBCLASSES_OF_EVENT: self.__class__ = SUBCLASSES_OF_EVENT[self.object_class] return self class Meta: unique_together=('stream_id', 'seq')
# -*- coding: utf-8 -*- from django.db import models from django.db.models.base import ModelBase from django.contrib.postgres.fields import HStoreField class ReadModel(models.Model): """ The read model is an abstract class for creating read-only models that present the state of the system to the outside. """ class Meta: abstract = True def save(self, *args, **kwargs): """ Disable the save method """ raise NotImplementedError() def _super_save(self, *args, **kwargs): super(ReadModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """ Disable the delete method. """ raise NotImplementedError() def _super_delete(self, *args, **kwargs): super(ReadModel, self).delete(*args, **kwargs) class BaseEventMetaclass(ModelBase): def __call__(cls, *args, **kwargs): obj = super(BaseEventMetaclass, cls).__call__(*args, **kwargs) return obj.get_object() class Event(models.Model): """ """ __metaclass__ = BaseEventMetaclass object_class = models.CharField(max_length=20) stream_id = models.UUIDField(null=True, blank=True) seq = models.IntegerField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) payload = HStoreField() def save(self, *args, **kwargs): if not self.object_class: self.object_class = self._meta.object_name super().save(*args, **kwargs) def get_object(self): """ After retrieving the Event object from the database this methods is used to get the """ SUBCLASSES_OF_EVENT = dict([(cls.__name__, cls) for cls in Event.__subclasses__()]) if self.object_class in SUBCLASSES_OF_EVENT: self.__class__ = SUBCLASSES_OF_EVENT[self.object_class] return self class Meta: unique_together=('stream_id', 'seq')
mit
Python
3a2e52a8da5f9f7a8e80e564b04dcf671ce06102
Remove dummy.mc at the end of all tests
SEMAFORInformatik/femagtools,SEMAFORInformatik/femagtools
tests/test_magncurv.py
tests/test_magncurv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # import unittest import tempfile import femagtools import os mcvPars =[dict( name="TKS_NO_20" ,desc="PowerCore NO 20 ;ThyssenKrupp Steel Eur" ,cversion=0 ,ctype=1 ,recalc=1 ,curve=[{"bi":[0.0,0.09029103,0.17855673,0.26691416,0.35827994], "bi2":[11,22,33], "nuer":[111,222,333], "a":[6,5,4], "b":[9,8,7], "hi":[1,2,3,4,5]}] ,remz=0.0 ,fillfac=0.92000002 ,bsat=0.0 ,bref=0.0 ,ch=4.0 ,ch_freq=5.0 ,cw=3.0 ,cw_freq=2.0 ,fo=50.0 ,Bo=1.5 ,b_coeff=1.0 ,rho=7.6500001 ,fe_sat_mag=2.15) ] class MagnetizingCurveTest(unittest.TestCase): maxDiff=None def test_findById( self ): mcv=femagtools.MagnetizingCurve(mcvPars) result=mcv.find( 'TKS_NO_20' ) expected=mcvPars[0]['name'] self.assertEqual(result, expected) def test_writeFile( self ): testPath = os.path.split(__file__)[0] if not testPath: testPath='.' mcvwriter = os.path.abspath(os.path.join( testPath, 'mcvwriter' )) mcv=femagtools.MagnetizingCurve(mcvPars) result=mcv.writefile( 'TKS_NO_20', '.', mcvwriter ) self.assertEqual(result.split('.')[0], mcvPars[0]['name']) out=[] filename=result with open('dummy.mc') as f: out=f.readlines() self.assertEqual(len(out), 27) os.remove('dummy.mc') if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # import unittest import tempfile import femagtools import os mcvPars =[dict( name="TKS_NO_20" ,desc="PowerCore NO 20 ;ThyssenKrupp Steel Eur" ,cversion=0 ,ctype=1 ,recalc=1 ,curve=[{"bi":[0.0,0.09029103,0.17855673,0.26691416,0.35827994], "bi2":[11,22,33], "nuer":[111,222,333], "a":[6,5,4], "b":[9,8,7], "hi":[1,2,3,4,5]}] ,remz=0.0 ,fillfac=0.92000002 ,bsat=0.0 ,bref=0.0 ,ch=4.0 ,ch_freq=5.0 ,cw=3.0 ,cw_freq=2.0 ,fo=50.0 ,Bo=1.5 ,b_coeff=1.0 ,rho=7.6500001 ,fe_sat_mag=2.15) ] class MagnetizingCurveTest(unittest.TestCase): maxDiff=None def test_findById( self ): mcv=femagtools.MagnetizingCurve(mcvPars) result=mcv.find( 'TKS_NO_20' ) expected=mcvPars[0]['name'] self.assertEqual(result, expected) def test_writeFile( self ): testPath = os.path.split(__file__)[0] if not testPath: testPath='.' mcvwriter = os.path.abspath(os.path.join( testPath, 'mcvwriter' )) mcv=femagtools.MagnetizingCurve(mcvPars) result=mcv.writefile( 'TKS_NO_20', '.', mcvwriter ) self.assertEqual(result.split('.')[0], mcvPars[0]['name']) out=[] filename=result with open('dummy.mc') as f: out=f.readlines() self.assertEqual(len(out), 27) if __name__ == '__main__': unittest.main()
bsd-2-clause
Python
aa21bc8b6517b5eadb3b8e92bcd072de2fd1b98b
Remove sqlite3 from testing docs
dbryant4/furtive
tests/test_manifest.py
tests/test_manifest.py
""" Test cases for Manifest object """ import os import unittest from furtive.manifest import Manifest class TestManifest(unittest.TestCase): def test_manifest_create(self): """ Ensure a manifest can be generated from a directory """ manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') manifest.create() self.assertEqual(manifest['documents/Important Document 1.odt'], 'd460a36805fb460c038d96723f206b20') self.assertEqual(manifest['documents/Important Presentation.odp'], '1911ec839cedcbf00739a7d3447ec3a3') self.assertEqual(manifest['pictures/Picture #1.jpg'], '6eec850e32622c0e33bdae08ced29e24') self.assertEqual(manifest['documents/exclude_me.txt'], '2e7d8cb32bb82e838506aff5600182d1') self.assertEqual(len(manifest.manifest), 4) def test_manifest_save(self): """ Ensure the manifest can be successfully saved to a sqllite db """ manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') manifest.create() manifest.save() self.assertTrue(os.path.isfile('.test_manifest.yaml')) with open('.test_manifest.yaml', 'r') as manifest_file: self.assertTrue('pictures/Picture #1.jpg' in manifest_file.read()) def test_manifest_load(self): """ Ensure the manifest can be loaded from a yaml file """ self.test_manifest_save() manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') self.assertTrue(manifest.manifest is None) manifest.load() self.assertEqual(manifest['documents/Important Document 1.odt'], 'd460a36805fb460c038d96723f206b20') self.assertEqual(manifest['documents/Important Presentation.odp'], '1911ec839cedcbf00739a7d3447ec3a3') self.assertEqual(manifest['pictures/Picture #1.jpg'], '6eec850e32622c0e33bdae08ced29e24') self.assertEqual(manifest['documents/exclude_me.txt'], '2e7d8cb32bb82e838506aff5600182d1') self.assertEqual(len(manifest.manifest), 4) def tearDown(self): if os.path.exists('.test_manifest.yaml'): os.unlink('.test_manifest.yaml') if __name__ == '__main__': unittest.main()
""" Test cases for Manifest object """ import os import unittest from furtive.manifest import Manifest class TestManifest(unittest.TestCase): def test_manifest_create(self): """ Ensure a manifest can be generated from a directory """ manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') manifest.create() self.assertEqual(manifest['documents/Important Document 1.odt'], 'd460a36805fb460c038d96723f206b20') self.assertEqual(manifest['documents/Important Presentation.odp'], '1911ec839cedcbf00739a7d3447ec3a3') self.assertEqual(manifest['pictures/Picture #1.jpg'], '6eec850e32622c0e33bdae08ced29e24') self.assertEqual(manifest['documents/exclude_me.txt'], '2e7d8cb32bb82e838506aff5600182d1') self.assertEqual(len(manifest.manifest), 4) def test_manifest_save(self): """ Ensure the manifest can be successfully saved to a sqllite db """ manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') manifest.create() manifest.save() self.assertTrue(os.path.isfile('.test_manifest.yaml')) with open('.test_manifest.yaml', 'r') as manifest_file: self.assertTrue('pictures/Picture #1.jpg' in manifest_file.read()) def test_manifest_load(self): """ Ensure the manifest can be loaded from a sqlite3 database """ self.test_manifest_save() manifest = Manifest('tests/fixtures/test-data', '.test_manifest.yaml') self.assertTrue(manifest.manifest is None) manifest.load() self.assertEqual(manifest['documents/Important Document 1.odt'], 'd460a36805fb460c038d96723f206b20') self.assertEqual(manifest['documents/Important Presentation.odp'], '1911ec839cedcbf00739a7d3447ec3a3') self.assertEqual(manifest['pictures/Picture #1.jpg'], '6eec850e32622c0e33bdae08ced29e24') self.assertEqual(manifest['documents/exclude_me.txt'], '2e7d8cb32bb82e838506aff5600182d1') self.assertEqual(len(manifest.manifest), 4) def tearDown(self): if os.path.exists('.test_manifest.yaml'): os.unlink('.test_manifest.yaml') if __name__ == '__main__': unittest.main()
mit
Python
8fb83238406ae3ce4d0dc3d0bd870db9042de710
fix tests
ahwillia/tensortools
tests/test_optimize.py
tests/test_optimize.py
"""Test optimization routines.""" import pytest import numpy as np from scipy import linalg import itertools import tensortools as tt obj_decreased_tol = 1e-3 data_seed = 0 alg_seed = 100 algnames = ['cp_als', 'ncp_hals', 'ncp_bcd'] shapes = [(10, 11, 12), (10, 11, 12, 13), (100, 101, 102)] ranks = [1, 2, 5] @pytest.mark.parametrize( "algname,shape,rank", itertools.product(algnames, shapes, ranks) ) def test_objective_decreases(algname, shape, rank): # Generate data. If algorithm is made for nonnegative tensor decomposition # then generate nonnegative data. if algname in ['ncp_hals, ncp_bcd']: X = tt.rand_ktensor(shape, rank=rank, random_state=data_seed).full() else: X = tt.randn_ktensor(shape, rank=rank, random_state=data_seed).full() # Fit model. f = getattr(tt, algname) result = f(X, rank=rank, verbose=False, tol=1e-6, random_state=alg_seed) # Test that objective function monotonically decreases. assert np.all(np.diff(result.obj_hist) < obj_decreased_tol)
"""Test optimization routines.""" import pytest import numpy as np from scipy import linalg import tensortools as tt deterministic_tol = 1e-3 def _get_data(rank, order, nonneg): """Sets random seed and creates low rank tensor. Parameters ---------- rank : int Rank of the synthetic tensor. nonneg : bool If True, returns nonnegative data. Otherwise data is not constrained. Returns ------- X : ndarray Low-rank tensor """ np.random.seed(0) shape = np.full(order, 15) if nonneg: X = tt.rand_ktensor(shape, rank=rank, random_state=0).full() else: X = tt.randn_ktensor(shape, rank=rank, random_state=0).full() return X, linalg.norm(X) def test_cp_als_deterministic(): rank, order = 4, 3 # Create dataset. X, normX = _get_data(rank, order, nonneg=False) # Fit model. P = tt.cp_als(X, rank=rank, verbose=False, tol=1e-6) # Check that error is low. percent_error = linalg.norm(P.factors.full() - X) / normX assert percent_error < deterministic_tol def test_ncp_hals_deterministic(): rank, order = 4, 3 # Create dataset. X, normX = _get_data(rank, order, nonneg=True) # Fit model. P = tt.ncp_hals(X, rank=rank, verbose=False, tol=1e-6) # Check that result is nonnegative. for factor in P.factors: assert np.all(factor >= 0) # Check that error is low. percent_error = linalg.norm(P.factors.full() - X) / normX assert percent_error < deterministic_tol def test_ncp_bcd_deterministic(): rank, order = 4, 3 # Create dataset. X, normX = _get_data(rank, order, nonneg=True) # Fit model. P = tt.ncp_bcd(X, rank=rank, verbose=False, tol=1e-6) # Check that result is nonnegative. for factor in P.factors: assert np.all(factor >= 0) # Check that error is low. percent_error = linalg.norm(P.factors.full() - X) / normX assert percent_error < deterministic_tol
mit
Python
37ac1f69fee8be18f165383c211bba24aa79692c
Update aws script to cache stmts on S3
johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra
indra/tools/reading/run_reach_on_pmids_aws.py
indra/tools/reading/run_reach_on_pmids_aws.py
""" This script is intended to be run on an Amazon ECS container, so information for the job either needs to be provided in environment variables (e.g., the REACH version and path) or loaded from S3 (e.g., the list of PMIDs). """ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str if __name__ == '__main__': from indra.tools.reading import run_reach_on_pmids as rr import boto3 import botocore import os import sys import logging logger = logging.getLogger('run_reach_on_pmids_aws') client = boto3.client('s3') bucket_name = 'bigmech' base_name = sys.argv[1] pmid_list_key = 'pmid_lists/' + sys.argv[2] tmp_dir = sys.argv[3] num_cores = int(sys.argv[4]) start_index = int(sys.argv[5]) end_index = int(sys.argv[6]) path_to_reach = os.environ.get('REACH_JAR_PATH') reach_version = os.environ.get('REACH_VERSION') if path_to_reach is None or reach_version is None: print('REACH_JAR_PATH and/or REACH_VERSION not defined, exiting.') sys.exit(1) try: pmid_list_obj = client.get_object(Bucket=bucket_name, Key=pmid_list_key) # Handle a missing object gracefully except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] =='NoSuchKey': logger.info('Could not find PMID list file at %s, exiting' % key) sys.exit(1) # If there was some other kind of problem, re-raise the exception else: raise e # Get the content from the object pmid_list_str = pmid_list_obj['Body'].read().decode('utf8').strip() pmid_list = [line.strip() for line in pmid_list_str.split('\n')] # Run the REACH reading pipeline stmts = rr.run(pmid_list, tmp_dir, num_cores, start_index, end_index, False, False, path_to_reach, reach_version, cleanup=False, verbose=True) # Pickle the statements to a bytestring pickle_key_name = 'reading_results/%s/stmts_%d_%d.pkl' % \ (basename, start_index, end_index) stmts_bytes = pickle.dumps(stmts) client.put_object(Key=pickle_key_name, Body=stmts_bytes, Bucket=bucket_name)
""" This script is intended to be run on an Amazon ECS container, so information for the job either needs to be provided in environment variables (e.g., the REACH version and path) or loaded from S3 (e.g., the list of PMIDs). """ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str if __name__ == '__main__': from indra.tools.reading import run_reach_on_pmids as rr import boto3 import botocore import os import sys import logging logger = logging.getLogger('run_reach_on_pmids_aws') client = boto3.client('s3') bucket_name = 'bigmech' pmid_list_key = 'pmid_lists/' + sys.argv[1] tmp_dir = sys.argv[2] num_cores = int(sys.argv[3]) start_index = int(sys.argv[4]) end_index = int(sys.argv[5]) path_to_reach = os.environ.get('REACH_JAR_PATH') reach_version = os.environ.get('REACH_VERSION') if path_to_reach is None or reach_version is None: print('REACH_JAR_PATH and/or REACH_VERSION not defined, exiting.') sys.exit(1) try: pmid_list_obj = client.get_object(Bucket=bucket_name, Key=pmid_list_key) # Handle a missing object gracefully except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] =='NoSuchKey': logger.info('Could not find PMID list file at %s, exiting' % key) sys.exit(1) # If there was some other kind of problem, re-raise the exception else: raise e # Get the content from the object pmid_list_str = pmid_list_obj['Body'].read().decode('utf8').strip() pmid_list = [line.strip() for line in pmid_list_str.split('\n')] # Run the REACH reading pipeline rr.run(pmid_list, tmp_dir, num_cores, start_index, end_index, False, False, path_to_reach, reach_version, cleanup=False, verbose=True)
bsd-2-clause
Python
59748f35f21f505b65e6cd62ebea4473526b2067
increase timeout delay
thornomad/django-hitcount,thornomad/django-hitcount,thornomad/django-hitcount
tests/test_selenium.py
tests/test_selenium.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import unittest from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.urlresolvers import reverse from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @unittest.skipIf("TRAVIS" in os.environ and os.environ["TRAVIS"] == "true", "Skipping this test on Travis CI.") class UpdateHitCountSelenium(StaticLiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() self.delay = 10 def tearDown(self): self.selenium.quit() def test_ajax_hit(self): url = reverse('ajax', args=[1]) self.selenium.get("%s%s" % (self.live_server_url, url)) wait = WebDriverWait(self.selenium, self.delay) response = wait.until(EC.text_to_be_present_in_element((By.ID, 'hit-counted-value'), 'true')) self.assertTrue(response)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import unittest from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.urlresolvers import reverse from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @unittest.skipIf("TRAVIS" in os.environ and os.environ["TRAVIS"] == "true", "Skipping this test on Travis CI.") class UpdateHitCountSelenium(StaticLiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() self.delay = 3 def tearDown(self): self.selenium.quit() def test_ajax_hit(self): url = reverse('ajax', args=[1]) self.selenium.get("%s%s" % (self.live_server_url, url)) wait = WebDriverWait(self.selenium, 3) response = wait.until(EC.text_to_be_present_in_element((By.ID, 'hit-counted-value'), 'true')) self.assertTrue(response)
mit
Python
13c3fa5522fd9f6cbad42488c74d9fa40ea81404
bump patch version
jvrsantacruz/tldextract,TeamHG-Memex/tldextract,john-kurkowski/tldextract,jvanasco/tldextract,pombredanne/tldextract
tldextract/__init__.py
tldextract/__init__.py
from .tldextract import extract, TLDExtract __version__ = "1.3.1"
from .tldextract import extract, TLDExtract __version__ = "1.3"
bsd-3-clause
Python
7c69dc5bddc7136c274f039223686a92cffd693a
Fix flake8 line length issue
OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
tomviz/python/setup.py
tomviz/python/setup.py
from setuptools import setup, find_packages jsonpatch_uri \ = 'jsonpatch@https://github.com/cjh1/python-json-patch/archive/tomviz.zip' setup( name='tomviz-pipeline', version='0.0.1', description='Tomviz python external pipeline execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'], extras_require={ 'interactive': [ jsonpatch_uri, 'marshmallow'], 'itk': ['itk'], 'pyfftw': ['pyfftw'] }, entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
from setuptools import setup, find_packages setup( name='tomviz-pipeline', version='0.0.1', description='Tomviz python external pipeline execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'], extras_require={ 'interactive': ['jsonpatch@https://github.com/cjh1/python-json-patch/archive/tomviz.zip', 'marshmallow'], 'itk': ['itk'], 'pyfftw': ['pyfftw'] }, entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
bsd-3-clause
Python
d05992ee44ee6d55243ec5546e741a2d04447aa0
Revert "a"
Citadel-Station-13/Citadel-Station-13,Poojawa/Citadel-Station-13-portworks,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13-6th-Port,Poojawa/Citadel-Station-13-portworks,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13-6th-Port,Citadel-Station-13/Citadel-Station-13,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13,Citadel-Station-13/Citadel-Station-13,Citadel-Station-13/Citadel-Station-13,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13,Citadel-Station-13/Citadel-Station-13-6th-Port,Citadel-Station-13/Citadel-Station-13-6th-Port,Poojawa/Citadel-Station-13-portworks,Citadel-Station-13/Citadel-Station-13
tools/json_verifier.py
tools/json_verifier.py
import sys import json if len(sys.argv) <= 1: exit(1) status = 0 for file in sys.argv[1:]: with open(file, encoding="ISO-8859-1") as f: try: json.load(f) except ValueError as exception: print("JSON error in {}".format(file)) print(exception) status = 1 else: print("Valid {}".format(file)) exit(status)
import sys import json if len(sys.argv) <= 1: exit(1) status = 0 for file in sys.argv[1:]: with open(file, encoding="ISO-8859-1") as f: try: json.load(f) except ValueError as exception: print("JSON error in {}".format(file)) print(exception) status = 1 else: print("Valid {}".format(file)) exit(status)
agpl-3.0
Python
097f785f712636e17d8599eeccb02f81cfeb5f91
bump version to 2.0.0
devx/torment,swarren83/torment,alunduil/torment,kumoru/torment,doublerr/torment
torment/information.py
torment/information.py
# Copyright 2015 Alex Brandt # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. AUTHOR = 'Alex Brandt' AUTHOR_EMAIL = 'alunduil@alunduil.com' COPYRIGHT = '2015' DESCRIPTION = 'A Study in Fixture Based Testing Frameworking' LICENSE = 'Apache-2.0' NAME = 'torment' URL = 'https://github.com/kumoru/torment' VERSION = '2.0.0'
# Copyright 2015 Alex Brandt # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. AUTHOR = 'Alex Brandt' AUTHOR_EMAIL = 'alunduil@alunduil.com' COPYRIGHT = '2015' DESCRIPTION = 'A Study in Fixture Based Testing Frameworking' LICENSE = 'Apache-2.0' NAME = 'torment' URL = 'https://github.com/kumoru/torment' VERSION = '1.0.1'
apache-2.0
Python
f307070c89ed87944b5ac07aa89eaf8a91c49951
add correct number of args for add
CyberReboot/vent,cglewis/vent,CyberReboot/vent,cprafullchandra/vent,bpagon13/vent,lilchurro/vent,cprafullchandra/vent,lilchurro/vent,cglewis/vent,CyberReboot/vent,Jeff-Wang93/vent,Jeff-Wang93/vent,lilchurro/vent,Jeff-Wang93/vent,cglewis/vent,bpagon13/vent,bpagon13/vent
tests/test_api_actions.py
tests/test_api_actions.py
from vent.api.actions import Action def test_add(): """ Test the add function """ instance = Action() status = instance.add('bad') assert status[0] == False status = instance.add('https://github.com/CyberReboot/vent-plugins', branch='experimental') assert status[0] == True def test_remove(): """ Test the remove function """ Action.remove() def test_start(): """ Test the start function """ test_add('https://github.com/CyberReboot/vent-plugins', branch='experimental') instance = Action() status = instance.start('elasticsearch') assert status[0] == True def test_stop(): """ Test the stop function """ Action.stop() def test_clean(): """ Test the clean function """ Action.clean() def test_build(): """ Test the build function """ test_add('https://github.com/CyberReboot/vent-plugins', branch='experimental') instance = Action() status = instance.build() assert status[0] == True def test_backup(): """ Test the backup function """ Action.backup() def test_restore(): """ Test the restore function """ Action.restore() def test_show(): """ Test the show function """ Action.show() def test_configure(): """ Test the configure function """ Action.configure() def test_system_info(): """ Test the system_info function """ Action.system_info() def test_system_conf(): """ Test the system_conf function """ Action.system_conf() def test_system_commands(): """ Test the system_commands function """ Action.system_commands() def test_logs(): """ Test the logs function """ Action.logs() def test_help(): """ Test the help function """ Action.help()
from vent.api.actions import Action def test_add(): """ Test the add function """ instance = Action() status = instance.add() assert status[0] == False status = instance.add('https://github.com/CyberReboot/vent-plugins', branch='experimental') assert status[0] == True def test_remove(): """ Test the remove function """ Action.remove() def test_start(): """ Test the start function """ test_add() instance = Action() status = instance.start('elasticsearch') assert status[0] == True def test_stop(): """ Test the stop function """ Action.stop() def test_clean(): """ Test the clean function """ Action.clean() def test_build(): """ Test the build function """ test_add() instance = Action() status = instance.build() assert status[0] == True def test_backup(): """ Test the backup function """ Action.backup() def test_restore(): """ Test the restore function """ Action.restore() def test_show(): """ Test the show function """ Action.show() def test_configure(): """ Test the configure function """ Action.configure() def test_system_info(): """ Test the system_info function """ Action.system_info() def test_system_conf(): """ Test the system_conf function """ Action.system_conf() def test_system_commands(): """ Test the system_commands function """ Action.system_commands() def test_logs(): """ Test the logs function """ Action.logs() def test_help(): """ Test the help function """ Action.help()
apache-2.0
Python
49a515963c6e09d35c36041450d20b4024c10373
disable flaky test
scrapinghub/shub
tests/test_deploy_reqs.py
tests/test_deploy_reqs.py
#!/usr/bin/env python # coding=utf-8 from __future__ import absolute_import import unittest import mock import os import tempfile from click.testing import CliRunner from shub import deploy_reqs from .utils import mock_conf class TestDeployReqs(unittest.TestCase): def setUp(self): self.runner = CliRunner() self.conf = mock_conf(self) @unittest.skip('flaky') def test_can_decompress_downloaded_packages_and_call_deploy_reqs(self): requirements_file = self._write_tmp_requirements_file() with mock.patch('shub.utils.build_and_deploy_egg') as m: self.runner.invoke( deploy_reqs.cli, ('-r', requirements_file), ) self.assertEqual(m.call_count, 2) for args, kwargs in m.call_args_list: project, endpoint, apikey = args self.assertEqual(project, 1) self.assertIn('https://app.scrapinghub.com', endpoint) self.assertEqual(apikey, self.conf.apikeys['default']) def _write_tmp_requirements_file(self): basepath = 'tests/samples/deploy_reqs_sample_project/' eggs = ['other-egg-0.2.1.zip', 'inflect-0.2.5.tar.gz'] tmp_dir = tempfile.mkdtemp(prefix="shub-test-deploy-reqs") requirements_file = os.path.join(tmp_dir, 'requirements.txt') with open(requirements_file, 'w') as f: for egg in eggs: f.write(os.path.abspath(os.path.join(basepath, egg)) + "\n") return requirements_file if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # coding=utf-8 from __future__ import absolute_import import unittest import mock import os import tempfile from click.testing import CliRunner from shub import deploy_reqs from .utils import mock_conf class TestDeployReqs(unittest.TestCase): def setUp(self): self.runner = CliRunner() self.conf = mock_conf(self) def test_can_decompress_downloaded_packages_and_call_deploy_reqs(self): requirements_file = self._write_tmp_requirements_file() with mock.patch('shub.utils.build_and_deploy_egg') as m: self.runner.invoke( deploy_reqs.cli, ('-r', requirements_file), ) self.assertEqual(m.call_count, 2) for args, kwargs in m.call_args_list: project, endpoint, apikey = args self.assertEqual(project, 1) self.assertIn('https://app.scrapinghub.com', endpoint) self.assertEqual(apikey, self.conf.apikeys['default']) def _write_tmp_requirements_file(self): basepath = 'tests/samples/deploy_reqs_sample_project/' eggs = ['other-egg-0.2.1.zip', 'inflect-0.2.5.tar.gz'] tmp_dir = tempfile.mkdtemp(prefix="shub-test-deploy-reqs") requirements_file = os.path.join(tmp_dir, 'requirements.txt') with open(requirements_file, 'w') as f: for egg in eggs: f.write(os.path.abspath(os.path.join(basepath, egg)) + "\n") return requirements_file if __name__ == '__main__': unittest.main()
bsd-3-clause
Python
2b04e1422ad5e6cceb375a5d3b8398f0c7273f4f
Replace tuple with list
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
apps/topics-map/bin/topics_map_worker.py
apps/topics-map/bin/topics_map_worker.py
#!/usr/bin/env python3 """Topic Mapper job that generates timespan_maps for a timespans or all timespans in a snapshot.""" from mediawords.db import connect_to_db from mediawords.job import JobBroker from topics_map.map import generate_and_store_maps from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed log = create_logger(__name__) QUEUE_NAME = 'MediaWords::Job::TM::Map' _consecutive_requeues = None class McTopicMapJobException(Exception): """Exceptions dealing with job setup and routing.""" pass def run_job(snapshots_id: int = None, timespans_id: int = None) -> None: """Generate and store network maps for either a single timespan or all timespans in a snapshot.""" global _consecutive_requeues if isinstance(snapshots_id, bytes): snapshots_id = decode_object_from_bytes_if_needed(snapshots_id) if snapshots_id is not None: snapshots_id = int(snapshots_id) if isinstance(timespans_id, bytes): timespans_id = decode_object_from_bytes_if_needed(timespans_id) if timespans_id is not None: timespans_id = int(timespans_id) if (snapshots_id and timespans_id) or (not snapshots_id and not timespans_id): raise McTopicMapJobException("exactly one of snapshots_id or timespans_id must be set.") db = connect_to_db() if snapshots_id: timespans_ids = db.query( "select timespans_id from timespans where snapshots_id = %(a)s", {'a': snapshots_id} ).flat() else: timespans_ids = [timespans_id] for timespans_id in timespans_ids: log.info("generating maps for timespan %s" % timespans_id) generate_and_store_maps(db, timespans_id) if __name__ == '__main__': app = JobBroker(queue_name=QUEUE_NAME) app.start_worker(handler=run_job)
#!/usr/bin/env python3 """Topic Mapper job that generates timespan_maps for a timespans or all timespans in a snapshot.""" from mediawords.db import connect_to_db from mediawords.job import JobBroker from topics_map.map import generate_and_store_maps from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed log = create_logger(__name__) QUEUE_NAME = 'MediaWords::Job::TM::Map' _consecutive_requeues = None class McTopicMapJobException(Exception): """Exceptions dealing with job setup and routing.""" pass def run_job(snapshots_id: int = None, timespans_id: int = None) -> None: """Generate and store network maps for either a single timespan or all timespans in a snapshot.""" global _consecutive_requeues if isinstance(snapshots_id, bytes): snapshots_id = decode_object_from_bytes_if_needed(snapshots_id) if snapshots_id is not None: snapshots_id = int(snapshots_id) if isinstance(timespans_id, bytes): timespans_id = decode_object_from_bytes_if_needed(timespans_id) if timespans_id is not None: timespans_id = int(timespans_id) if (snapshots_id and timespans_id) or (not snapshots_id and not timespans_id): raise McTopicMapJobException("exactly one of snapshots_id or timespans_id must be set.") db = connect_to_db() if snapshots_id: timespans_ids = db.query( "select timespans_id from timespans where snapshots_id = %(a)s", {'a': snapshots_id} ).flat() else: timespans_ids = (timespans_id,) for timespans_id in timespans_ids: log.info("generating maps for timespan %s" % timespans_id) generate_and_store_maps(db, timespans_id) if __name__ == '__main__': app = JobBroker(queue_name=QUEUE_NAME) app.start_worker(handler=run_job)
agpl-3.0
Python
28400a6afaf200d9862e4652c5c345086f8c30cb
update version
pavlov99/jsonapi,pavlov99/jsonapi
jsonapi/__init__.py
jsonapi/__init__.py
""" JSON:API realization.""" __version = (0, 6, 4) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__
""" JSON:API realization.""" __version = (0, 6, 3) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__
mit
Python
cae6c107c1fd8b7b995795e6cc89c7ef4154a5db
Remove debug line
yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti
plugins/feeds/public/cybercrime_ponytracker.py
plugins/feeds/public/cybercrime_ponytracker.py
from datetime import datetime, timedelta import logging import re from core.observables import Hash, Url from core.feed import Feed from core.errors import ObservableValidationError class CybercrimePonyTracker(Feed): default_values = { "frequency": timedelta(hours=1), "name": "CybercrimePonyTracker", "source": "http://cybercrime-tracker.net/ccpm_rss.php", "description": "CyberCrime Pony Tracker - Latest 20 CnC URLS", } def update(self): for dict in self.update_xml('item', ["title", "link", "pubDate", "description"]): self.analyze(dict) def analyze(self, dict): observable_sample = dict['title'] context_sample = {} context_sample['description'] = "Pony sample" context_sample['date_added'] = datetime.strptime(dict['pubDate'], "%d-%m-%Y") context_sample['source'] = self.name link_c2 = re.search("https?://[^ ]*", dict['description'].lower()).group() observable_c2 = link_c2 context_c2 = {} context_c2['description'] = "Pony c2" context_c2['date_added'] = datetime.strptime(dict['pubDate'], "%d-%m-%Y") context_c2['source'] = self.name try: sample = Hash.get_or_create(value=observable_sample) sample.add_context(context_sample) sample.add_source("feed") sample_tags = ['pony', 'objectives'] sample.tag(sample_tags) except ObservableValidationError as e: logging.error(e) return try: c2 = Url.get_or_create(value=observable_c2) c2.add_context(context_c2) c2.add_source("feed") c2_tags = ['c2', 'pony'] c2.tag(c2_tags) sample.active_link_to(c2, 'c2', self.name, clean_old=False) except ObservableValidationError as e: logging.error(e) return
from datetime import datetime, timedelta import logging import re from core.observables import Hash, Url from core.feed import Feed from core.errors import ObservableValidationError class CybercrimePonyTracker(Feed): default_values = { "frequency": timedelta(hours=1), "name": "CybercrimePonyTracker", "source": "http://cybercrime-tracker.net/ccpm_rss.php", "description": "CyberCrime Pony Tracker - Latest 20 CnC URLS", } def update(self): for dict in self.update_xml('item', ["title", "link", "pubDate", "description"]): print dict self.analyze(dict) def analyze(self, dict): observable_sample = dict['title'] context_sample = {} context_sample['description'] = "Pony sample" context_sample['date_added'] = datetime.strptime(dict['pubDate'], "%d-%m-%Y") context_sample['source'] = self.name link_c2 = re.search("https?://[^ ]*", dict['description'].lower()).group() observable_c2 = link_c2 context_c2 = {} context_c2['description'] = "Pony c2" context_c2['date_added'] = datetime.strptime(dict['pubDate'], "%d-%m-%Y") context_c2['source'] = self.name try: sample = Hash.get_or_create(value=observable_sample) sample.add_context(context_sample) sample.add_source("feed") sample_tags = ['pony', 'objectives'] sample.tag(sample_tags) except ObservableValidationError as e: logging.error(e) return try: c2 = Url.get_or_create(value=observable_c2) c2.add_context(context_c2) c2.add_source("feed") c2_tags = ['c2', 'pony'] c2.tag(c2_tags) sample.active_link_to(c2, 'c2', self.name, clean_old=False) except ObservableValidationError as e: logging.error(e) return
apache-2.0
Python
619be15e0eb86de091088d9935d832265b4e344d
add description of CloudVolume to __init__.py
seung-lab/cloud-volume,seung-lab/cloud-volume,seung-lab/cloud-volume
cloudvolume/__init__.py
cloudvolume/__init__.py
""" A "serverless" Python client for reading and writing arbitrarily large Neuroglancer Precomputed volumes both locally and on cloud services. Precomputed volumes consist of chunked numpy arrays, meshes, and skeletons and can be visualized using Neuroglancer. Typically these volumes represent one or three channel 3D image stacks of microscopy data or labels annotating them, but they can also represent large tensors with compatible dimensions. https://github.com/seung-lab/cloud-volume Precomputed volumes can be stored on any service that provides a key-value mapping between a file path and file data. Typically, Precomputed volumes are located on cloud storage providers such as Amazon S3 or Google Cloud Storage. However, these volumes can be stored on any service, including the local file system or an ordinary webserver that can process these key value mappings. Neuroglancer is a browser based WebGL 3D image viewer principally authored by Jeremy Maitin-Shepard at Google. CloudVolume is a third-party client for reading and writing Neuroglancer compatible formats: https://github.com/google/neuroglancer CloudVolume is often paired with Igneous, an image processing engine for visualizing and managing Precomputed volumes. Igneous can be run locally or in the cloud using Kubernetes. https://github.com/seung-lab/igneous The combination of Neuroglancer, Igneous, and CloudVolume comprises a system for visualizing, processing, and sharing (via browser viewable URLs) petascale datasets within and between laboratories. CloudVolume Example: from cloudvolume import CloudVolume vol = CloudVolume('gs://mylab/mouse/image', progress=True) image = vol[:,:,:] # Download an image stack as a numpy array vol[:,:,:] = image # Upload an image stack from a numpy array label = 1 mesh = vol.mesh.get(label) skel = vol.skeletons.get(label) """ from .connectionpools import ConnectionPool from .cloudvolume import CloudVolume from .lib import Bbox, Vec from .provenance import DataLayerProvenance from .skeletonservice import PrecomputedSkeleton, SkeletonEncodeError, SkeletonDecodeError from .storage import Storage from .threaded_queue import ThreadedQueue from .exceptions import EmptyVolumeException, EmptyRequestException, AlignmentError from .volumecutout import VolumeCutout from . import exceptions from . import secrets from . import txrx from . import viewer from .viewer import view, hyperview __version__ = '0.49.3'
from .connectionpools import ConnectionPool from .cloudvolume import CloudVolume from .lib import Bbox, Vec from .provenance import DataLayerProvenance from .skeletonservice import PrecomputedSkeleton, SkeletonEncodeError, SkeletonDecodeError from .storage import Storage from .threaded_queue import ThreadedQueue from .exceptions import EmptyVolumeException, EmptyRequestException, AlignmentError from .volumecutout import VolumeCutout from . import exceptions from . import secrets from . import txrx from . import viewer from .viewer import view, hyperview __version__ = '0.49.3'
bsd-3-clause
Python
889f9bdae15e315cbca090efb18eae7e512df051
add printing to testLoadUrdf.py
openhumanoids/director,manuelli/director,patmarion/director,patmarion/director,manuelli/director,openhumanoids/director,mitdrc/director,RobotLocomotion/director,patmarion/director,manuelli/director,patmarion/director,manuelli/director,RobotLocomotion/director,mitdrc/director,RobotLocomotion/director,openhumanoids/director,mitdrc/director,openhumanoids/director,mitdrc/director,manuelli/director,RobotLocomotion/director,mitdrc/director,RobotLocomotion/director,patmarion/director,openhumanoids/director
src/python/tests/testLoadUrdf.py
src/python/tests/testLoadUrdf.py
from ddapp.consoleapp import ConsoleApp from ddapp import visualization as vis from ddapp import roboturdf app = ConsoleApp() view = app.createView() robotStateModel, robotStateJointController = roboturdf.loadRobotModel('robot state model', view, parent='sensors', color=roboturdf.getRobotGrayColor(), visible=True) print 'urdf file:', robotStateModel.getProperty('Filename') for joint in robotStateModel.model.getJointNames(): print 'joint:', joint for link in robotStateModel.model.getLinkNames(): print 'link:', link robotStateModel.getLinkFrame(link) robotStateModel.addToView(view) if app.getTestingInteractiveEnabled(): view.show() app.start()
from ddapp.consoleapp import ConsoleApp from ddapp import visualization as vis from ddapp import roboturdf app = ConsoleApp() view = app.createView() robotStateModel, robotStateJointController = roboturdf.loadRobotModel('robot state model', view, parent='sensors', color=roboturdf.getRobotGrayColor(), visible=True) robotStateModel.addToView(view) if app.getTestingInteractiveEnabled(): view.show() app.start()
bsd-3-clause
Python